CGI: VBScript dictionary file

From The Uniform Server Wiki
Revision as of 23:21, 7 November 2011 by Ric (talk | contribs) (Created page with "{{Nav CGI}} '''VBScript dictionary file''' Previous page covered using the VBScript dictionary for a database engine. The database dictionary r...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

VBScript dictionary file

Previous page covered using the VBScript dictionary for a database engine. The database dictionary resides in memory hence it is volatile for permanent storage a file is required. This page covers two functions for reading and writing the dictionary database to a file.

File structure

The file has a flat structure meaning it consists of key and item pairs separated by a comma delimiter. Each entry is saved as a single text line.

Keys and items may contain the comma separator and or new line character these would break the line format if directely saved to a file. To resole any conflicts keys and items are encoded before being saved using the escape function. When the file is read the keys and items are decoded using the unescape function.

Top

Create a database dictionary

Databases must be given a unique file name for example address_book.txt generally they reside in the same folder as the script. Its not mandatory you can use a different folder however the file name must then include its full path.

Each database file you are going to use is declared as a constant for example:

  • Const DB_FILE1 = "address_book.txt"
  • Const DB_FILE2 = "guest_book.txt"

     OR

  • Const DB_FILE1 = "C:\\some_folder\address_book.txt"
  • Const DB_FILE2 = "C:\\some_folder\guest_book.txt"

After defining database file constants you need to create corresponding VBScript dictionaries for each database for example:

  • Set address_book = CreateObject("Scripting.Dictionary")
  • Set guest_book = CreateObject("Scripting.Dictionary")

To use a database the following are probably a minimum set of functions required:

  • clear_db(db_name,db_file_name) - Clears database dictionary content
  • save_db(db_name,db_file_name) - Save database dictionary to file
  • load_db(db_name,db_file_name) - Read database file and load content into database dictionary
  • reload_db(db_name,db_file_name) - Clear database dictionary and load database file into database dictionary

These are covered in the next sections.

Top

Clear database dictionary

This function takes as paramter the dictionary object db_name. For example:

clear_db(address_book)
Function clear_db(db_name)                                             
  db_name.RemoveAll
End Function

Top

Save database dictionary to file

  • The database file is opened for writing.
  • All keys are loaded into an array.
  • This key array is iterated through using a For Each loop.
  • Key and Item is encoded using the escape funtion.
  • These are concatonated along with a comma seperator.
  • The resulting line is written to the database file.

This function takes as paramter the dictionary object db_name
and file name file_name. For example:

save_db(address_book,DB_FILE1)
Function save_db(db_name,file_name)
 Dim objFSO,objFile,line,key_array,strKey
 Const ForReading = 1, ForWriting = 2, ForAppending = 8, ReadOnly = 1

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

 key_array = db_name.Keys                                      'Get all Keys
 For Each strKey in key_array                                  'Scan array
   line = escape(strKey) & "," & escape(db_name.Item(strKey))  'Encode 
   objFile.WriteLine(line)                                     'Write to file  
 Next

 objFile.Close
End Function

Top

Load database file into database dictionary

  • The database file is opened for reading.
  • The file is read line-by-line using a Do loop.
  • Each line is split giving the encoded Index and Item.
  • These are decoded using the unescape function.
  • The resulting pair is added to the dictionary.

This function takes as paramter the dictionary object db_name
and file name file_name. For example:

load_db(address_book,DB_FILE1)
Function load_db(db_name,file_name)
 Dim objFSO,objFile,line,pair_array,decoded_index,decoded_item
 Const ForReading = 1, ForWriting = 2, ForAppending = 8, ReadOnly = 1

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

 Do Until objFile.AtEndOfStream            'Read to end of file
   line = objFile.ReadLine                 'Read line from file 
   pair_array = split(line,",")            'Split Index-Item pair
   decoded_index = unescape(pair_array(0)) 'Decode Index
   decoded_item  = unescape(pair_array(1)) 'Decode Item
   db_name.Add decoded_index,decoded_item  'Add to Dictionary
 Loop                                      'Read another line
 objFile.Close
End Function

Top

Reload database file into database dictionary

This function takes as paramter the dictionary object db_name
and file name file_name. For example:

reload_db(address_book,DB_FILE1)
Function reload_db(db_name,file_name)
  db_name.RemoveAll                   'Delete dictionary content
  call load_db(db_name,file_name)     'Load DB from file
End Function

Top

Test script 14 - Database demo

In test folder vbs_test create a new file test14.wsf with content shown on right.

Start server and run script by typing the following http://localhost:8081/vbs_test/test14.wsf into browser address bar.

Overview

This test script contains all the above functions including an additional one to list content of the dictionary database.

Generally these functions would be included in an external file containing a set of common functions.

Section 1

Creating a new database requires two lines as follows:

First line creates a constant defining path to the database file address_book.txt (File is local meaning in the same folder as script hence only the file name is required.) Second line creates the database dictionary for consistency uses same name as the file address_book.

Section 2

The database dictionary is populated using the dictionary’s Add method.

In this demo the lines are hard coded, generally a database would be populated from user input such as forms.

Section 3

This section saves the database dictionary to the database file.

When to save data is generally application specific. You can save data every time new data is added to the dictionary. Or wait until a complete record has been added.

Note: Perhaps a new function that appends data to the database file would be more appropriate.

Section 4 This test first clears the database dictionary.

A message is output indicating start of test. The database dictionary content is listed nothing is displayed because the database was cleared.

Section 5

This test first loads the database file into the database dictionary.

A message is output indicating start of test. The database dictionary content is listed. The hard coded data that was saved to the file will be listed confirming correct operation.

Output as follows:

DB Content 1?
DB Content 2
mike smith = --name--
mike smith email = m_smith@me.com
mike smith location = Cambridge
mike smith info = Any input ;\n etc
'!c:/windows/system32/cscript //nologo
<job>
<script language="VBScript">
Wscript.Echo "Content-type: text/html"&vbLF&vbLF

'--Clear Function
Function clear_db(db_name)
  db_name.RemoveAll
End Function

'--Reload function
Function reload_db(db_name,file_name)
  db_name.RemoveAll
  call load_db(db_name,file_name)           'Load DB from file
End Function

'--Load Function
Function load_db(db_name,file_name)
 Dim objFSO,objFile,line,pair_array,decoded_index,decoded_item
 Const ForReading = 1, ForWriting = 2, ForAppending = 8, ReadOnly = 1
 Set objFSO = CreateObject("Scripting.FileSystemObject") 'Create file object
 Set objFile = objFSO.OpenTextFile(file_name, ForReading) 'Open for read
 Do Until objFile.AtEndOfStream            'Read to end of file
   line = objFile.ReadLine                 'Read line from file 
   pair_array = split(line,",")            'Split Index-Item pair
   decoded_index = unescape(pair_array(0)) 'Decode Index
   decoded_item  = unescape(pair_array(1)) 'Decode Item
   db_name.Add decoded_index,decoded_item  'Add to Dictionary
 Loop                                      'Read another line
 objFile.Close
End Function

'--Save function
Function save_db(db_name,file_name)
 Dim objFSO,objFile,line,key_array,strKey
 Const ForReading = 1, ForWriting = 2, ForAppending = 8, ReadOnly = 1
 Set objFSO  = CreateObject("Scripting.FileSystemObject")       'Create file object
 Set objFile = objFSO.OpenTextFile(file_name, ForWriting, True) 'Open for write
 key_array = db_name.Keys                                       'Get all Keys
 For Each strKey in key_array                                   'Scan array
   line = escape(strKey) & "," & escape(db_name.Item(strKey))   'Encode Key and Item
   objFile.WriteLine(line)                                      'Write to file  
 Next
 objFile.Close
End Function

'--- List db content
Function list_db(db_name)
 key_array = db_name.Keys            'Get all Keys
 For Each strKey in key_array        'Scan array
  Wscript.Echo strKey & " = " & db_name.Item(strKey) & "<br />"
 Next
End Function
'==============================================================================

'1)--- Create database address_book
Const DB_FILE1   = "address_book.txt"                   'File to use
Set address_book = CreateObject("Scripting.Dictionary") 'Create database

'2)--- Add content to database
'--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"

'3)--Save database
call save_db(address_book,"address_book.txt") 'Save DB to file

'4)--Test 1
clear_db(address_book)                        'Clear database
Wscript.Echo "DB Content 1? <br />"           'First test
list_db(address_book)                         'No content displayed

'5)--Test 2
call load_db(address_book,"address_book.txt") 'Load DB from file
Wscript.Echo "DB Content 2 <br />"            'Second test
list_db(address_book)                         'Content displayed

</script>
</job>

Top

Summary

Previous page introduce the VBScript dictionary and skeleton code for permanent storage using a file. The above fleshed this out to provide working code for a dictionary database with file-base storage. Although this combination is usable it is intended only to introduce a method of saving a dictionary to a file.

It is essential to have a consistent interface which the above is lacking this also applies to obtaining CGI variables. An ideal solution is to use classes these are covered on the next three pages.

Where to next

Next page provides an introduction to VBScript classes.

Top