Wednesday, 30 November 2011

VBScript Keywords

empty:
Used to indicate an uninitialized variable value. A variable value is uninitialized when it is first created and no value is assigned to it, or when a variable value is explicitly set to empty.
Example:
dim x ‘the variable x is uninitialized!
x=”ff” ‘the variable x is NOT uninitialized anymore
x=empty ‘the variable x is uninitialized!
Note: This is not the same as Null!!
isEmpty:
Used to test if a variable is uninitialized.
Example: If (isEmpty(x)) ‘is x uninitialized?
nothing Used to indicate an uninitialized object value, or to disassociate an object variable from an object to release system resources.
Example: set myObject=nothing
is nothing:
Used to test if a value is an initialized object.
Example: If (myObject Is Nothing) ‘is it unset?
Note: If you compare a value to Nothing, you will not get the right result! Example: If (myObject = Nothing) ‘always false!
null:
Used to indicate that a variable contains no valid data.
One way to think of Null is that someone has explicitly set the value to “invalid”, unlike Empty where the value is “not set”.
Note: This is not the same as Empty or Nothing!!
Example: x=Null ‘x contains no valid data
isNull:
Used to test if a value contains invalid data.
Example: if (isNull(x)) ‘is x invalid?
true:
Used to indicate a Boolean condition that is correct (true has a value of -1)
false:
Used to indicate a Boolean condition that is not correct (false has a value of 0)

Dictionary Method

Object that stores data key, item pairs.
A Dictionary object is the equivalent of a PERL associative array. Items can be any form of data, and are stored in the array. Each item is associated with a unique key. The key is used to retrieve an individual item and is usually a integer or a string, but can be anything except an array. The following code illustrates how to create a Dictionary object: [VBScript] Dim d ‘ Create a variable. Set d = CreateObject(“Scripting.Dictionary”) d.Add “a”, “Athens” ‘ Add some keys and items. d.Add “b”, “Belgrade” d.Add “c”, “Cairo” …
Methods
Add Method (Dictionary) | Exists Method | Items Method | Keys Method | Remove Method | RemoveAll Method
Add method : Adds a key and item pair to a Dictionary object Exists : Returns true if a specified key exists in the Dictionary object, false if it does not.
Items: Returns an array containing all the items of the dictionary object.
Keys: Returns an array containing all the keys of the dictionary object.
Remove: Remove the specified item from the dictionary object.
RemoveAll: Remove all items from the Dictionary object.
Count:Returns the number of items in a collection or Dictionary object. Read-only.
Item: Sets or returns an item for a specified key in a Dictionary object
Key: Sets a key in a Dictionary object.
Example: 
Function KeyExistsDemo
Dim d, msg ‘ Create some variables.
Set d = CreateObject(“Scripting.Dictionary”)
d.Add “a”, “Athens” ‘ Add some keys and items.
d.Add “b”, “Belgrade”
d.Add “c”, “Cairo”
d.Remove(“c”)
d.RemoveAll
DicDemo = d.Item(“a”) ‘ Return associate item.
Exists
If d.Exists(“c”) Then
msg = “Specified key exists.”
Else
msg = “Specified key doesn’t exist.”
End If
KeyExistsDemo = msg
items: 

     a = d.Items   ' Get the items.
For i = 0 To d.Count -1 ‘ Iterate the array.
s = s & a(i) & "<BR>" ' Create return string.

Next

DicDemo = s


Keys: 

    a = d.Keys   ' Get the keys.
For i = 0 To d.Count -1 ‘ Iterate the array.
s = s & a(i) & "<BR>" ' Return results.

   Next

   DicDemo = s
End Function

VBScript Features

The following table is a list of VBScript features.

Array handling: 
Assignments
Set
Comments
Constants/Literals 
Control flow
Conversions
Dates/Times
Declarations
Error Handling
Expressions
Formatting Strings
Input/Output
Operators
Procedures
Rounding
Script Engine ID
Strings
Variants

Difference b/w Eval & Execute

Eval & Execute Statement
Eval: Evaluates an expression and returns the result. (True (-1)  & False (0))
Required. String containing any legal VBScript expression
In VBScript, x = y can be interpreted two ways. The first is as an assignment statement, where the value of y is assigned to x. The second interpretation is as an expression that tests if x and y have the same value. If they do, result is True; if they are not, result is False. The Eval method always uses the second interpretation, whereas the Execute statement always uses the first.
Note In Microsoft® JScript™, no confusion exists between assignment and comparison, because the assignment operator (=) is different from the comparison operator (==).
The following example illustrates the use of the Eval function: 
Sub GuessANumber
   Dim Guess, RndNum
   RndNum = Int((100) * Rnd(1) + 1)
   Guess = CInt(InputBox(“Enter your guess:”,,0))
   Do
      If Eval(“Guess = RndNum”) Then
         MsgBox “Congratulations! You guessed it!”
         Exit Sub
      Else
         Guess = CInt(InputBox(“Sorry! Try again.”,,0))
      End If
   Loop Until Guess = 0
End Sub
Execute: Executes one or more specified statements
The required statement argument is a string expression containing one or more statements for execution. Include multiple statements in the statement argument, using colons or embedded line breaks to separate them. 
The context in which the Execute statement is invoked determines what objects and variables are available to the code being run. In-scope objects and variables are available to code running in an Execute statement. However, it is important to understand that if you execute code that creates a procedure, that procedure does not inherit the scope of the procedure in which it occurred.
Like any procedure, the new procedure’s scope is global, and it inherits everything in the global scope. Unlike any other procedure, its context is not global scope, so it can only be executed in the context of the procedure where the Execute statement occurred. However, if the same Execute statement is invoked outside of a procedure (i.e., in global scope), not only does it inherit everything in global scope, but it can also be called from anywhere, since its context is global. The following example illustrates this behavior:
Dim X   ‘ Declare X in global scope.
X = “Global”   ‘ Assign global X a value.
Sub Proc1   ‘ Declare procedure.
   Dim X   ‘ Declare X in local scope.
   X = “Local”   ‘ Assign local X a value.
            ’ The Execute statement here creates a
            ’ procedure that, when invoked, prints X.
            ’ It print the global X because Proc2
            ’ inherits everything in global scope.
   Execute “Sub Proc2: Print X: End Sub”
   Print Eval(“X”)   ‘ Print local X.
   Proc2   ‘ Invoke Proc2 in Proc1′s scope.
End Sub
Proc2   ‘ This line causes an error since 
        ’ Proc2 is unavailable outside Proc1.
Proc1   ‘ Invoke Proc1.
   Execute “Sub Proc2: Print X: End Sub”
Proc2   ‘ This invocation succeeds because Proc2
        ’ is now available globally

VB script function & variable

Array Function:  Returns a Variant containing an array. 
Array(arglist)
The required arglist argument is a comma-delimited list of values that are assigned to the elements of an array contained with the Variant. If no arguments are specified, an array of zero length is created. 
Remarks
The notation used to refer to an element of an array consists of the variable name followed by parentheses containing an index number indicating the desired element. In the following example, the first statement creates a variable named A. The second statement assigns an array to variable A. The last statement assigns the value contained in the second array element to another variable. 
Dim A
A = Array(10,20,30)
B = A(2)   ‘ B is now 30.
Note   A variable that is not declared as an array can still contain an array. Although a Variant variable containing an array is conceptually different from an array variable containing Variant elements, the array elements are accessed in the same way.
Dim Statement: Declares variables and allocates storage space
Variables declared with Dim at the script level are available to all procedures within the script. At the procedure level, variables are available only within the procedure. 
You can also use the Dim statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Dim statement, an error occurs.
Note   When you use the Dim statement in a procedure, you generally put the Dim statement at the beginning of the procedure.
The following examples illustrate the use of the Dim statement: 
Dim Names(9)       ‘ Declare an array with 10 elements.
Dim Names()        ’ Declare a dynamic array.
Dim MyVar, MyNum   ‘ Declare two variables.
ReDim Statement
Declares dynamic-array variables, and allocates or reallocates storage space at procedure level.
The ReDim statement is used to size or resize a dynamic array that has already been formally declared using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts). You can use the ReDim statement repeatedly to change the number of elements and dimensions in an array.
If you use the Preserve keyword, you can resize only the last array dimension, and you can’t change the number of dimensions at all. For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension and still preserve the contents of the array. 
The following example shows how you can increase the size of the last dimension of a dynamic array without erasing any existing data contained in the array. 
ReDim X(10, 10, 10)
. . .
ReDim Preserve X(10, 10, 15)
Caution   If you make an array smaller than it was originally, data in the eliminated elements is lost.
Private Statement: 
Declares private variables and allocates storage space. Declares, in a Class block, a private variable.
Private statement variables are available only to the script in which they are declared.
You can also use the Private statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs.
Private MyNumber   ‘ Private Variant variable.
Private MyArray(9)   ‘ Private array variable.
   ‘ Multiple Private declarations of Variant variables.
Public Statement:
Declares public variables and allocates storage space. Declares, in a Class block, a private variable.
Public statement variables are available to all procedures in all scripts.
You can also use the Public statement with empty parentheses to declare a dynamic array. After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs.
The following example illustrates the use of the Public statement: 
Public MyNumber   ‘ Public Variant variable.
Public MyArray(9)   ‘ Public array variable.
   ‘ Multiple Public declarations of Variant variables.
Public MyNumber, MyVar, YourNumber
Set Statement:
Assigns an object reference to a variable or property. 
The Dim, Private, Public, or ReDim statements only declare a variable that refers to an object. No actual object is referred to until you use the Set statement to assign a specific object.
Dim fso, d, s
   Set fso = CreateObject(“Scripting.FileSystemObject”)
   Set d = fso.GetDrive(fso.GetDriveName(drvPath))
   s = “Drive ” & UCase(drvPath) & ” – “ 
   s = s & d.VolumeName  & “<BR>”
   s = s & “Free Space: ” & FormatNumber(d.FreeSpace/1024, 0) 
   s = s & ” Kbytes”
   ShowFreeSpace = s
Is Operator:
 Compares two object reference variables.
If object1 and object2 both refer to the same object, result is True; if they do not, result is False. Two variables can be made to refer to the same object in several ways.
In the following example, A has been set to refer to the same object as B: 
Set A = B
The following example makes A and B refer to the same object as C: 
Set A = C
Set B = C
Assignment Operator (=) Assigns a value to a variable or property.
Comparison Operators Used to compare expressions.
The Is operator has specific comparison functionality that differs from the operators in the following table. The following table contains a list of the comparison operators and the conditions that determine whether result is True, False, or Null: 

Operator Description True if False if Null if   
< Less than expression1 < expression2 expression1 >= expression2 expression1 or expression2 = Null   
<= Less than or equal to expression1 <= expression2 expression1 > expression2expression1 or expression2 = Null   
> Greater than expression1 > expression2 expression1 <= expression2 expression1 or expression2 = Null   
>= Greater than or equal to expression1 >= expression2 expression1 < expression2expression1 or expression2 = Null   
= Equal to expression1 = expression2 expression1 <> expression2 expression1 or expression2 = Null   
<> Not equal to expression1 <> expression2 expression1 = expression2 expression1 or expression2 = Null  
When comparing two expressions, you may not be able to easily determine whether the expressions are being compared as numbers or as strings. 
The following table shows how expressions are compared or what results from the comparison, depending on the underlying subtype: 

If Then   
Both expressions are numeric Perform a numeric comparison.   
Both expressions are strings Perform a string comparison.   
One expression is numeric and the other is a string The numeric expression is less than the string expression.   
One expression is Empty and the other is numeric Perform a numeric comparison, using 0 as the Empty expression.   
One expression is Empty and the other is a string Perform a string comparison, using a zero-length string (“”) as the Empty expression.   
Both expressions are Empty The expressions are equal.  
Operator Precedence When several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator precedence. Parentheses can be used to override the order of precedence and force some parts of an expression to be evaluated before other parts. Operations within parentheses are always performed before those outside. Within parentheses, however, normal operator precedence is maintained.
When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last. Comparison operators all have equal precedence; that is, they are evaluated in the left-to-right order in which they appear. Arithmetic and logical operators are evaluated in the following order of precedence:

Arithmetic Comparison Logical   
Negation (-) Equality (=) Not   
Exponentiation (^) Inequality (<>) And   
Multiplication and division (*, /) Less than (<) Or   
Integer division (\) Greater than (>) Xor   
Modulus arithmetic (Mod) Less than or equal to (<=) Eqv   
Addition and subtraction (+, -) Greater than or equal to (>=) Imp   
String concatenation (&) Is &  
When multiplication and division occur together in an expression, each operation is evaluated as it occurs from left to right. Likewise, when addition and subtraction occur together in an expression, each operation is evaluated in order of appearance from left to right.
The string concatenation operator (&) is not an arithmetic operator, but in precedence it does fall after all arithmetic operators and before all comparison operators. The Is operator is an object reference comparison operator. It does not compare objects or their values; it checks only to determine if two object references refer to the same object.
IsArray Returns a Boolean value indicating whether a variable is an array.
IsArray returns True if the variable is an array; therewise, it returns False. IsArray is especially useful with variants containing arrays. 
The following example uses the IsArray function to test whether MyVariable is an array: 
Dim MyVariable
Dim MyArray(3)
MyArray(0) = “Sunday”
MyArray(1) = “Monday”
MyArray(2) = “Tuesday”
MyVariable = IsArray(MyArray) ‘ MyVariable contains “True”.

Vb Scripts: Round, Int and Fix & CINT functions

Round:
Returns a number rounded to a specified number of decimal places The following example uses the Round function to round a number to two decimal places: Dim MyVar, pi pi = 3.14159 MyVar = Round(pi, 2) ‘ MyVar contains
Int and Fix functions:
Returns the integer portion of a number. Fix(number) is equivalent to: Sgn(number) * Int(Abs(number)) The following examples illustrate how the Int and Fix functions return integer portions of numbers: MyNumber = Int(99.8) ‘ Returns 99. MyNumber = Fix(99.2) ‘ Returns 99. MyNumber = Int(-99.8) ‘ Returns -100. MyNumber = Fix(-99.8) ‘ Returns -99. MyNumber = Int(-99.2) ‘ Returns -100. MyNumber = Fix(-99.2) ‘ Returns -99.
CINT:
Returns an expression that has been converted to a Variant of subtype Integer The following example uses the CInt function to convert a value to an Integer: Dim MyDouble, MyInt MyDouble = 2345.5678 ‘ MyDouble is a Double. MyInt = CInt(MyDouble) ‘ MyInt contains 2346. Note CInt differs from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. When the fractional part is exactly 0.5, the CInt function always rounds it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.

VBScript functions

Functions in VbScript
Date, Time Functions
Function
CDate:
Converts a valid date and time expression to the variant of subtype Date
Date :
Returns the current system date
DateAdd:
Returns a date to which a specified time interval has been added
DateDiff:
Returns the number of intervals between two dates
DatePart:
Returns the specified part of a given date
DateSerial:
Returns the date for a specified year, month, and day
DateValue:
Returns a date
Day:
Returns a number that represents the day of the month (between 1 and 31)
FormatDateTime:
Returns an expression formatted as a date or time
Hour:
Returns a number that represents the hour of the day (between 0 and 23, inclusive)
IsDate:
Returns a Boolean value that indicates if the evaluated expression can be converted to a date
Minute:
Returns a number that represents the minute of the hour (between 0 and 59)
Month:
Returns a number that represents the month of the year (between 1 and 12)
MonthName :
Returns the name of a specified month
Now :
Returns the current system date and time
Second :
Returns a number that represents the second of the minute (between 0 and 59)
Time :
Returns the current system time
Timer :
Returns the number of seconds since 12:00 AM
TimeSerial :
Returns the time for a specific hour, minute, and second
TimeValue :
Returns a time
Weekday :
Returns a number that represents the day of the week (between 1 and 7)
WeekdayName :
Returns the weekday name of a specified day of the week
Year :
Returns a number that represents the year
**********************************************
Conversion Functions
Function
Asc:
Converts the first letter in a string to ANSI code
CBool:
Converts an expression to a variant of subtype Boolean
CByte:
Converts an expression to a variant of subtype Byte
CCur:
Converts an expression to a variant of subtype Currency
CDate:
Converts a valid date and time expression to the variant of subtype Date
CDbl:
Converts an expression to a variant of subtype Double
Chr:
Converts the specified ANSI code to a character
CInt:
Converts an expression to a variant of subtype Integer
CLng:
Converts an expression to a variant of subtype Long
CSng:
Converts an expression to a variant of subtype Single
CStr:
Converts an expression to a variant of subtype String
Hex:
Returns the hexadecimal value of a specified number
Oct:
Returns the octal value of a specified number
********************************************************
Format Functions
FormatCurrency:
Returns an expression formatted as a currency value
FormatDateTime:
Returns an expression formatted as a date or time
FormatNumber:
Returns an expression formatted as a number
FormatPercent:
Returns an expression formatted as a percentage
***********************************************
Math Functions
Abs
Returns the absolute value of a specified number
Atn
Returns the arctangent of a specified number
Cos
Returns the cosine of a specified number (angle)
Exp
Returns e raised to a power
Hex
Returns the hexadecimal value of a specified number
Int
Returns the integer part of a specified number
Fix
Returns the integer part of a specified number
Log
Returns the natural logarithm of a specified number
Oct
Returns the octal value of a specified number
Rnd
Returns a random number less than 1 but greater or equal to 0
Sgn
Returns an integer that indicates the sign of a specified number
Sin
Returns the sine of a specified number (angle)
Sqr
Returns the square root of a specified number
Tan
Returns the tangent of a specified number (angle)
*********************************************
Array Functions
Array
Returns a variant containing an array
Filter
Returns a zero-based array that contains a subset of a string array based on a filter criteria
IsArray
Returns a Boolean value that indicates whether a specified variable is an array
Join
Returns a string that consists of a number of substrings in an array
LBound
Returns the smallest subscript for the indicated dimension of an array
Split
Returns a zero-based, one-dimensional array that contains a specified number of substrings
UBound
Returns the largest subscript for the indicated dimension of an array
*****************************\
String Functions
InStr
Returns the position of the first occurrence of one string within another. The search begins at the first character of the string
InStrRev
Returns the position of the first occurrence of one string within another. The search begins at the last character of the string
LCase
Converts a specified string to lowercase
Left
Returns a specified number of characters from the left side of a string
Len
Returns the number of characters in a string
LTrim
Removes spaces on the left side of a string
RTrim
Removes spaces on the right side of a string
Trim
Removes spaces on both the left and the right side of a string
Mid
Returns a specified number of characters from a string
Replace
Replaces a specified part of a string with another string a specified number of times
Right
Returns a specified number of characters from the right side of a string
Space
Returns a string that consists of a specified number of spaces
StrComp
Compares two strings and returns a value that represents the result of the comparison
String
Returns a string that contains a repeating character of a specified length
StrReverse
Reverses a string
UCase
Converts a specified string to uppercase
********************************
Other Functions
Function Description
CreateObject
Creates an object of a specified type
Eval Evaluates an expression and returns the result
GetLocale
Returns the current locale ID
GetObject
Returns a reference to an automation object from a file
GetRef
Allows you to connect a VBScript procedure to a DHTML event on your pages
InputBox
Displays a dialog box, where the user can write some input and/or click on a button, and returns the contents
IsEmpty
Returns a Boolean value that indicates whether a specified variable has been initialized or not
IsNull
Returns a Boolean value that indicates whether a specified expression contains no valid data (Null)
IsNumeric
Returns a Boolean value that indicates whether a specified expression can be evaluated as a number
IsObject
Returns a Boolean value that indicates whether the specified expression is an automation object
LoadPicture
Returns a picture object. Available only on 32-bit platforms
MsgBox
Displays a message box, waits for the user to click a button, and returns a value that indicates which button the user clicked
RGB
Returns a number that represents an RGB color value
Round
Rounds a number
ScriptEngine
Returns the scripting language in use
ScriptEngineBuildVersion
Returns the build version number of the scripting engine in use
ScriptEngineMajorVersion
Returns the major version number of the scripting engine in use
ScriptEngineMinorVersion
Returns the minor version number of the scripting engine in use
SetLocale
Sets the locale ID and returns the previous locale ID
TypeName
Returns the subtype of a specified variable
VarType
Returns a value that indicates the subtype of a specified variable
****************************************