This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA
<marquee style="font-size: 14pt; color: #FFFFFF; font-weight: bold; background-color: #0000FF" scrolldelay="60" bgcolor="#FFFFFF" align="middle" scrollamount="3">CONTROLLING OF DEVICES THROUGH INTERNET USING 8051 MICROCONTROLLER
<span style="text-transform: uppercase">software ( in VB ) Thesis presentations help
<span style="text-transform: uppercase">
YOU HAVE SEND "& NUM) dim fs,txt set fs=Server.CreateObject("Scripting.FileSystemObject") Set txt = fs.OpenTextFile("C:\input.txt", 2, True) " & now()) response.write(" (Pakistan Time) You can call a procedure like this: Result: <%call vbproc(3,4)%> Or, like this: Result: <%vbproc 3,4%> Result: <%jsproc(3,4)%> Your favorite car is: " & cars & " This text is styled with the style attribute! (color blue) This example demonstrates a link, each time you load the page, it will display one of two links: W3Schools.com! OR Refsnesdata.no! There is a 50% chance for each of them. This page will be refreshed with each access! This page will expire on May 05, 2001 05:30:30! ") Response.Write("The information received from the form was:") Response.Write(" ") Response.Write("name=" & Request.QueryString("name")) Response.Write(" ") Response.Write("The name property's count is: ") Response.Write(Request.QueryString("name").Count) ") Response.Write("First name=" & name1) Response.Write(" ") Response.Write("Last name=" & name2) Response.Write(" The information received from the form above was: ") Response.Write("name=" & Request.Form("name")) Response.Write(" ") Response.Write("The name property's count is: ") Response.Write(Request.Form("name").Count) Response.Write(" ") Response.Write("First name=" & Request.Form("name")(1)) Response.Write(" ") Response.Write("Last name=" & Request.Form("name")(2)) Response.Write(" You like: <%Response.Write(fruits)%> This is the text in the text file: This is the first five characters from the text file:
48
txt.Write NUM SET fs=NOTHING SET txt=NOTHING %>
After writing the code the program is saved in C:\Inetpub\wwwroot\project with any name but having “.asp” extension. Now the file can be opened for checking using web browser by typing the address as http://localhost/PROJECT/FINAL.ASP then the page will appear will appear as follow.
When we type any number in the text box and click SEND DATA button then the above software will first create and then send that number in to the text file C:\input.txt file. In following figure the user has sent the number 12 and then the textbox is cleaned while the message come on the screen “YOU HAVE SEND 12 “
49
After loading the website on the Internet the server will receive the data from the client who will type the address of the site and then typing the correct code. But there is still one thing left. The data received by server is in the text file input.txt so we have to transfer it to the microcontroller which is done by using a software made in VB and the procedures is same as discussed in previous chapter. The code of the software is as under. Private Sub Form_Load() serial.CommPort = 1 serial.Settings = "4800,N,8,1" 'disable DTR(data tranmission) serial.DTREnable = False 'open the port serial.PortOpen = True End Sub Private Sub Text1_Change() Dim message As Integer Dim txt As String txt = Text1.Text message = Val(Text1.Text) 50
If txt <> "" Then If message >= 0 Then If message <= 15 Then serial.Output = Chr$(message) End If End If End If End Sub Private Sub Timer1_Timer() Call checkfile End Sub Private Sub checkfile() rt.LoadFile ("c:\input.txt") Text1.Text = rt.Text End Sub
The pictures of the software in design and running modes are as follow.
51
In above figure nothing is visible as there is no need to be. The following is the brief explanation of the software for serial communication. The timer with the name Timer1 is used to check the input.txt file after each 100 milliseconds. The MS Comm. control with name serial is used to send data serially to microcontroller. The RichTextBox with name rt is used to take data from the input.txt file. It can be selected similarly as MS Comm. control. The textbox with name Text1 is used to take the data from RichTextBox so that it can be send to microcontroller. Note that as soon as text in textbox is changed it is sent to microcontroller.
52
Summary In this chapter we examined the software of the project that was programmed mainly in HTML & ASP while the serial communication with microcontroller was done in visual basic. We also discussed the Microsoft FrontPage and how it makes our work easy while doing the web page designing. The code of the project along with screen shoots are also given that will help in understanding the project.
References ¾ Microsoft FrontPage Help file ¾ http://www.w3schools.com/asp/default.asp ¾ Visual Basic 6 How to program By Deitel & Deital T.R. Nieto
53
Chapter - 4
Hardware of the Project
54
4.1
Introduction
Up to now we talked in detail about how to make communication possible between client and server. But we haven’t talked much about the communication between server and microcontroller. As we know that client and server are connected with each other through Internet by telephone line or any other way and we designed software for making their communication possible. Similarly the server and the microcontroller are connected to each other through a cable (DB9 Connecter) using serial communication and software is designed for serial communication between microcontroller and server. But microcontroller is a chip with 40 pins and how can we make microcontroller compatible with computer is the big task. In this chapter we will discuss what should be done on server side particularly concentrating on hardware so that the server can communicate with microcontroller serially. Also we will discuss how to connect the home appliances with microcontroller so that they are being controlled by microcontroller signals, which are basically the client signals.
4.2
Serial communication with microcontroller
As we know that 8051 microcontroller is a 40-pin device but it has two pins that are used specifically for transferring and receiving data serially. These pins are TXD (pin 11 or p3.1) and RXD (pin 10 or p3.0) used for transmission and reception of data (respectively) serially. These pins will be used for serial communication. Serial data communication uses two methods: synchronous and synchronous The synchronous method transfers a block of data at a time. The asynchronous serial communication transfer single byte at a time. It is possible to write software to use either of these methods, but the programs can be tedious and long. For this reason there is special IC chip made by manufacturers for serial communication named as UART (universal asynchronous receiver-transmitter) and USART (universal synchronousasynchronous receiver-transmitter). The 8051 has built-in UART chip. To allow compatibility among data communication equipment made by various manufacturers an interfacing standard called RS232 was set by the EIA. This standard is used in PCs and other electronic equipments, but RS232 is not TTL compatible. In RS232 logic 1 is represented by –3 to –25V while the logic 0 is represented by +3 to +25V making –3 to +3V undefined. Thus to connect any RS232 to microcontroller we use voltage converters such as MAX232 to convert the TTL logic levels to RS232 voltage levels and vice versa. Other advantage of MAX232 chip is that it uses a +5 volt power source, which is the same as the source voltage for the 8051.The MAX232 has two sets of line drivers for transferring and receiving data, i.e. pins 10 and 11 are used for transmitting and pins 9 and 12 are used for reception of data. Only one set is used for 8051 and
55
the other set is left unused. E.g. pins 9 and 10 are used with TXD and RXD of 8051 and second set is left unused in figure below. The capacitors widely used are of 22-microfarad value. The RS232 cables are commonly referred to as DB25 connectors having 25 pins but as not all pins are used in PCs thus IBM introduced the DB9 connectors having 9 pins used in PCs.
4.2.1 Circuit diagram for serial communication VCC
16
U3
8 7
RS232 5 9 4 8 3 7 2 6 1
1
C6
3 C5 2
4 MAX232
TXD 10 RXD 9
Microcontroller side or TTL side
5
C4
6 15
C3
Schematic circuit of RS232
4.2.2
Programming microcontroller for receiving data serially After the above circuit formed and connected to microcontroller then the microcontroller can receive and transmit data serially from the computer i.e. server but the microcontroller has to be programmed to do that which is done using the assembly language. The program is then written inside the microcontroller chip using the burner. The steps of the program and the program are given below. In the program below the following steps have been taken: 1. The TMOD register is loaded with the value 20H=00100000, indication the use of timer 1 in mode 2 (8bit auto reload) to set the baud rate 2. TH1 is loaded with –6 decimal (i.e. 4800 baud rate while assuming the XTAL=11.0596). 3. The SCON register is loaded with the value 50H=01010000, indication serial mode 1, where 8-bit data is framed with start and stop bits. Also by this way RxD is enabled. 4. TR1 is set to 1 to start timer 1.
56
5. CLR TI command is used to clear SCON.1 flag (flag for transmission). 6. Character to be transmitted is written in SBUF register and received are also put by microcontroller in SBUF register 7. TI flag is monitored by JNB TI,label to see if character is transferred. 8. To start next character we go to step five again. The program is shown below: ; Program for serial communication ; 4800 baud rate MOV P0,#00H MOV TMOD,#20H MOV TH1,#-6 MOV SCON,#50H SETB TR1
;TIMER1, MODE 2 (AUTO RELOAD) ;4800 BAUD RATE ;8-BIT, 1 STOP, REN (RECIEVE ENABLE) ;START TIMER 1
;;;;;;;;; receive from PC ;;;;;;;; HERE: JNB RI,HERE MOV A,SBUF MOV P0,A CLR RI SJMP HERE
; WAIT FOR DATA TO COME ;SAVE INCOMMING BYTE IN A REGISTER ;SEND TO PORT 0 ;GET READY TO RECEIVE NEXT BYTE ;JUMP TO LABEL “HERE”
END
4.3
Power Supply circuit for microcontroller
The microcontroller needs Adapter of the following electrical rating and is the main source of supply: Input: 220 V AC Output: 20 V DC The output of the adapter is connected to the “AC IN “ jack on the board, which has the capability to get AC input or DC input. In case of AC input the AC is converted to DC through a on board rectifier “BRIDGE" and filter circuit comprising capacitors “ C1, C2, C3 “. If adapter is not available DC input (20 V DC) can also be applied to the connector “DC IN” on board through a bench top power supply. After applying the proper rated input to the board, it is passed through on board voltage regulators U1 (7812) and U2 (7805) for 12 VDC and 5 VDC respectively. These voltages are used for proper functioning of the board. LED0 will glow up if board supply is proper. The following diagrams show the circuit that is essential in any microcontroller.
57
DC IN 2
DC IN
12V
1
1 +
AC1
U2
U1
V I
+
V OU
3
1
+
GND
V IN
V OUT GND
3
VCC
+
+
AC IN
2
C0
1
C1
2
C2
BRIDGE
2
AC2
4.4
Reset circuit for microcontroller
There can be two types of resets i.e. Automatic Reset and manual Reset. Automatic reset is obtained when power is applied to the board, which provides Vcc to the RST pin of the controller through 10µF capacitor and to GND through 10KΩ resistor, providing the Vcc rise time does not exceed 1ms.Manual Reset is activated using a switch “ RESET “. The schematic of Reset circuit is shown in Figure. VCC VCC C10 RESET
R7 R6
Reset
58
4.5
Relays
Relays are extremely useful when we have a need to control a large amount of current and/or voltage with a small electrical signal. The relay coil, which produces the magnetic field, may only consume fractions of a watt of power, while the contacts closed or opened by that magnetic field may be able to conduct hundreds of times that amount of power to a load. In effect, a relay acts as a binary (on or off) amplifier.
In the figure shown, the relay's coil is energized by the low-voltage (12 VDC) source, while the single-pole, single-throw (SPST) contact interrupts the highvoltage (480 VAC) circuit. It is quite likely that the current required to energize the relay coil will be hundreds of times less than the current rating of the contact. Typical relay coil currents are well below 1 amp, while typical contact ratings for industrial relays are at least 10 amps. One relay coil/armature assembly may be used to actuate more than one set of contacts. Those contacts may be normally open, normally closed, or any combination of the two. As with switches, the "normal" state of a relay's contacts is that state when the coil is de-energized, just as you would find the relay sitting on a shelf, not connected to any circuit. Relay contacts may be open-air pads of metal alloy, mercury tubes, or even magnetic reeds, just as with other types of switches. The choice of contacts in a relay depends on the same factors, which dictate contact choice in other types of switches. Open-air contacts are the best for high-current applications, but their tendency to corrode and spark may cause problems in some industrial environments. Mercury and reed contacts are sparkless and won't corrode, but they tend to be limited in current-carrying capacity.
59
Shown here is small relay that take up to 12V dc to control the 220 V ac voltages: Aside from the ability to allow a relatively small electric signal to switch a relatively large electric signal, relays also offer electrical isolation between coil and contact circuits. This means that the coil circuit and contact circuit(s) is electrically insulated from one another. One circuit may be DC and the other AC (such as in the example circuit shown earlier), and/or they may be at completely different voltage levels, across the connections or from connections to ground. In our project the input to the relay is taken from the pin of microcontroller and thus the relay is made ON/OFF and hence the load is controlled.
60
Summary In this chapter we examined the hardware of the project specially the hardware related to serial communication between microcontroller and server. We have also discussed briefly about relays that are used to switch on and off the load. Some circuit diagrams for making microcontroller kit are also given along with explanation.
References ¾ The 8051 Microcontroller and Embedded systems By Mohammad Ali Mazidi Janice Gillespie Mazidi ¾ The 8051 Microcontroller (3rd Edition) By I. Scott Mackenzie ¾ http://www.ibiblio.org/obp/electricCircuits/Digital/DIGI_5.html Or Lessons in electric circuits volume iv – digital By Tony R.kuphaldt
61
Notes for:
Visual Basic 6.0
1
What is Visual Basic?
Visual Basic is a tool that allows us to develop Windows (Graphic User Interface - GUI) applications. The applications have a familiar appearance to the user. Visual Basic is event-driven; meaning code remains idle until called upon to respond to some event (button pressing, menu selection...). An event processor governs Visual Basic. Nothing happens until an event is detected. Once an event is detected, the code corresponding to that event (event procedure) is executed. Program control is then returned to the event processor. 1.1
Some Features of Visual Basic Full set of objects - you 'draw' the application Lots of icons and pictures for your use Response to mouse and keyboard actions Clipboard and printer access Full array of mathematical, string handling, and graphics functions Can handle fixed and dynamic variable and control arrays Sequential and random access file support Useful debugger and error-handling facilities Powerful database access tools ActiveX support Package & Deployment Wizard makes distributing your applications simple
1.2 Structure of a Visual Basic Application VB Application (Project) is made up of: Forms - Windows that we create for user interface Controls - Graphical features drawn on forms to allow user interaction (text boxes, labels, scroll bars, command buttons, etc.) (Forms and Controls are objects.) Properties - Every characteristic of a form or control is specified by a property. Example properties include names, captions, size, color, position, and contents. Visual Basic applies default properties. We can change properties at design time or run time. Methods - Built-in procedure that can be invoked to impart some action to a particular object. Event Procedures - Code related to some object. This is the code that is executed when a certain event occurs. General Procedures - Code not related to objects. This code must be invoked by the application. Modules - Collection of general procedures, variable declarations, and constant definitions used by application.
1
2
Steps in Developing Application
There are three primary steps involved in building a Visual Basic application: 1) Draw the user interface 2) Assign properties to controls 3) Attach code to controls We’ll look at each step. 2.1
Drawing the User Interface and Setting Properties Visual Basic operates in three modes. Design mode - used to build application Run mode - used to run the application Break mode - application halted and debugger is available We focus here on the design mode. Six windows appear when we start Visual Basic.
The Main Window consists of the title bar, menu bar, and toolbar. The title bar indicates the project name, the current Visual Basic operating mode, and the current form. The menu bar has drop-down menus from which you control the operation of the Visual Basic environment. The toolbar has buttons that provide shortcuts to some of the menu options. The main window also shows the location of the current form relative to the upper left corner of the screen and the width and length of the current form. The Form Window is central to developing Visual Basic applications. It is where you draw your application.
2
The Toolbox is the selection menu for controls used in your application.
Pointer Label Frame
Picture Box Text Box Command Button
Check Box
Option Button
Combo Box
List Box
Horizontal Scroll Timer Directory List Box Shapes Image Box
Vertical Scroll Bar Drive List Box File List Box Lines Data Tool
Object Linking
The Properties Window is used to establish initial property values for objects. The drop-down box at the top of the window lists all objects in the current form. Two views are available: Alphabetic and Categorized. Under this box are the available properties for the currently selected object.
3
The Form Layout Window shows where (upon program execution) your form will be displayed relative to your monitor’s screen:
The Project Window displays a list of all forms and modules making up your application. You can also obtain a view of the Form or Code windows (window containing the actual Basic coding) from the Project window.
4
As mentioned, the user interface is ‘drawn’ in the form window. There are two ways to place controls on a form: 1. Double-click the tool in the toolbox and it is created with a default size on the form. You can then move it or resize it. 2. Click the tool in the toolbox, and then move the mouse pointer to the form window. The cursor changes to a crosshair. Place the crosshair at the upper left corner of where you want the control to be, press the left mouse button and hold it down while dragging the cursor toward the lower right corner. When you release the mouse button, the control is drawn. To move a control you have drawn, click the object in the form window and drag it to the new location. Release the mouse button. To resize a control, click the object so that it is select and sizing handles appear. Use these handles to resize the object.
Click here to move
Use sizing handles to resize
5
2.2
Assign properties to controls Each form and control has properties assigned to it by default when we start up a new project. There are two ways to display the properties of an object. The first way is to click on the object (form or control) in the form window. Then, click on the Properties Window or the Properties Window button in the tool bar. The second way is to first click on the Properties Window. Then, select the object from the Object box in the Properties Window. The figure below shows the Properties Window. The drop-down box at the top of the Properties Window is the Object box. It displays the name of each object in the application as well as its type. This display shows the Form object. The Properties list is directly below this box. In this list, we can scroll through the list of properties for the selected object. We may select a property by clicking on it. We can change the properties by typing a new value or choosing from a list of predefined settings (available as a drop down list). Properties can be viewed in two ways: Alphabetic and Categorized. A very important property for each object is its name. The name is used by Visual Basic to refer to a particular object in code. Object names can be up to 40 characters long, must start with a letter must contain only letters, numbers, and the underscore (_) character. Names are used in setting properties at run time and also in establishing procedure names for object events. 2.3 Attach code to controls We’re now ready to attach code to our application. As objects are added to the form, Visual Basic automatically builds a framework of all event procedures. We simply add code to the event procedures we want our application to respond to. Attaching code to control is the programming side of the visual basics and requires good programming skills. Thus we will understand different programming terminologies and techniques used in visual basic to attach code to controls after drawing user interface and setting properties (we will mainly focus on attaching effective code to control).
6
3
Variables
Variables are used by Visual Basic to hold information needed by our application. Rules used in naming variables are:
No more than 40 characters They may include letters, numbers, and underscore (_) The first character must be a letter We cannot use a reserved word (word needed by Visual Basic)
Data Type Boolean Integer Long (Integer) Single (Floating) Double (Floating) Currency Date Object String Variant
3.1
Visual Basic Data Types Suffix Range None True or False % -32768 to 32767 & -2147483648 to 2147483647 ! -3.402823E38 to –1.4013E-45 (-ve) 3.402823E38 to 1.4013E-45 (+ve) # -1.798E308 to –4.940E-324 (-ve) 1.798E308 to 4.940E-324 (+ve) @ None None $ 0 to 2000000000 characters None Any value within the range above
Variable Declaration There are three ways for a variable to be typed (declared): 1. Default 2. Implicit 3. Explicit
If variables are not implicitly or explicitly typed, they are assigned the variant type by default. The variant data type is a special type used by Visual Basic that can contain numeric, string, or date data. To implicitly type a variable, use the corresponding suffix shown above in the data type table. For example, TextValue$ = "This is a string" creates a string variable, while Amount% = 300 creates an integer variable.
7
There are many advantages to explicitly typing variables. Primarily, we insure all computations are properly done, mistyped variable names are easily spotted, and Visual Basic will take care of insuring consistency in upper and lower case letters used in variable names. Because of these advantages, and because it is good programming practice, we will explicitly type all variables. To explicitly type a variable, we must first determine its scope. There are four levels of scope:
Procedure level Procedure level, static Form and module level Global level
Within a procedure, variables are declared using the Dim statement: Dim MyInt as Integer Dim MyDouble as Double Dim MyString, YourString as String Procedure level variables declared in this manner do not retain their value once a procedure terminates. To make a procedure level variable retain its value upon exiting the procedure, replace the Dim keyword with Static: Static MyInt as Integer Static MyDouble as Double Form (module) level variables retain their value and are available to all procedures within that form (module). Form (module) level variables are declared in the declarations part of the general object in the form's (module's) Code window. The Dim keyword is used: Dim MyInt as Integer Dim MyDate as Date Global level variables retain their value and are available to all procedures within an application. Module level variables are declared in the declarations part of the general object of a module's code window. (It is advisable to keep all global variables in one module.) Use the Global keyword: Global MyInt as Integer Global MyDate as Date What happens if we declare a variable with the same name in two or more places? More local variables shadow (are accessed in preference to) less local variables. For example, if a variable MyInt is defined as Global in a module and declared local in a routine MyRoutine, while in MyRoutine, the local value of MyInt is accessed. Outside MyRoutine, the global value of MyInt is accessed. 8
4
Visual Basic Statements and Expressions
The simplest statement is the assignment statement. It consists of a variable name, followed by the assignment operator (=), followed by some sort of expression e.g. StartTime = Now Explorer.Caption = "Captain Spaulding" BitCount = ByteCount * 8 Energy = Mass * LIGHTSPEED ^ 2 NetWorth = Assets - Liabilities The assignment statement stores information. If a statement is very long, it may be continued to the next line using the continuation character, an underscore (_). Example: Months = Log(Final * IntRate / Deposit + 1) _ / Log(1 + IntRate) Comment statements begin with the keyword Rem or a single quote ('). For example: Rem This is a remark ' This is also a remark x=2*y ' another way to write a remark or comment
5
Visual Basic Operators
The simplest operators carry out arithmetic operations. These operators in their order of precedence are: Operator ^ */ \ Mod +-
Operation Exponentiation Multiplication and division Integer division (truncates) Modulus Addition and subtraction
To concatenate two strings, use the & symbol or the + symbol: lblTime.Caption = "The current time is" & Format(Now, “hh:mm”) txtSample.Text = "Hook this “ + “to this”
9
There are six comparison operators in Visual Basic: Operator Comparison > Greater than < Less than >= Greater than or equal to <= Less than or equal to = Equal to <> Not equal to The result of a comparison operation is a Boolean value (True or False). Three logical operators used mostly are: Operator Not And Or
Operation Logical not Logical and Logical or
The Not operator simply negates an operand. The And operator returns a True if both operands are True. Else, it returns a False. The Or operator returns a True if either of its operands is True, else it returns a False. Logical operators follow arithmetic operators in precedence.
6
Visual Basic Functions
Visual Basic offers a rich assortment of built-in functions. Some examples are: Function Abs Asc Chr Cos Date Format Left Len
Value Returned Absolute value of a number ASCII or ANSI code of a character Character corresponding to a given ASCII or ANSI code Cosine of an angle Current date as a text string Date or number converted to a text string Selected left side of a text string Number of characters in a text string
10
Mid Now Right Rnd Sin Sqr Str Time Timer Val
Selected portion of a text string Current time and date Selected right end of a text string Random number Sine of an angle Square root of a number Number converted to a text string Current time as a text string Number of seconds elapsed since midnight Numeric value of a given text string
Example (Stopwatch Application) Drawing Controls Start a new project. The idea of this project is to start a timer, then stop the timer and compute the elapsed time (in seconds). Place three command buttons and six labels on the form. Move and size the controls and form so it looks something like this:
A convention has been established for naming Visual Basic objects. This convention is to use a three-letter prefix (depending on the object) followed by a name you assign. A few of the prefixes are (we’ll see more as we progress): Object Form Command Button Label Text Box Menu Check box
Prefix frm cmd, btn lbl txt mnu chk
Example frmWatch cmdExit, btnStart lblStart, lblEnd txtTime, txtName mnuExit, mnuSave chkChoice
11
Setting Properties Set properties of the form, three buttons, and six labels: Form1: BorderStyle Caption Name
1-Fixed Single Stopwatch Application frmStopWatch
Command1: Caption Name Command2: Caption Name
&End Timing cmdEnd
Command3: Caption Name
E&xit cmdExit
Label1: Caption
Start Time
Label2: Caption
End Time
Label3: Caption
Elapsed Time
Label4: BorderStyle Caption Name
1-Fixed Single [Blank] lblStart
Label5: BorderStyle Caption Name
1-Fixed Single [Blank] lblEnd
Label6: BorderStyle Caption Name
1-Fixed Single [Blank] lblElapsed
&Start Timing cmdStart
In the Caption properties of the three command buttons, notice the ampersand (&). The ampersand precedes a button's access key. That is, in addition to clicking on a button to invoke its event, you can also press its
12
access key (no need for a mouse). The access key is pressed in conjunction with the Alt key. Hence, to invoke 'Begin Timing', you can either click the button or press Alt+B. Note in the button captions on the form, the access keys appear with an underscore (_). Our form should now look something like this
Attaching Code All that’s left to do is attach code to the application. We write code for every event a response is needed for. In this application, there are three such events: clicking on each of the command buttons. Double-click anywhere on the form to open the code window. Or, select ‘View Code’ from the project window. Click the down arrow in the Object box and select the object named (general). The Procedure box will show (declarations). Here, you declare three form level variables: Option Explicit Dim StartTime As Variant Dim EndTime As Variant Dim ElapsedTime As Variant The Option Explicit statement forces us to declare all variables. The other lines establish StartTime, EndTime, and ElapsedTime as variables global within the form. Select the cmdStart object in the Object box. If the procedure that appears is not the Click procedure, choose Click from the procedure box. Type the following code which begins the timing procedure. Note the Sub and End Sub statements are provided for you: Sub cmdStart_Click () 13
‘Establish and print starting time StartTime = Now lblStart.Caption = Format(StartTime, "hh:mm:ss") lblEnd.Caption = "" lblElapsed.Caption = "" End Sub In this procedure, once the Start Timing button is clicked, we read the current time and print it in a label box. We also blank out the other label boxes. In the code above (and in all code in these notes), any line beginning with a single quote (‘) is a comment. You decide whether you want to type these lines or not. They are not needed for proper application operation. Now, code the cmdEnd button. Sub cmdEnd_Click () ‘Find the ending time, compute the elapsed time ‘Put both values in label boxes EndTime = Now ElapsedTime = EndTime - StartTime lblEnd.Caption = Format(EndTime, "hh:mm:ss") lblElapsed.Caption = Format(ElapsedTime, "hh:mm:ss") End Sub Here, when the End Timing button is clicked, we read the current time (End Time), compute the elapsed time, and put both values in their corresponding label boxes. Finally code the cmdExit button. Sub cmdExit_Click () End End Sub This routine simply ends the application once the Exit button is clicked. Save and to Run your application To run the application Click the Run button on the toolbar, or by pressing
14
Save [Form Name] Save the currently selected form or module with the current name. The selected file is identified in the Project window. Save [Form Name] As Like Save File, however you have the option to change the file name Saves all forms and modules in the current project using Save Project their current names and also save the project file. Save Project As Like Save Project, however you have the option to change file names. When you choose this option, if you have not saved your forms or modules, you will also be prompted to save those files. I always use this for new projects.
7
Visual Basic Branching - If Statements
Branching statements are used to cause certain actions within a program if a certain condition is met. The simplest is the If/Then statement: If Balance - Check < 0 Then Print "You are overdrawn" Here, if and only if Balance - Check is less than zero, the statement “You are overdrawn” is printed. You can also have If/Then/End If blocks to allow multiple statements: If Balance - Check < 0 Then Print "You are overdrawn" Print "Authorities have been notified" End If In this case, if Balance - Check is less than zero, two lines of information are printed. Or, If/Then/Else/End If blocks: If Balance - Check < 0 Then Print "You are overdrawn" Print "Authorities have been notified" Else Balance = Balance - Check End If Here, the same two lines are printed if you are overdrawn (Balance - Check < 0), but, if you are not overdrawn (Else), your new Balance is computed. Or, we can add the ElseIf statement: If Balance - Check < 0 Then Print "You are overdrawn" Print "Authorities have been notified" ElseIf Balance - Check = 0 Then
15
Print "Whew! You barely made it" Balance = 0 Else Balance = Balance - Check End If Now, one more condition is added. If your Balance equals the Check amount (ElseIf Balance - Check = 0), a different message appears. In using branching statements, make sure you consider all viable possibilities in the If/Else/End If structure. Also, be aware that each If and ElseIf in a block is tested sequentially. The first time an If test is met, the code associated with that condition is executed and the If block is exited. If a later condition is also True, it will never be considered.
8
Visual Basic Looping
Looping is done with the Do/Loop format. Loops are used for operations are to be repeated some number of times. The loop repeats until some specified condition at the beginning or end of the loop is met. Do While/Loop Example: Counter = 1 Do While Counter <= 1000 Debug.Print Counter Counter = Counter + 1 Loop This loop repeats as long as (While) the variable Counter is less than or equal to 1000. Note a Do While/Loop structure will not execute even once if the While condition is violated (False) the first time through. Also note the Debug.Print statement. What this does is print the value Counter in the Visual Basic Debug window. Do Until/Loop Example: Counter = 1 Do Until Counter > 1000 Debug.Print Counter Counter = Counter + 1 Loop This loop repeats Until the Counter variable exceeds 1000. Note a Do Until/Loop structure will not be entered if the Until condition is already True on the first encounter. Do/Loop While Example: Sum = 1 Do Debug.Print Sum
16
Sum = Sum + 3 Loop While Sum <= 50 This loop repeats While the Variable Sum is less than or equal to 50. Note, since the While check is at the end of the loop; a Do/Loop While structure is always executed at least once. Do/Loop Until Example: Sum = 1 Do Debug.Print Sum Sum = Sum + 3 Loop Until Sum > 50 This loop repeats Until Sum is greater than 50. And, like the previous example, a Do/Loop Until structure always executes at least once. Note: Make sure to get out of a loop! Infinite loops are never nice. If you get into one, try Ctrl+Break. That sometimes works - other times the only way out is rebooting your machine! The statement Exit Do will get you out of a loop and transfer program control to the statement following the Loop statement.
9
Visual Basic Counting
Counting is accomplished using the For/Next loop e.g. For I = 1 to 50 Step 2 A=I*2 Debug.Print A Next I In this example, the variable I initialize at 1 and with each iteration of the For/Next loop variable I is incremented by 2 (Step). This looping continues until I variable become greater than or equal to its final value (50). If Step is not included, the default value is 1. Negative values of Step are allowed. We can exit a For/Next loop using an Exit For statement. This will transfer program control to the statement following the Next statement.
17
Notes for:
ACTIVE SERVER PAGE (ASP)
1. Introduction to ASP 1.1
What is ASP? An ASP file can contain text, HTML tags and scripts. Scripts in an ASP file are executed on the server • ASP stands for Active Server Pages • ASP is a program that runs inside IIS • IIS stands for Internet Information Services • IIS comes as a free component with Windows 2000 • IIS is also a part of the Windows NT 4.0 Option Pack • The Option Pack can be downloaded from Microsoft • PWS is a smaller - but fully functional - version of IIS • PWS can be found on your Windows 95/98 CD 1.2 • • • • •
ASP Compatibility ASP is a Microsoft Technology To run IIS you must have Windows NT 4.0 or later To run PWS you must have Windows 95 or later ChiliASP is a technology that runs ASP without Windows OS InstantASP is another technology that runs ASP without Windows
• • • •
What is an ASP File? An ASP file is just the same as an HTML file An ASP file can contain text, HTML, XML, and scripts Scripts in an ASP file are executed on the server An ASP file has the file extension ".asp"
1.3
1.4 • •
1.5 • • • • • •
How Does ASP Differ from HTML? When a browser requests an HTML file, the server returns the file When a browser requests an ASP file, IIS passes the request to the ASP engine. The ASP engine reads the ASP file, line by line, and executes the scripts in the file. Finally, the ASP file is returned to the browser as plain HTML What can ASP do for you? Dynamically edit, change or add any content of a Web page Respond to user queries or data submitted from HTML forms Access any data or databases and return the results to a browser Customize a Web page to make it more useful for individual users The advantages of using ASP instead of CGI and Perl, are those of simplicity and speed Provides security since your ASP code can not be viewed from the browser
1
• •
Since ASP files are returned as plain HTML, they can be viewed in any browser Clever ASP programming can minimize the network traffic
2. Run ASP on Your PC You can run ASP on your own PC without an external server. To do that, you must install Microsoft's Personal Web Server (PWS) or Internet Information Services (IIS) on your PC. 2.1 1. 2. 3. 4. 5.
6.
2.2
How to install PWS and run ASP on Windows 98 Open the Add-ons folder on your Windows98 CD, find the PWS folder and run the setup.exe file. An Inetpub folder will be created on your harddrive. Open it and find the wwwroot folder. 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. 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.
How to install IIS and run ASP on Windows 2000 From your Start Button, go to Settings, and Control Panel In the Control Panel window select Add/Remove Programs In the Add/Remove window select Add/Remove Windows Components In the Wizard window check Internet Information Services, click OK 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 9. 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. 10. Open your browser and type in "http://localhost/MyWeb/test1.asp", to view your first ASP page 1. 2. 3. 4. 5. 6. 7. 8.
2.3 How to install IIS and run ASP on Windows XP Professional Note: You cannot run ASP on Windows XP Home Edition. 1. Insert the Windows XP Professional CD-Rom into your CD-Rom Drive 2. From your Start Button, go to Settings, and Control Panel 3. In the Control Panel window select Add/Remove Programs
2
4. 5. 6. 7. 8. 9.
In the Add/Remove window select Add/Remove Windows Components In the Wizard window check Internet Information Services, click OK 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 10. Make sure your Web server is running - its status can be checked by going into the Control Panel, then Administrative Tools, and double-click the "IIS Manager" icon 11. Open your browser and type in "http://localhost/MyWeb/test1.asp", to view your first ASP page 2.4
How to install IIS & run ASP on Windows Server 2003 (.NET Server) 1. When you start the Windows Server 2003, you should see the Manage Your Server wizard 2. If the wizard is not displayed, go to Administrative Tools, and select Manage Your Server 3. In the wizard, click Add or Remove a Role, click Next 4. Select Custom Configuration, click Next 5. Select Application Server role, click Next 6. Select Enable ASP.NET, click Next 7. Now, the wizard may ask for the Server 2003 CD. Insert the CD and let it run until it is finished, then click the Finish button 8. The wizard should now show the Application Server role installed 9. Click on Manage This Application Server to bring up the Application Server Management Console (MMC) 10. Expand the Internet Information Services (IIS) Manager, then expand your server, and then the Web Sites folder 11. You should see the Default Web Site, and it should not say (Stopped) 12. IIS is running! 13. In the Internet Information Services (IIS) Manager click on the Web Service Extensions folder 14. Here you will see that Active Server Pages are Prohibited (this is the default configuration of IIS 6) 15. Highlight Active Server Pages and click the Allow button 16. ASP is now active!
3. ASP Syntax You cannot view the ASP source code by selecting "View source" in a browser; you will only see the output from the ASP file, which is plain HTML. This is because the scripts are executed on the server before the result is sent back to the browser.
3
3.1
The Basic Syntax Rule An ASP file normally contains HTML tags, just like an HTML file. However, an ASP file can also contain server scripts, surrounded by the delimiters <% and %>. Server scripts are executed on the server, and can contain any expressions, statements, procedures, or operators valid for the scripting language you prefer to use. Consider the program below, which give “Hello World” as output to the browser. The response.write command is used to write output to a browser. <% response.write("Hello World!") %> Hello World! 3.2
ASP Variables A variable is used to store information. If the variable is declared outside a procedure any script in the ASP file can change it. If the variable is declared inside a procedure, it is created and destroyed every time the procedure is executed. Different examples shown below give different variables types. This example below demonstrates how to declare a variable, assign a value to it, and use the value in a text. <% dim name name="Abdul Wahid" response.write("My name is: " & name) %> My name is: Abdul Wahid Arrays are used to store a series of related data items. Following example demonstrates how to declare an array that stores names. <%
4
Dim famname(4),i famname(1) = "Abdul wahid" famname(2) = "Aamir" famname(3) = "Walid" famname(4) = "Haddad" For i = 1 to 4 response.write(famname(i) & "
") Next %> Abdul wahid Aamir Walid Haddad This example below will display a different message to the user depending on the time on the server. (Demonstration of time variable) <% dim h h=hour(now()) response.write("
3. To declare variables accessible to more than one ASP file, declare them as session variables or application variables. 4. Session variables are used to store information about ONE single user, and are available to all pages in one application. Typically information stored in session variables are name, id, and preferences. 5. Application variables are also available to all pages in one application. Application variables are used to store information about ALL users in a specific application. ASP Procedures In ASP you can call a JavaScript procedure from a VBScript and vice versa. Consider the example below in which VBScript is used to call a procedure. In example below it is shown how to call a vbscript procedure from ASP. <% sub vbproc(num1,num2) response.write(num1*num2) end sub %>
6
<%@ language="javascript" %> <% function jsproc(num1,num2) { Response.Write(num1*num2) } %>
4. ASP Forms and User Input The Request.QueryString and Request.Form commands may be used to retrieve information from forms, e.g. user input. Consider the example below in which it is shown that How to interact with the user, with the Request.QueryString command, using a form with method=”get”
7
<% dim fname fname=Request.QueryString("fname") If fname<>"" Then Response.Write("Hello " & fname & "!
") Response.Write("How are you today?") End If %>
Your name:
Submit
Consider the example below in which it is shown that How to interact with the user, with the Request.Form command, using a form with method=”post” <% dim fname fname=Request.Form("fname") If fname<>"" Then Response.Write("Hello " & fname & "!
") Response.Write("How are you today?") End If %>
Your name:
Submit
In other example below it is shown that how to interact with the user, through radio buttons (a form with radio buttons), with the Request.Form command. <% dim cars cars=Request.Form("cars") %> <% if cars<>"" then Response.Write("
User Input The Request object may be used to retrieve user information from forms. For example: User input can be retrieved in two ways: With Request.QueryString or Request.Form. 9
Request.QueryString The Request.QueryString command is used to collect values in a form with method="get". Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send. If a user typed "Abdul" and "Wahid" in the form example above, the URL sent to the server would look like this: http://www.w3schools.com/simpleform.asp?fname=Abdul&lname=Wahid Assume that the ASP file "simpleform.asp" contains the following script: Welcome <% response.write(request.querystring("fname")) response.write(" " & request.querystring("lname")) %> The browser will display the following in the body of the document: Welcome Abdul Wahid Request.Form The Request.Form command is used to collect values in a form with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send. If a user typed "Abdul" and "Wahid" in the form example above, the URL sent to the server would look like this: http://www.w3schools.com/simpleform.asp Assume that the ASP file "simpleform.asp" contains the following script: Welcome <% response.write(request.form("fname")) response.write(" " & request.form("lname")) %> The browser will display the following in the body of the document: Welcome Abdul Wahid
10
Form Validation User input should be validated on the browser whenever possible (by client scripts). Browser validation is faster and you reduce the server load. You should consider using server validation if the user input will be inserted into a database. A good way to validate a form on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error messages on the same page as the form. This makes it easier to discover the error.
5. ASP Response Object The ASP Response object is used to send output to the user from the server. Its collections, properties, and methods are described below: Collections Collection Cookies
Description Sets a cookie value. If the cookie does not exist, it will be created, and take the value that is specified
Properties Property Buffer CacheControl
Description Specifies whether to buffer the page output or not Sets whether a proxy server can cache the output generated by ASP or not Charset Appends the name of a character-set to the content-type header in the Response object ContentType Sets the HTTP content type for the Response object Sets how long (in minutes) a page will be cached on a Expires browser before it expires ExpiresAbsolute Sets a date and time when a page cached on a browser will expire IsClientConnected Indicates if the client has disconnected from the server Pics Appends a value to the PICS label response header Status Specifies the value of the status line returned by the server The table above can be understood by following example. ASP IsClientConnected Property The IsClientConnected property indicates if the client has disconnected from the server. Syntax response.IsClientConnected Example <%
11
If response.IsClientConnected=true then response.write("The user is still connected!") else response.write("The user is not connected!") end if %> Methods Method AddHeader AppendToLog BinaryWrite Clear End Flush Redirect Write
Description Adds a new HTTP header and a value to the HTTP response Adds a string to the end of the server log entry Writes data directly to the output without any character conversion Clears any buffered HTML output Stops processing a script, and returns the current result Sends buffered HTML output immediately Redirects the user to a different URL Writes a specified string to the output
The table above can be understood by following example. ASP Write Method The Write method writes a specified string to the output. Syntax Response.Write variant Parameter Variant
Description Required. The data to write
Examples 1 <% name="John" Response.Write(name) %> John 2 <% Response.Write("Hello
World") %> Hello World
12
To further understand the response object consider the following examples. This example demonstrates how to write text with ASP. (Using write method) <% response.write("Hello World!") %> Hello World! This example demonstrates how to combine text and HTML tags with ASP. <% response.write("You can use HTML tags to format the text!
") %> <% response.write("
The following example is self-explanatory. (Show a random link) <% randomize() r=rnd() if r>0.5 then response.write("W3Schools.com!") else response.write("Refsnesdata.no!") end if %>
14
one of two links: W3Schools.com! OR Refsnesdata.no! There is a 50% chance for each of them. This example demonstrates a link, each time you load the page, it will display one of two links: W3Schools.com! OR Refsnesdata.no! There is a 50% chance for each of them. This example demonstrates how to specify how many minutes a page will be cached in a browser before it expires. <%Response.Expires=-1%>
This page will be refreshed with each access! The following example demonstrates how to specify a date/time a page cached in a browser will expire. <% Response.ExpiresAbsolute=#May 05,2001 05:30:30# %>
15
The user is still connected!
6. ASP Request Object When a browser asks for a page from a server, it is called a request. The ASP Request object is used to get information from the user. Its collections, properties, and methods are described below: Collections Collection ClientCertificate Cookies Form QueryString ServerVariables Properties Property TotalBytes
Methods Method BinaryRead
Description Contains all the field values stored in the client certificate Contains all the cookie values sent in a HTTP request Contains all the form (input) values from a form that uses the post method Contains all the variable values in a HTTP query string Contains all the server variable values
Description Returns the total number of bytes the client sent in the body of the request
Description Retrieves the data sent to the server from the client as part of a post request and stores it in a safe array
Examples below will make it clearer to further understand the Request object. This example demonstrates how to use the values retrieved from a form. We use the QueryString collection. The form uses the get method <% dim fname fname=Request.QueryString("fname")
16
If fname<>"" Then Response.Write("Hello " & fname & "!
") Response.Write("How are you today?") End If %>
Your name:
Submit
This example demonstrates what the QueryString contains if several input fields have the same name. It shows how to separate input fields with equal names from each other. It also shows how to use the Count keyword to count the "name" property. The form uses the get method. <% If Request.QueryString<>"" Then If Request.QueryString("name")<>", " Then name1=Request.QueryString("name")(1) name2=Request.QueryString("name")(2) end if end if %>
<% If Request.QueryString<>"" Then Response.Write("
17
Response.Write("
This example demonstrates how to use the values retrieved from a form. We use the Form collection. The form uses the post method. <% dim fname fname=Request.Form("fname") If fname<>"" Then Response.Write("Hello " & fname & "!
") Response.Write("How are you today?") End If %>
Your name:
Submit
This example demonstrates what the Form collection contains if several input fields have the same name. It shows how to separate input fields with equal names from each other. It also shows how to use the Count keyword to count the "name" property. The form uses the post method.
The output below is when the submit button was clicked. First name: Last name:
Donald Duck
Submit
The information received from the form above was: name=Donald, Duck The name property's count is: 2 First name=Donald Last name=Duck This example demonstrates how to interact with the user through checkboxes, with the Form collection. The form uses the post method.
19
<% fruits=Request.Form("fruits") %> <% if fruits<>"" then%>
7. ASP Server Object The ASP Server object is used to access properties and methods on the server. Its properties and methods are described below:
20
Properties Property ScriptTimeout
Methods Method CreateObject Execute GetLastError() HTMLEncode MapPath Transfer URLEncode
Description Sets or returns the maximum number of seconds a script can run before it is terminated
Description Creates an instance of an object Executes an ASP file from inside another ASP file Returns an ASPError object that describes the error condition that occurred Applies HTML encoding to a specified string Maps a specified path to a physical path Sends (transfers) all the information created in one ASP file to a second ASP file Applies URL encoding rules to a specified string
The examples below will help to understand. The example below is to check, when was a file last modified. <% Set fs = Server.CreateObject("Scripting.FileSystemObject") Set rs = fs.GetFile(Server.MapPath("demo_lastmodified.asp")) modified = rs.DateLastModified %> This file was last modified on: <%response.write(modified) Set rs = Nothing Set fs = Nothing %> This file was last modified on: 02.12.2004 15:11:39 This example opens the file "Textfile.txt" for reading. <% Set FS = Server.CreateObject("Scripting.FileSystemObject") Set RS = FS.OpenTextFile(Server.MapPath("text") & "\TextFile.txt",1) While not rs.AtEndOfStream 21
Response.Write RS.ReadLine Response.Write("
") Wend %> Hello World line 1 Hello World line 2 Hello World line 3
8. ASP FileSystemObject Object The FileSystemObject object is used to access the file system on the server. This object can manipulate files, folders, and directory paths. It is also possible to retrieve file system information with this object. The following code creates a text file (c:\test.txt) and then writes some text to the file: <% dim fs,fname set fs=Server.CreateObject("Scripting.FileSystemObject") set fname=fs.CreateTextFile("c:\test.txt",true) fname.WriteLine("Hello World!") fname.Close set fname=nothing set fs=nothing %> The FileSystemObject object's properties and methods are described below: Properties Property Drives
Methods Method
Description Returns a collection of all Drive objects on the computer
Description
22
BuildPath CopyFile CopyFolder CreateFolder CreateTextFile DeleteFile DeleteFolder DriveExists FileExists FolderExists GetAbsolutePathName GetBaseName GetDrive GetDriveName GetExtensionName GetFile GetFileName GetFolder GetParentFolderName GetSpecialFolder GetTempName MoveFile MoveFolder OpenTextFile
Appends a name to an existing path Copies one or more files from one location to another Copies one or more folders from one location to another Creates a new folder Creates a text file and returns a TextStream object that can be used to read from, or write to the file Deletes one or more specified files Deletes one or more specified folders Checks if a specified drive exists Checks if a specified file exists Checks if a specified folder exists Returns the complete path from the root of the drive for the specified path Returns the base name of a specified file or folder Returns a Drive object corresponding to the drive in a specified path Returns the drive name of a specified path Returns the file extension name for the last component in a specified path Returns a File object for a specified path Returns the file name or folder name for the last component in a specified path Returns a Folder object for a specified path Returns the name of the parent folder of the last component in a specified path Returns the path to some of Windows' special folders Returns a randomly generated temporary file or folder Moves one or more files from one location to another Moves one or more folders from one location to another Opens a file and returns a TextStream object that can be used to access the file
ASP CreateTextFile Method The CreateTextFile method creates a new text file in the current folder and returns a TextStream object that can be used to read from, or write to the file. Syntax FileSystemObject.CreateTextFile(filename[,overwrite[,unicode]]) FolderObject.CreateTextFile(filename[,overwrite[,unicode]])
23
Parameter filename overwrite
unicode
Description Required. The name of the file to create Optional. A Boolean value that indicates whether an existing file can be overwritten. True indicates that the file can be overwritten and False indicates that the file can not be overwritten. Default is True Optional. A Boolean value that indicates whether the file is created as a Unicode or an ASCII file. True indicates that the file is created as a Unicode file, False indicates that the file is created as an ASCII file. Default is False
Example for the FileSystemObject object is as follow: <% dim fs,tfile set fs=Server.CreateObject("Scripting.FileSystemObject") set tfile=fs.CreateTextFile("c:\somefile.txt") tfile.WriteLine("Hello World!") tfile.close set tfile=nothing set fs=nothing %> Example for the Folder object is as follow: <% dim fs,fo,tfile Set fs=Server.CreateObject("Scripting.FileSystemObject") Set fo=fs.GetFolder("c:\test") Set tfile=fo.CreateTextFile("test.txt",false) tfile.WriteLine("Hello World!") tfile.Close set tfile=nothing set fo=nothing set fs=nothing %> ASP GetFile Method The GetFile method returns a File object for the specified path. Syntax FileSystemObject.GetFile(path) Parameter path
Description Required. The path to a specific file
24
Example <% dim fs,f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.GetFile("c:\test\test.htm") Response.Write("The file was last modified on: ") Response.Write(f.DateLastModified) set f=nothing set fs=nothing %> The file was last modified on 01/01/20 4:23:56 AM
The examples below will further understand us how to use the FileSystemObject Object This example demonstrates how to first create a FileSystemObject Object, and then use the FileExists method to check if the file exists. <% Set fs=Server.CreateObject("Scripting.FileSystemObject") If (fs.FileExists("c:\winnt\cursors\3dgarro.cur"))=true Then Response.Write("File c:\winnt\cursors\3dgarro.cur exists.") Else Response.Write("File c:\winnt\cursors\3dgarro.cur does not exist.") End If set fs=nothing %> File c:\winnt\cursors\3dgarro.cur exists. This example demonstrates how to use the FolderExists method to check if a folder exists. <% Set fs=Server.CreateObject("Scripting.FileSystemObject")
25
If fs.FolderExists("c:\temp") = true Then Response.Write("Folder c:\temp exists.") Else Response.Write("Folder c:\temp does not exist.") End If set fs=nothing %> Output will be (if the required folder exits). Folder c:\temp exists. This example demonstrates how to use the DriveExists method to check if a drive exists. <% Set fs=Server.CreateObject("Scripting.FileSystemObject") if fs.driveexists("c:") = true then Response.Write("Drive c: exists.") Else Response.Write("Drive c: does not exist.") End If Response.write("
") if fs.driveexists("g:") = true then Response.Write("Drive g: exists.") Else Response.Write("Drive g: does not exist.") End If set fs=nothing %> Drive c: exists. Drive g: does not exist.
26
9. ASP TextStream Object The TextStream object is used to access the contents of a text file. The following code creates a text file (c:\test.txt) and then writes some text to the file (the variable f is an instance of the TextStream object): <% dim fs, f set fs=Server.CreateObject("Scripting.FileSystemObject") set f=fs.CreateTextFile("c:\test.txt",true) f.WriteLine("Hello World!") f.Close set f=nothing set fs=nothing %> To create an instance of the TextStream object you can use the CreateTextFile or OpenTextFile methods of the FileSystemObject object, or you can use the OpenAsTextStream method of the File object. The TextStream object's properties and methods are described below: Properties Property AtEndOfLine
AtEndOfStream Column Line Methods Method Close Read ReadAll ReadLine Skip SkipLine Write WriteLine
Description Returns true if the file pointer is positioned immediately before the end-of-line marker in a TextStream file, and false if not Returns true if the file pointer is at the end of a TextStream file, and false if not Returns the column number of the current character position in an input stream Returns the current line number in a TextStream file
Description Closes an open TextStream file Reads a specified number of characters from a TextStream file and returns the result Reads an entire TextStream file and returns the result Reads one line from a TextStream file and returns the result Skips a specified number of characters when reading a TextStream file Skips the next line when reading a TextStream file Writes a specified text to a TextStream file Writes a specified text and a new-line character to a
27
WriteBlankLines
TextStream file Writes a specified number of new-line character to a TextStream file
The example below demonstrates how to use the OpenTextFile method of the FileSystemObject (explained earlier) to create a TextStream Object. The ReadAll method of the TextStream Object reads from the opened text file.
28
Output of the program is: This is the first five characters from the text file: Hello
10. ASP File Object The File object is used to return information about a specified file.The File object is used to return information about a specified file. To work with the properties and methods of the File object, you will have to create an instance of the File object through the FileSystemObject object. First; create a FileSystemObject object and then instantiate the File object through the GetFile method of the FileSystemObject object or through the Files property of the Folder object. The following code uses the GetFile method of the FileSystemObject object to instantiate the File object and the DateCreated property to return the date when the specified file was created: <% Dim fs,f Set fs=Server.CreateObject("Scripting.FileSystemObject") Set f=fs.GetFile("c:\test.txt") Response.Write("File created: " & f.DateCreated) set f=nothing set fs=nothing %> Output: File created: 9/19/2001 10:01:19 AM The File object's properties and methods are described below: Properties Property Attributes DateCreated DateLastAccessed DateLastModified Drive Name ParentFolder Path ShortName
Description Sets or returns the attributes of a specified file Returns the date and time when a specified file was created Returns the date and time when a specified file was last accessed Returns the date and time when a specified file was last modified Returns the drive letter of the drive where a specified file or folder resides Sets or returns the name of a specified file Returns the folder object for the parent of the specified file Returns the path for a specified file Returns the short name of a specified file (the 8.3 naming convention) 29
ShortPath Size Type Methods Method Copy Delete Move OpenAsTextStream
Returns the short path of a specified file (the 8.3 naming convention) Returns the size, in bytes, of a specified file Returns the type of a specified file
Description Copies a specified file from one location to another Deletes a specified file Moves a specified file from one location to another Opens a specified file and returns a TextStream object to access the file
ASP Summary In this chapter we have discussed how to add server-side scripts to our web site, to make our web site more dynamic and interactive. We have learned how to dynamically edit, change or add any content of a web page, respond to data submitted from HTML forms return the results to a browser, customize a web page to make it more useful for individual users. We will further use this knowledge in web designing in our project.
References ¾ ASP manual By Mehdi Anchor & Philip Olson ¾ http://www.w3schools.com/asp/default.asp
30