Page #27 (Chapter 3 - Building ASP Applications)

Chapter 3 - Building ASP Applications

Visual Basic Developers Guide to ASP and IIS
A. Russell Jones
  Copyright 1999 SYBEX Inc.

Using the Scripting.Dictionary Object
A Scripting.Dictionary object is similar to a Visual Basic collection object, but faster and much more flexible. The documentation describes it as similar to a Perl associative array, if that helps you. Both the VB collection object and the Dictionary object have keys, values, and Add, Remove, and Item methods; however, for the Dictionary Add method you must supply the key first, then the value. The Add method for a VB collection requires the value first, then the key. I find the Dictionary object syntax more natural. In addition, the Dictionary object has methods to get the list of keys or values, and has an Exists method, which lets you find out whether a specified key exists.
In VB, to find out whether a Dictionary key exists, you would use code like this:
Dim d as new Dictionary
d.Add "Name", "Bill"
Debug.Print d.Exists("Name") ' prints True
In contrast, to find out whether a key exists in a VB collection object, you have to use On Error Resume Next, attempt to retrieve the value, and check for errors.
Sub keyExists(c as Collection, aKey as string) as Boolean
     Dim V as variant
     On Error Resume Next
     V = c(aKey)
     KeyExists = (Err.Number <> 5)             
End Sub
  Note The preceding code explicitly checks for Err.Number=5 rather than just checking if any error occurred. This is because if the key exists, but the associated value is an object variable rather than a scalar variable, you will get Error 450 instead of Error 5.
The keys are strings. The values are variants, which means that they can be any data type, including objects. You can imagine that a Dictionary object looks like a table with two columns, as shown in Table 3.1.
Table 3.1: Dictionary Object Keys and Values Example
Key
Value
"FirstName"
"John"
"LastName"
"Davis"
"City"
"Albuquerque"
"State"
"New Mexico"
"Address"
"1723 Candelaria"
"Age"
42
"Telephones"
(Array) "555-555-5555", "555-555-5556"
The keys must be unique. Having unique keys enables the Dictionary object to keep a sorted key list so that it can find any specific value with a fast binary lookup. This makes the Dictionary object larger than an array of the same size but much more efficient at finding values quickly.
Several other features of the Scripting.Dictionary object are worth noting. Unlike a VB collection object, you don't have to use the Add method to add new items; if you assign a value to a key that doesn't exist, the Dictionary creates a new key for you.
You can change the values of associations in the Dictionary through simple assignment—you don't have to remove the key and then add it again with a new value. Here's a VBScript example:
Dim d
Set d = Server.CreateObject("Scripting.Dictionary")
d("newKey") = "This is a new key"
Response.Write d("newKey") ' displays "This is a new key"
d("newKey") = "This is a changed value"
Response.Write d("newKey") ' displays "This is a changed value"
Response.Write d("NewKey") ' fails to display
When this code runs, it creates a new Dictionary object with one key, newKey, and one value, the string "This is a new key", which displays in the browser. The code then assigns a new value to the association with the key newKey, and displays that. Finally, to show that keys in the Dictionary object are case sensitive by default, the program tries to display the key NewKey. That statement fails to display because the Dictionary object can't find the key, but unlike referencing missing keys in a VB Collection object, it doesn't cause a runtime error.
You can control how a Dictionary object treats case sensitivity in keys by using the CompareMode property. There are three CompareMode constants defined in the Microsoft Scripting Runtime Library: BinaryCompare, Text-Compare, and DatabaseCompare, which are equivalent (and equal in value) to the VBScript CompareMode constants vbBinaryCompare, vbTextCompare, and vbDatabaseCompare. One restriction: You must set the CompareMode property before adding any items to the Dictionary; otherwise, a runtime error occurs. To avoid having to define the Scripting CompareMode constants, use the built-in VBScript CompareMode constants. Alter the code so it looks like this:
Dim d
Set d = Server.CreateObject("Scripting.Dictionary")
d.CompareMode = vbTextCompare
d("newKey") = "This is a new key"
Response.Write d("newKey") ' displays "This is a new key"
d("newKey") = "This is a changed value"
Response.Write d("newKey") ' displays "This is a changed value"
Response.Write d("NewKey") ' displays "This is a changed value"
Now, when you browse to the page, the browser displays all three lines.
Although the Object Browser lists the DatabaseCompare constant as one of the available CompareMode constants, the documentation for the Dictionary object doesn't include it as a valid value. Using it doesn't raise an error, though. As an experiment, set the CompareMode property of the Dictionary object to vbDatabaseCompare and run the file. Running it the first time appears to cause the Dictionary to treat keys as case insensitive; however, if you refresh the file, the third line disappears. Add a line to display the CompareMode property. The first time, the file properly displays 2, the value of the vbDatabaseCompare constant. If you run the file again, though, it will display the CompareMode property as 0, which corresponds to the vbBinaryCompare constant. I don't have a good explanation for this behavior (yet). Don't set the CompareMode property to vbDatabaseCompare.
Remember that, by default, Dictionary keys are case sensitive. This case sensitivity, coupled with the lack of a runtime error when you reference missing keys, goes against the case-insensitive theme of VB and VBScript and caused me several hours of frustrated debugging before I realized the reason. I don't like using the Dictionary in case-sensitive mode. If you don't either, you can avoid this problem altogether by wrapping the code that creates the Dictionary object in a function:
Function newDictionary()
     Set newDictionary = Server.CreateObject _
         ("Scripting.Dictionary")
     newDictionary.CompareMode = vbTextCompare
End Function
The function returns a case-insensitive Dictionary object.
  Note Like VB, VBScript uses the name of the function to return values; it creates a local variable with the same name as the function. You can often use this feature to make your code more readable, save yourself typing, and avoid the overhead of creating an extra local variable.
Table 3.2 shows the complete list of methods and properties for the Scripting .Dictionary object.
Table 3.2: Scripting.Dictionary Object Methods and Properties
Name
Type
Description
Add key, value
Method
Adds a new string key to the Dictionary associated with the specified value. If the key already exists, an error occurs.
CompareMode (CompareMethod)
Property Get, Let
Controls the way the Dictionary object compares keys. Sets or returns one of the CompareMethod enumeration constants.
vbBinaryCompare (0) (case-sensitive)
vbTextCompare (1) (case-insensitive)
vbDatabaseCompare (2) (N/A)
Count
Property Get (read-only)
Returns the count of the number of associations in the Dictionary object.
Exists key
Property Get (read-only)
Returns a Boolean value that shows whether the specified key exists.
Item key or index
Property, Get, Let, Set
Returns or sets a value associated with the specified string key or integer index.
Items
Method
Returns a variant array of all of the values currently stored in the Dictionary.
Key key
Property Let (write-only)
Changes a string key from one string to another.
Keys
Method
Returns a variant array of all of the keys currently stored in the Dictionary.
Remove key
Method
Removes the specified key, if it exists.
RemoveAll
Method
Removes all keys.
  Note The Microsoft VBScript documentation doesn't list the vbDatabaseCompare as a valid CompareMode value for a Dictionary object. Although it doesn't raise an error if you use it, it exhibits some strange behavior, so don't use it.



Visual Basic Developer[ap]s Guide to ASP and IIS
Visual Basic Developer[ap]s Guide to ASP and IIS
ISBN: 782125573
EAN: N/A
Year: 2005
Pages: 98

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net