Click here to load reader
Upload
phamanh
View
216
Download
2
Embed Size (px)
Citation preview
3
APPENDIX
BVBSCRIPT
BASIC VBSCRIPT PROGRAMMING TECHNIQUES AND SAMPLE CODE
This appendix contains a list of commonly used VBScript techniques. Sample code is pro-vided to illustrate how these techniques could be used within a Web application. Thisappendix also contains a list of commonly used ASP techniques that are used with VBScript.This appendix is not meant to be an exhaustive reference on VBScript or ASP, nor does itcontain the complete reference and documentation for VBScript or ASP.For more in-depthinformation on ASP, please visit http://www.learnasp.com/. For the complete documentationon VBScript as well as JScript, please visit the Microsoft Windows Script Technologies Website at http://msdn.microsoft.com/scripting/. Additional documentation is available at theMSDN Online Library at http://msdn.microsoft.com/library/default.asp.
Comments and the VBScript Basics
To add a comment, use a single apos- ' This code was written on 8/2/2001.trophe. You can add comments inline.
Use the line continuation character (_) to document.write("Welcome" & _continue code on another line. In general, "to our Web site.")VBScript is not case sensitive.
Using Variables
Data Types
Subtype Constant Value Description
Empty vbEmpty 0 Variant is uninitialized. No value has beenassigned to the variable.
Null vbNull 1 Contains no valid data
Boolean vbBoolean 11 A logical value of either True or False. True alsohas the value of –1, and False has the value of 0.
Byte vbByte 17 Contains integers from 0 to 255
Integer vbInteger 2 Contains integers from –32,768 to 32,767
Currency vbCurrency 6 –922,337,203,685,477.5808 to922,337,203,685,477.5807
Long vbLong 3 Contains integers from range –2,147,483,648 to2,147,483,647
Single vbSingle 4 Contains a single-precision, floating-point numberin the range –3.402823E38 to –1.401298E–45 fornegative values; 1.401298E–45 to 3.402823E38for positive values
Double vbDouble 5 Contains a double-precision, floating-point number in the range –1.79769313486232E308 to –4.94065645841247E–324 for negative values; 4.94065645841247E–324 to1.79769313486232E308 for positive values
To declare a variable, use the Dim dim strProduct, intQuantitykeyword. You can declare multiple variables together.
To assign a variable to a value, use the intQuantity = 5assignment operator (=). strWelcome = "This is a string"
blnLogin = true
To assign a variable to a form field, use first = "Kim"the assignment operator (=) and explicitly document.frm1.fname.value = firstidentify the field. You are changing the value property for the field.
Use to force the declaring of all variables <% option explicit %>before they are used. Place this on the top line of the page.
Use to instantiate a new object. Set objName = new Date()
Use to remove the reference to the object. Set objName = nothing
To concatenate variables and strings, use document.write("Cost = " & intCost)the ampersand (&) as the concatenation operator.
4 Appendix B VBScript
Appendix B 5
Data Types (continued)
Arithmetic and Unary Operators
The Date
To get the current date Date()
To get the current time Time()
To get the current date and time Now()
To get the weekday number between 1 and 7 Weekday(Date)
To get the name of the weekday WeekdayName(Weekday(Date))
To get the name of the weekday for today WeekdayName(Weekday(Date()))
To get the day of the month, a number Day(Date)between 0 and 31
To get the number of the month, starting at 0 Month(Date)
To get the name of the month MonthName(Month(Date))
To get the name of the current month MonthName(Month(Date()))
To get the two-digit year Year(MyDate)
To get the two-digit year for the current date Year(Now())
Category Operator Description Example
Arithmetic + Addition x + y
Arithmetic - Subtraction x – y
Arithmetic * Multiplication x * y
Arithmetic / Division x / y
Unary ++ Increment i = ++ i
Unary -- Decrement i = -- i
Unary – Negation -i
Subtype Constant Value Description
Date (Time) vbDate (Time) 7 Contains a number that represents a datebetween January 1, 100 to December 31, 9999
String vbString 8 Contains a variable-length string that can be upto approximately 2 billion characters in length
Object vbObject 9 Contains an object
Error vbError 10 Contains an error number
Array vbArray 8192 Contains an array
B
Using Constants
Built-in Constants
Arrays
To declare and populate a one-dimensional array, Dim Products(1)declare the array name and the number of dimensions. Products(0) = "Pencils"Arrays always start with zero (0). Use the assignment Products(1) = "Pens"operator (=) to assign values to each element in the array. The array elements are identified by their position in the array.
To write an array element value to a Web page, document.write Products(0)identify the array element by its position.
Constant Description Value Returned
VbCrLf Returns a carriage return and line feed Chr(10) & Chr(13)
VbCr Returns a carriage return Chr(13)
VbLf Returns a line feed Chr(10)
VbTab Returns a horizontal tab Chr(9)
TristateTrue Returns a –1 ( for True) –1
TristateFalse Returns a 0 ( for False) 0
To assign a value to a constant, use the Const const constCompany = "GTT"keyword and the assignment operator (=). const constDate = #09-28-36#
To retrieve the value of a constant, assign the document.title = constTitleconstant to another container such as a document.write constCompanyvariable, or use it in an expression.
Use to include the adovbs.inc file that contains <!--#include file="adovbs.inc"-->many predefined constants that are used to access a database. (Don’t forget to include theentire path if the Web page is not in the same directory as the include file. You can create your own page of constants and include that file in your Web pages.)
6 Appendix B VBScript
Appendix B 7
Comparison Operators
Using Built-in Functions to Test Variable TypesTo detect if the value of a variable is a number, use the isNumeric built-in function:
StrNumber = isNumeric(strQuantity)document.write(strNumber)
Using Built-in Functions to Convert ValuesTo convert a “number” string into a number, use the Int built-in conversion function:
strQ = Int(strQuantity)
Name Description Example
Chr Converts the ANSI number into a string character Chr(10)
Cdate Converts the value into a date CDate(12/12/2001)
Cint Converts the value into an integer CInt(345)
CStr Converts the value into a string CStr("Hello")
Ccur Converts the value into currency CCur(2343.20)
Int Returns only the integer portion of a number Int(54345.1223)
Round Rounds the number; can specify the number of places Round(234.14)
Name Description (all functions return a Boolean value) Sample
IsArray Determines if the variable is an array IsArray(objArray)
IsDate Determines if the variable is a date IsDate (objDate)
IsNumeric Determines if the variable is a number IsNumeric(myNum)
IsEmpty Determines if the variable has been initialized IsEmpty (myVar)
IsNull Determines if the variable contains no valid data IsNull (yourVar)
IsObject Determines if the variable is a valid object IsObject (objMail)
Condition Being Tested Operator Example
Is A equal to B? = A = B
Is A not equal to B? <> A <> B
Is A less than B? < A < B
Is A greater than B? > A > B
Is A less than or equal to B? <= A <= B
Is A greater than or equal to B? >= A >= B
B
Special Characters in VBScriptTo convert an ASCII number into a character using the Chr function:
Cost = Chr(36) & "36.50"
Using Built-in Math FunctionsTo round a number up to the next highest integer using the built-in Ceil mathematicalfunction:
document.write(Ceil(233.57))
Function Description Sample
Abs() Returns the absolute value of a number Abs(-5)
Floor() Rounds the number to the next lowest integer Floor(5.05)
Ceil() Rounds the number to the next highest integer Ceil(5.05)
Random() Returns a random number Random()
Round Rounds the number to the nearest integer Round(5.5)
Description Character ANSI Code
Backspace 8
Tab space 9
New line 10
Carriage return 11
Space 32
Double quote " 34
Pound sign # 35
Dollar sign $ 36
Ampersand & 38
Single quote ' 39
Forward slash / 47
At symbol @ 64
Back slash \ 92
Copyright ©
Trademark ™
Registered ®
8 Appendix B VBScript
Appendix B 9
Using Built-in String FunctionsTo change the format of a number to currency, use the Format Currency built-in stringfunction:
document.write(FormatCurrency(strCost))
Using Functions and Subroutines
To create a function, use the Function keyword, function calcTotal()and name the function. End the function with ƒƒƒƒƒdocument.write(strTotal)the End Function keywords. Unlike subroutines, end functionfunctions can return a value.
To call a function, use the Call keyword and the call calcTotal()function name. The Call keyword is optional.
To create an Event Handler procedure, use the Sub btnSubmit_onClickSub keyword, and the name of the event. The ƒƒƒƒƒdocument.write("Welcome")name of the event is a combination of the name End subof the object, an underscore (_), and the name of the event. Use the End Sub keywords to end the procedure.
Name Description Example
FormatCurrency Formats a value with the dollar sign and FormatCurrency(25.2)2 decimal places
Instr Returns the first character position of a Instr()string within another string
LCase Converts a string to all lowercase characters LCase("PassWord")
Len Returns the string length in characters Len("PassWord")
LTrim Removes leading empty spaces from a string LTrim(" pass")
RTrim Removes the trailing empty spaces from RTrim("John ")a string
Space Returns a string that contains a specified document.write "Jim"number of empty spaces & Space(1) & "Murphy"
String Returns the same string for the designated String(3,@)number of times
StrReverse Returns the string in reverse order StrReverse("password")
Trim Removes leading and trailing spaces from Trim(" pass ")a string
UCase Converts a string to all uppercase characters UCase("PassWord")
B
Control Structures
Logical OperatorsTo create an If Then Else statement that uses a combined expression, use a logical operator.Don’t forget to use parentheses around each expression, and around the entire expression.Each expression must evaluate to True or False.
if ((name="admin") and (pwd="pass")) thenƒƒƒƒƒwindow.alert("Welcome Administrator")elseƒƒƒƒƒlocation.href=("http://www.course.com")end if
To create an If Then Else statement, place ifƒ(a=1) thenthe Then keyword on the same line as the If ƒƒƒƒƒwindow.alert("a")keyword. When creating nested If Then Else elsestatements, don’t forget to include the End If ƒƒƒƒƒwindow.alert("not a")keywords for each If statement. end if
To create a Select Case statement, be sure to select case aNumberinclude the End Select keywords. ƒƒƒƒƒcase 1
ƒƒƒƒƒƒƒƒƒƒwindow.alert("1")ƒƒƒƒƒcase 2ƒƒƒƒƒƒƒƒƒƒwindow.alert("2")ƒƒƒƒƒcase elseƒƒƒƒƒƒƒƒƒƒwindow.alert("other")end select
When creating a Do While statement, dim z, iremember that the code will repeat until an z = 5expression evaluates to false. Don’t forget to i = 0alter the expression in the code, or the loop do while i <= zwill repeat forever. ƒƒƒƒƒwindow.alert(i)
ƒƒƒƒƒi = i + 5loop
To create a For Next Loop statement, use the for i = 1 to 5For keyword. The loop will continue for a ƒƒƒƒƒdocument.write(i & "<br>")specified number of times. The starting num- nextber and the ending number can be variables.
To create a For Each In Loop statement, use for each eachElement in Productsthe For Each keyword to identify the element ƒƒƒƒƒdocument.write(Products(i))that you want to retrieve. The In keyword is ƒƒƒƒƒdocument.write("<br>")the name of the collection that contains the ƒƒƒƒƒi = i + 1individual elements. next
10 Appendix B VBScript
Appendix B 11
THE ASP MODEL
Basic ASP
To create a server-side script using block <script language = scripting tags "vbscript"
ƒƒƒrunat = "server">Response.write("Hello")
</script>
To create a server-side script using inline <% Response.write("Hello")%>scripting tags
To set the default language to VBScript <%@language = "vbscript" %>(must be placed on the first line of the ASP page)
To force you to declare all variables <% option explicit %>before they are used (must be placed on the first line)
To include a file using an absolute <!--#include file="C:\garden.inc" -->physical path
To include a file using a relative physical <!--#include file="/garden.inc" -->path starting from the current directory
To include a file using a relative virtual <!--#include virtual="/garden.inc" -->path starting from the root directory
Operators Example Description
AND if ((a = 1) and ( = 2)) If both expressions are true, the result is true.If either expression is false, the result is false.
OR if ((a = 1) or (b = 2)) If either expression is true, or both are true,the result is true. If both are false, the resultis false.
NOT if (not (a = 1)) Used to negate a single expression. If theexpression is true, the result is false. If theexpression is false, the result is true.
B
The Response Object
The Request Object
The HTML form tag that must be <form method = "POST"configured with method get or post. ƒƒƒaction = "builtinObjects.asp">The action must be an ASP page for the request object to be able to retrieve the form field values.
To retrieve the entire QueryString Request.querystringcollection, which includes the name and value pairs
To retrieve the entire QueryString For each ff in request.querystringcollection of name and value pairs Response.write ff & ", "
Response.write(request.querystring(ff))Response.write "<br>"
To retrieve the value from a form Request.querystring("txtName")field name txtName that uses the get method
To retrieve the entire form Request.formcollection, which includes the name and value pairs from a form that uses the post method
To write out an expression to the Response.write("Hello")Web page. The shortcut (=) can be Response.write(strName)used for only a single line of code. Response.write("Hello " & strName)You can concatenate variables and <% = strName %>string in the expression. <% = "Hello" %>
To redirect the user to another Response.redirect "http://www.course.com"Web page Response.redirect "default.htm"
To control the output to the Response.buffer = "true"browser; must be placed on the first line in the page.
To erase the contents of the buffer Response.clear
To send the contents of the buffer Response.flushto the browser
To stop sending content to the Response.endbrowser
To set the expiration property to Response.expires = 5 minutescontrol caching the Web page Response.expiresabsolute = #Mar10,2001#
12 Appendix B VBScript
Appendix B 13
The Request Object (continued)
The Server Variables Collection of the Request Object
Variable Name Description
SERVER_NAME The name of the Web server
SERVER_SOFTWARE The operating system of the server and the Web server software
SERVER_PORT Port number for the Web server
LOCAL_ADDR The local IP address of the server’s computer
SERVER_PROTOCOL The protocol being used to deliver the request (HTTP 1.0 or 1.1)
HTTP_REFERER The page that referred the client to the current page
HTTP_USER_AGENT The user agent that provides the browser name and version
REMOTE_ADDR The remote IP address of the server’s computer
URL The URL of the file being requested
PATH_INFO The virtual path to the file being requested
PATH_TRANSLATED The virtual path translated into the physical path; similar resultsto using the MapPath() method of the server object
REQUEST_METHOD The method that a form is using to send information—either postor get
HTTP_CONTENT_LENGTH The length of the file attached to the header, which may includethe results from a form that uses the post method. This value is 0if the Get method is used.
QUERY_STRING The querystring generated from the name and value pairs from aform that used the get method
HTTP_COOKIE Name and value of a cookie, if the client has one written fromthe same server
LOGON_USER The NT user account of the user. If the user is logged in with theIIS default account, no value is returned.
To retrieve the value from a form Request.form("txtName")field name txtName that uses the post method
To retrieve a specific server Request.servervariables("SERVER_NAME")variable value
To write out all the server variables For each sv in request.servervariablesResponse.write sv & ", "Response.write(request.servervariables(sv))next
To retrieve the relative path to a SP = Request.servervariables("PATH_INFO")Web page
To retrieve the absolute path. The = Server.MapPath(SP)relative path is a required parameter. = Server.MapPath(Request.servervariables
("PATH_INFO"))
B
Application and Session Objects
To create an application variable in Application("AName") = "Fred"the Global Application File Application.Contents("AName") = "Fred"
To retrieve an application variable Name = Application("AName")from a Web page and assign it to a variable
To change the value of an Application.Lockapplication variable in the Global Application("ANum")=Application("Anum")+1Application File Application.Unlock
To create a session variable in an Session("SName") = "Maria"ASP page Session.Contents("SName") = "Maria"
Session("SDate") = Now()
To retrieve a session variable from NewMember= Session("SName")a Web page and assign it to a variable
To view the timeout property of = session.timeoutthe Session object
To change the timeout property session.timeout = 30of the Session object. The default is 20 minutes.
To call the abandon method of the session.abandonSession object
To view the SessionID property of = session.sessionIDthe Session object
To assign the value of a session ID <input type = "hidden" name = "sessionID"to a hidden field value="<% = session.sessionID %>">
To create an application scope <object runat="Server" Scope=Applicationobject in the Global Application File PROGID=ComponentName id=objName>
</object>
To assign a value to a property of Application("objName").Property = valuean application object
14 Appendix B VBScript
Appendix B 15
Cookies
To read an entire cookie from the = Request.servervariables("HTTP_COOKIE")server variable and write it to the Web page
To write a simple cookie to the Response.cookies("cookie") = "red"client’s file system
To read a simple cookie and write it = Request.cookies("cookie")to the Web page and assign it to a cookie = request.cookies("cookie")variable
To read a simple cookie and write <input type = "text" name = "sessionID"the value to a form field value="<% = Request.cookies("cookie") %>">
To write a named group of cookies Response.cookies("gp")("bc")= "red"to the client’s file system Response.cookies("gp")("fc")= "blue"
Response.cookies("gp").Expires = Date + 30
To write a cookie using the value Response.cookies("Cookie ")= strUserfrom a variable
To write a cookie using the value Response.cookies("Name")=request.formfrom a form field ("tName")
To read a cookie from a group = Request.cookies("gp")("bc")of cookies and write it to the = Request.cookies("gp")("fc")Web page
To determine if the cookie contains Request.cookies("gp").HasKeysa group of cookies; returns a True or False value
B
Working with Other Objects
To create a Browser Capabilities Set bc = Server.CreateObjectComponent object ("MSCW.BrowserType")
To retrieve the Request.servervariables("HTTP_USER_AGENT")HTTP_USER_AGENT server variable
To retrieve the support status bc.framesof a feature of the browser
To retrieve the name of the bc.browserbrowser
To create the AdRotator Set objAd = Server.CreateObjectcomponent in the ASP page ("MSWC.AdRotator")
To create the first section of the Redirect RedirectPage.aspRotator Scheduler File border 4
height 50width 400http://www.course.com/*
To create the second section images/imageName.gifof the Rotator Scheduler File http://www.course.com/(ad.txt) Course Technology
50
To create the Redirection File Response.Redirect(RedirectPage.asp) (Request.QueryString("url"))
To call the GetAdvertisement Ad = objAd.GetAdvertisement("ad.txt")method to write the banner ad Response.write Adin the ASP page
To call the create the Newmail Set oM = CreateObject("CDONTS.Newmail")object from CDONTS component
To set properties of the Newmail oM.From = "[email protected]"object oM.To = "[email protected];
[email protected]"oM.CC = "[email protected]"oM.BCC = "[email protected]"oM.Subject = "Subject"oM.Importance = cdoHighoM.Body = "Message Body"
To call the send method of the oM.Sendsendmail object
To send HTML instead of text in sHTML = "<b>This message is in bold </b>"the message body oM.BodyFormat = cdoBodyFormatHTML
oM.Body = sHTML
16 Appendix B VBScript
Appendix B 17
Scripting Library
To create an instance of the Set oD = Server.CreateObjectdictionary object (Scripting.Dictionary)
To add a key/item pair to the oD.Add "memberid", memberiddictionary object
To retrieve the value for the item oD.Item("memberid")in a dictionary object
To retrieve the number of oD.countkey/item pairs of data in a dictionary object
To create a FileSystemObject Set FSO = server.createobject ("Scripting.FileSystemObject")
To create a folder using the FSO.CreateFolder "c:\test\"CreateFolder method of the FileSystemObject
To copy a folder using the FSO.CopyFolder "c:\test\", CopyFolder method of the "c:\testCopy\", TrueFileSystemObject
To move a folder using the FSO.MoveFolder "c:\test3\", "c:\test4\"MoveFolder method of the FileSystemObject
To delete a folder using the FSO.DeleteFolder "c:\test5\"DeleteFolder method of the FileSystemObject
To create a file using the FSO.CreateTextFile "c:\test\sample.txt"CreateFile method of the FileSystemObject
To copy a file using the FSO.CopyFile "c:\test\s1.txt",CopyFolder method of the "c:\test\s2.txt", TrueFileSystemObject
To delete a file using the FSO.DeleteFile "c:\test\testfile.txt"DeleteFolder method of the FileSystemObject
To retrieve the drives collection Set objDrv = FSO.Drives
To retrieve the drive type with drv.DriveTypethe DriveType property of a drive object
To retrieve the total size of the formatNumber(drv.TotalSize/1073741824,0)disk drive in gigabytes, using the TotalSize property
To retrieve the available space formatNumber(drv.AvailableSpace/1048576,0)of the disk drive in megabytes, using the AvailableSpace property
B
Scripting Library (continued)
To retrieve a specific folder object, Set of = objFSO.GetFolder("c:\test\")using the GetFile method of the FileSystemObject
To retrieve the SubFolders Set subf= of.subfcollection of the folder object, using the SubFolders property
To retrieve the date the folder of.dateCreatedwas created
To retrieve the date the folder of.dateLastModifiedwas last modified
To find the difference in days DateDiff("d",of.dateCreated, between the date the folder was of.dateLastModified)created and the date it was last modified
To retrieve the path property for of.Patha folder object
To display the size of a file, using of.Sizethe size property of the file object
To create a TextStream object Set tf = filesys.CreateTextFileusing the CreateTextFile object (FilePath, true)
To write to a file using the tf.Write("Office Supply Store ")TextStream object tf.WriteLine("Product Inventory List")
tf.WriteBlankLines(2)
To append to a file using the Set tf = objFSO.OpenTextFile(FilePath, TextStream object 8, False)
To open a file for reading, using Set tf = objFSO.OpenTextFile(filePath, the TextStream object 1, 0)
To read a line of text from a file, tf.ReadLineusing the TextStream object
To enable error handling On Error Resume Next
To display the error number, Err.Numberusing the error object
18 Appendix B VBScript