CGI: VBScript dictionary - DB

From The Uniform Server Wiki
Jump to navigation Jump to search

VBScript dictionary - DB

If you have chosen to use VBScript (or JavaScript) as your main scripting language you probably are not going to use a MySQL server. Although you can access a MySQL server from either of these scripting languages you need to install suitable drivers. This prevents your scripts and server being portable an alternative is to use a flat file structure for storing data. The following covers using the VBScript dictionary in combination with a file for data storage and retrieval. This combination is an ideal alternative for basic dynamic web sites.

VBScript dictionary

The Dictionary object stores name/value pairs (referred to as the key and item respectively) in the equivalent of an array. The key is a unique identifier associated with an item. An item can be of any type such as strings, dates, numbers, and so on. A dictionary can be iterated through using a “For Each loop”. Unlike arrays you can iterate on either keys or items. A minimalist set of properties and methods along with a dictionary’s flexible interaction makes it an ideal candidate for use as a database.

Create dictionary object

To create a dictionary object use the following syntax:

Dim my_object
Set my_object = CreateObject("Scripting.Dictionary")

Properties

Syntax Description

x = my_object.CompareMode
my_object.CompareMode = comparison_mode

The CompareMode property is used to set and return the key's string comparison mode which determines how keys are matched while looking up or searching.

x = my_object.Count

The Count property is used to determine the number of key/item pairs in the Dictionary object.

x = my_object.Item(key)
my_object.Item(key) = itemvalue

The Item property allows us to retreive the value of an item in the collection designated by the specified key argument and also to set that value by using itemvalue.

my_object.Key(keyvalue) = newkeyvalue

The Key property lets us change the key value of an existing key/item pair.

Methods

Syntax Description

my_object.Add keyvalue, itemvalue

The Add method is used to add a new key/item pair to a Dictionary object.

my_object.Exists(keyvalue)

The Exists method is used to determine whether a key already exists in the specified Dictionary. Returns True if it does and False otherwise.

array_name = my_object.Items

The Items method is used to retreive all of the items in a particular Dictionary object and store them in an array.

arrayname = my_object.Keys

The Keys method is used to retreive all of the keys in a particular Dictionary object and store them in an array.

my_object. Remove(keyvalue)

The Remove method is used to remove a single key/item pair from the specified Dictionary object.

my_object.RemoveAll

The RemoveAll method is used to remove all the key/item pairs from the specified Dictionary object.

Top

Example scripts

The following code examples show how to use the dictionary object’s properties and methods.

  • For each example create a new file in folder MiniServer\www\vbs_test
  • To run start server and type the following into browser address bar: http://localhost:8081/vbs_test/filename

Substitute filename with appropriate file you wish to run: For example: http://localhost:8081/bs_test/db1.wsf

db1.wsf - How to create a Dictionary

  • How to create a Dictionary.
  • How to add key/item pairs.
  • Note: Spaces are allowed in keys.
'!c:/windows/system32/cscript //nologo
<job>
<script language="VBScript">
Wscript.Echo "Content-type: text/html"&vbLF&vbLF

Dim books
Set books = CreateObject("Scripting.Dictionary")
books.Add "book_1",  "Cars"
books.Add "book_2",  "Easy PHP"
books.Add "book_3",  "Home cooking 1"
books.Add "book 3",  "Home cooking 2"

'--Spaces are allowed in keys
Wscript.Echo "Spaces are allowed in keys."

Wscript.Echo "<br /><br />"

Wscript.Echo "The key 'book_3' points to "
Wscript.Echo "is " & books.Item("book_3")
 
Wscript.Echo "<br />"

Wscript.Echo "The key 'book 3' points to "
Wscript.Echo "is " & books.Item("book 3")

</script>
</job>

 

db2.wsf - How to remove a single key/item pair

  • How to remove a single key/item pair.
  • First check the key exists.
  • If it exists delete.
'!c:/windows/system32/cscript //nologo
<job>
<script language="VBScript">
Wscript.Echo "Content-type: text/html"&vbLF&vbLF

Dim books
Set books = CreateObject("Scripting.Dictionary")
books.Add "book_1",  "Cars"
books.Add "book_2",  "Easy PHP"
books.Add "book_3",  "Home cooking 1"
books.Add "book 3",  "Home cooking 2"

If books.Exists("book 3") Then 'If key exists
  books.Remove("book 3")       'Delete it
End If

Wscript.Echo "The key 'book_3' points to "
Wscript.Echo "is " & books.Item("book_3")
 
Wscript.Echo "<br />"

Wscript.Echo "The key 'book 3' points to "
Wscript.Echo "is " & books.Item("book 3")

</script>
</job>

Top

These two scripts show how to scan an entire dictionary using either its keys or items.

db3.wsf - How to print all Dictionary keys

  • How to print all Dictionary keys.
  • Uses the for each loop.
'!c:/windows/system32/cscript //nologo
<job>
<script language="VBScript">
Wscript.Echo "Content-type: text/html"&vbLF&vbLF

Dim address_book
Set address_book = CreateObject("Scripting.Dictionary")
address_book.Add "mike smith",       "m_smith@me.com"
address_book.Add "mike smith info",  "Lives in Cambridge"
address_book.Add "dave smith",       "d_smith@us.net"
address_book.Add "dave smith info",  "Lives in London"

key_array = address_book.Keys     'Get all keys
For Each strKey in key_array      'Scan array
 Wscript.Echo strKey & "<br />"   'and print key values
Next

</script>
</job>

 

db4.wsf - How to print all Dictionary Items

  • How to print all Dictionary Items.
  • Uses the for each loop.
'!c:/windows/system32/cscript //nologo
<job>
<script language="VBScript">
Wscript.Echo "Content-type: text/html"&vbLF&vbLF

Dim address_book
Set address_book = CreateObject("Scripting.Dictionary")
address_book.Add "mike smith",       "m_smith@me.com"
address_book.Add "mike smith info",  "Lives in Cambridge"
address_book.Add "dave smith",       "d_smith@us.net"
address_book.Add "dave smith info",  "Lives in London"

item_array = address_book.Items     'Get all Items
For Each strItem in item_array      'Scan array
 Wscript.Echo strItem & "<br />"    'and print Item values
Next

</script>
</job>

Top

These two scripts show how to perform a selective search and list the entire content of the dictionary (database). When you design any database they require a structure specific to the application. To highlight this both scripts use a basic record structure as an example.

db5.wsf - How to perform a selective search

  • How to perform a selective search.
  • Note data is organised in records.
'!c:/windows/system32/cscript //nologo
<job>
<script language="VBScript">
Wscript.Echo "Content-type: text/html"&vbLF&vbLF

Dim address_book
Set address_book = CreateObject("Scripting.Dictionary")

'--Record 1
address_book.Add "mike smith",          "--name--"
address_book.Add "mike smith email",    "m_smith@me.com"
address_book.Add "mike smith location", "Cambridge"
address_book.Add "mike smith info",     "Any input ;\n etc"

'--Record 2
address_book.Add "dave smith",          "--name--"
address_book.Add "dave smith email",    "d_smith@us.net"
address_book.Add "dave smith location", "London"
address_book.Add "dave smith info",     "More data + etc "

'--List all names
key_array = address_book.Keys                'Get all Keys
For Each strKey in key_array                 'Scan array
 If address_book.Item(strKey) = "--name--" Then 
   Wscript.Echo strKey  & "<br />"      'display name
 End If
Next

</script>
</job>

 

db6.wsf - How to list all data in Dictionary

  • How to list all data in Dictionary.
  • Important required for saving database to file.
'!c:/windows/system32/cscript //nologo
<job>
<script language="VBScript">
Wscript.Echo "Content-type: text/html"&vbLF&vbLF

Dim address_book
Set address_book = CreateObject("Scripting.Dictionary")

'--Record 1
address_book.Add "mike smith",           "--name--"
address_book.Add "mike smith email",     "m_smith@me.com"        
address_book.Add "mike smith location",  "Cambridge"
address_book.Add "mike smith info",      "Any input ;\n etc"

'--Record 2
address_book.Add "dave smith",           "--name--"
address_book.Add "dave smith email",     "d_smith@us.net"
address_book.Add "dave smith location",  "London"
address_book.Add "dave smith info",      "More data + etc "

'***** List all keys and Items *****
key_array = address_book.Keys       'Get all Keys
For Each strKey in key_array        'Scan array
 Wscript.Echo strKey & " = " & address_book.Item(strKey) & "<br />"
Next



</script>
</job>

Top

Saving Dictionary to file

The Dictionary can be saved in a flat file format. For example each line saved to a file consists of a key and item separated by a comma. File structure shown below.

Problem

The simple structure shown on right has one serious problem.
The Key and Item may themselves contain a comma (delimiter)
or a line end character.

Key1,Item1\n
Key2,Item2\n
Key3,Item3\n
Key4,Item4\n
etc.
EOF

Solution

Think of the comma and line end as being special characters, a solution immediately presents itself in the for of Escape() and Unescape() functions covered on the URL Encoding page.

Before saving to a file escape both the Key and Item, these will then never contain a comma or line end character.

The following VBScript skeleton code shows how to save and read a dictionary to and from a file:

Save to file:

 Dim objFSO,objFile,line
 Const ForReading = 1, ForWriting = 2, ForAppending = 8, ReadOnly = 1

 Set objFSO  = CreateObject("Scripting.FileSystemObject")       'Create file object
 Set objFile = objFSO.OpenTextFile(FileName, ForWriting, True)  'Open for write

 '...Get Key array                                              'Save keys to array
 '...loop read Key-Index pair                                   'Use this to iterate 
 '...Get Key and Item                                           'dictionary get key-item pairs
 line = escape(Key) & "," & escape(Item)                        'Encode Key and Item
 objFile.WriteLine(line)                                        'Write to file
 '...get next pair

 objFile.Close

Read file

 Dim objFSO,objFile,line
 Const ForReading = 1, ForWriting = 2, ForAppending = 8, ReadOnly = 1

 Set objFSO = CreateObject("Scripting.FileSystemObject") 'Create file object
 Set objFile = objFSO.OpenTextFile(FileName, ForReading) 'Open for read

 Do Until objFile.AtEndOfStream        'Read to end of file
   line = objFile.ReadLine             'Read line from file 
   '...split line                      'Extract Key and Item
   '...unescape                        'Decode Key and Item
   '...add to Dictionary               'Save Key and Item to Dictionary
 Loop                                  'Read another line
 objFile.Close

Top

Summary

Above introduced the VBScript dictionary it is very easy to use and ideal for a database engine. For permanent storage a file is required, skeleton code and its data structure were covered.

Where to next

Next page covers expanding the above to provide dictionary file read and write functions.

Top