CGI: VBScript File DB Class Summary

Revision as of 23:25, 7 November 2011 by Ric (talk | contribs) (Created page with "{{Nav CGI}} '''VBScript File DB Class Summary''' Previous page covered the file DB Class. This page summaries the class interface and provides a code listing. An example of us...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

VBScript File DB Class Summary

Previous page covered the file DB Class.

This page summaries the class interface and provides a code listing.

An example of using the file DB Class is also given.


File DB Class properties and methods

The file DB class uses a dictionary to provide fast data (key-item pairs) retrieval and storage. The class transparently stores all dictionary transactions to a file. This is automatically loaded when a class is instantiated and rebuilds the dictionary database. The following are the properties and method supported by this class:

Properties

Syntax Description

my_db.file_name = "xxx.txt"
x = my_db.file_name

The file_name property sets the file name to be used for the database file. A full path can be specified for example c:\some_folder\xxx.txt or just the file name xxx.txt in that case the file will be saved to the folder where the script resides. Property is readable.

my_db.buffer_size = "3"
x = my_db.buffer_size

The buffer_size property sets the record size default is one. Record is the number of key-item pairs to save before they are actually written or deleted using methods Add and Remove methods. Property is readable.

x = my_db.Count

The Count property returns number of key-item pairs contained in the main database dictionary.

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

Returns Item value using key. Data is extracted directly from the main database dictionary. Or sets Item value using key. A new key-item pair is added if the key does not exist or updates an exiting item if the key exists. The transaction is appended to the database file with a maker i both key and item is encoded. Note: A buffer is not used the property always performs a single transaction.

my_db.Key(OldKeyValue) = NewKeyValue

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

Methods

Syntax Description
my_db.list The list method lists all data (index-item pairs) contained in the main database dictionary. It is included only for testing.

my_db.clean

The clean method writes the main database dictionary to a time stamped file.

Format as shown: 1315777171.txt It provides a clean database file containing only added items. Use this file when the main file becomes large and cluttered with old transactions.

my_db.Add keyvalue, itemvalue

The Add method is used to add a new key/item pair to the add buffer. If the key already exists it is first deleted and the new pair added. Buffer counter is incremented.

The buffer counter is tested against the record size (buffer size) if equal buffer content is written to the database dictionary and database file. Database entries are tagged with an a indicating an addition. On completion the counter is reset to zero.

my_db.Exists(keyvalue)

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

array_name = my_db.Items

The Items method is used to retreive all of the items in the database dictionary object and store them in an array.

arrayname = my_db.Keys

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

my_db. Remove(keyvalue)

The Remove method is used to add a new key/item pair to the delete buffer. If the key already exists it is first deleted and the new pair added. Buffer counter is incremented.

The buffer counter is tested against the record size (buffer size) if equal buffer content is removed from the database dictionary and entries added to the database file. Database entries are tagged with a d indicating a deletion. On completion the counter is reset to zero.

Top

File DB Class code

A complete code listing of the File DB class is shown on the right.


Its operation has been fully covered on the previous page.


Append the code to file common_functions.vbs for later use.

'=== File DB class ============================================================

Class file_db_class
 Private main_db,add_buff,del_buff                    'Dictionaries
 Private db_file_name,buff_size_count,user_buff_size  'variables  

 '--Constructor
 Private Sub Class_Initialize()                       'Set inital
   db_file_name    = "" 'No default
   buff_size_count = 0  'Buffer size counter
   user_buff_size  = 1  'Default record size

   Set main_db  = CreateObject("Scripting.Dictionary")'Main database
   Set add_buff = CreateObject("Scripting.Dictionary")'Add buffer
   Set del_buff = CreateObject("Scripting.Dictionary")'Delete buffer
 End Sub

 '--Terminate
 Private Sub Class_Terminate 'Standard method when class destroyed
   On Error Resume Next      'File may already be closed.       
   dbFile.Close              'This ensures file really is closed.
 End Sub

 '--Load database from file
 Private Sub load_main_db()
  Dim fso,dbFile,line,split_line
  Dim decoded_key,decoded_item,decoded_keyn
  Set fso=CreateObject("Scripting.FileSystemObject") 'File obj
  Set dbFile=fso.OpenTextFile(db_file_name,1,true)   'Open for read

  While Not dbFile.AtEndOfStream              'Read file
    line = dbFile.ReadLine()                  'Read line
    If line="" Then
      dbFile.Close                            'Close file
      Exit Sub                                'Nothing else to do
    End If

    split_line = Split(line,",")              'Split at seperator
    Select Case split_line(0)                 'Check marker
    Case "a"                                  'Marker add to db
     decoded_key  = Unescape(split_line(1))   'Decode key
     decoded_item = Unescape(split_line(2))   'Decode Item
     main_db.Add decoded_key,decoded_item     'Add entry to db

    Case "d"                                  'Marker delete from db
     decoded_key  = Unescape(split_line(1))   'Decode key
     main_db.Remove decoded_key               'Delete entry

    Case "i"                                  'Marker edit item
     decoded_key  = Unescape(split_line(1))   'Decode key
     decoded_item = Unescape(split_line(2))   'Decode Item
     main_db.Item(decoded_key) = decoded_item 'Edit key item

    Case "k"                                  'Marker edit key
     decoded_key  = Unescape(split_line(1))   'Decode key
     decoded_keyn = Unescape(split_line(2))   'Decode new key
     main_db.Key(decoded_key) = decoded_keyn  'Change key
 
    End Select 
  Wend 'End read file
  dbFile.Close                                'Close file
 End Sub
 '--End Load database from file

 '--Add buffer to main DB and update database file
 Sub add_buff_sub()                           'Add content to main DB
   Dim key_array,strKey,encode1,encode2
   Dim fso,dbFile

   Set fso=CreateObject("Scripting.FileSystemObject") 'File obj
   Set dbFile=fso.OpenTextFile(db_file_name,8,false)  'Open for append

   key_array = add_buff.Keys                        'Get all Keys
   For Each strKey in key_array                     'Scan array
    If main_db.Exists(strKey) Then                  'Check key exists
      main_db.Remove strKey                         'yes delete entry
      encode1 =  escape(strKey)                     'encode key  
      dbFile.WriteLine "d," & encode1               'Save to file
    End If
    main_db.Add strKey, add_buff.Item(strKey)       'Add data unit to main db
    encode1 =  escape(strKey)                       'encode key  
    encode2 =  escape(add_buff.Item(strKey))        'encode Item
    dbFile.WriteLine "a," & encode1 & "," & encode2 'Save to file
   Next                                             'Get next line

   dbFile.Close                                     'Close file
   add_buff.RemoveAll                               'Clear buffer
 End Sub
 '--End Add buffer to main DB

 '--Delete buffer remove from main DB and update database file
 Sub del_buff_sub()                           'Delete content from main DB
   Dim key_array,strKey,encode1
   Dim fso,dbFile

   Set fso=CreateObject("Scripting.FileSystemObject") 'File obj
   Set dbFile=fso.OpenTextFile(db_file_name,8,false)  'Open for append

   key_array = del_buff.Keys                        'Get all Keys
   For Each strKey in key_array                     'Scan array
    If main_db.Exists(strKey) Then                  'Check key exists
      main_db.Remove strKey                         'yes delete entry
      encode1 =  escape(strKey)                     'encode key  
      dbFile.WriteLine "d," & encode1               'Save to file
    End If
   Next                                             'Get next line

   dbFile.Close                                     'Close file
   del_buff.RemoveAll                               'Clear buffer
 End Sub

 '===Properties specific to file DB

 '--Set database file name
 Public Property Let file_name(name)
   db_file_name = name                'Set file name variable
   load_main_db                       'Load file into database 
 End Property

 '--Read database file name
 Public Property Get file_name()
   file_name = db_file_name           'Return file name
 End Property

 '--Set buffer size
 Public Property Let buffer_size(size)
   user_buff_size = size
 End Property

 '--Read buffer size
 Public Property Get buffer_size
   buffer_size = user_buff_size
 End Property

 '===Methods specific to file DB

 '--List all data in main database used for testing
 Public Sub list()
   Dim key_array, strKey
   key_array = main_db.Keys                           'Get all Keys
   For Each strKey in key_array                       'Scan array
     Wscript.Echo strKey & " = " & main_db.Item(strKey) & "<br />"
   Next
 End Sub

 '--Save a clean copy of the main database
 Public Function clean()
  Dim key_array,strKey,encode1,encode2
  Dim fso,dbFile,clean_name  

   'Create file with time stamp
   clean_name = DateDiff("s", "01/01/1970 00:00:00", Now()) & ".txt"

   Set fso=CreateObject("Scripting.FileSystemObject") 'File obj
   Set dbFile=fso.OpenTextFile(clean_name,2,true)   'Open for append

   key_array = main_db.Keys                         'Get all Keys
   For Each strKey in key_array                     'Scan array
    encode1 =  escape(strKey)                       'encode key  
    encode2 =  escape(main_db.Item(strKey))         'encode Item
    dbFile.WriteLine "a," & encode1 & "," & encode2 'Save to file
   Next                                             'Get next line
   dbFile.Close                                     'Close file
  clean = True
 End Function

 '=== Replicated dictionary properties ====

 '--Read number of key/item pairs
 Public Property Get Count() 
   Count = main_db.Count         'Get number of key/item pairs
 End Property

 '--Read Item value using key 
 Public Property Get Item(key) 
   Item = main_db.Item(key)      'Get Item value
 End Property

 '--Set Item value using key 
 Public Property Let Item(Key,Item_value) 
   Dim encode1,encode2
   Dim fso,dbFile

   main_db.Item(key) = Item_value                     'Set Item value
   Set fso=CreateObject("Scripting.FileSystemObject") 'File obj
   Set dbFile=fso.OpenTextFile(db_file_name,8,false)  'Open for append

   encode1 =  escape(key)                             'encode key  
   encode2 =  escape(Item_value)                      'encode Item
   dbFile.WriteLine "i," & encode1 & "," & encode2    'Save to file
   dbFile.Close                                       'Close file
 End Property

 '--Set Replace key with new key  
 Public Property Let Key(oldkey,newkey) 
   Dim encode1,encode2
   Dim fso,dbFile

   main_db.Key(oldkey) = newkey                       'Set new key
   Set fso=CreateObject("Scripting.FileSystemObject") 'File obj
   Set dbFile=fso.OpenTextFile(db_file_name,8,false)  'Open for append

   encode1 =  escape(oldkey)                          'encode key  
   encode2 =  escape(newkey)                          'encode new key
   dbFile.WriteLine "k," & encode1 & "," & encode2    'Save to file

   dbFile.Close                                       'Close file
 End Property

 '===Replicated dictionary methods

 '--Add Key and Item to main db
 Public Sub Add(key,item)
    If add_buff.Exists(key) Then            'Check key exists in buffer
      add_buff.Remove key                   'yes delete entry from buffer
    End If
   add_buff.Add key,item                    'Add new item to buffer

   buff_size_count = buff_size_count + 1    'Increment buff counter

   If buff_size_count = user_buff_size Then 'Is max record value reached
     add_buff_sub                           'Add data to DB and DB file
     buff_size_count = 0                    'Reset counter
   End If
 End Sub

 '--Does Key Exist
 Public Function Exists(key)
    If main_db.Exists(key) Then
      Exists = True
    Else
      Exists = False
    End If
 End Function

 '--Return array of Items
 Public Function Items()
    Items = main_db.Items
 End Function

 '--Return array of Keys
 Public Function Keys()
    Keys = main_db.Keys
 End Function

 '--Remove a key value pair
 Public Sub Remove(key)
   If del_buff.Exists(key) Then            'Check key exists in delete buffer
     dell_buff.Remove key                  'yes delete entry from buffer
   End If
   del_buff.Add key,""                     'Add new item to buffer
   buff_size_count = buff_size_count + 1   'Increment buff counter

  If buff_size_count = user_buff_size Then 'Is max record value reached
    del_buff_sub                           'Remove data from DB and add to DB file
    buff_size_count = 0                    'Reset counter
  End If
 End Sub

End Class
'======================================================== End File DB class ===

Top

Test script 18 - File DB Class use

This example shows how to use the File DB class.

The script is self-explanatory however there are some points worthy of note.

  • The File DB class is contained in file common_functions.vbs
  • Always check an entry exists before using it.

Run script

  • Create a new file file_db_1.wsf with content as shown on right.
  • Save to test folder \www\vbs_test
  • Start Apache if not already running
  • Enter: http://localhost:8081/vbs_test/file_db_1.wsf into browser.

Result shown below:

entry1 = some value 1        --3)
entry2 = some value 2
entry3 = some value 3
entry4 = some value 4

Entry 3 = some value 3       --4)
Deleting entry 3             --5)
Key entry3 does NOT exits    --6)
'!c:/windows/system32/cscript //nologo

<job>
'-- Include any external files
<script language="VBScript" src="common_functions.vbs"/>

' Main script ---
<script language="VBScript">
Option Explicit ' Force explicit variable declaration.
Wscript.Echo "Content-type: text/html"&vbLF&vbLF
Wscript.Echo "<title>Test 18</title>"

Dim test_db

'1)--- Create test database
set test_db       = New file_db_class  'Create new object
test_db.file_name = "test_db.txt"      'Set db file name

'2)--- Add content to database

test_db.Add "entry1",     "some value 1"        
test_db.Add "entry2",     "some value 2" 
test_db.Add "entry3",     "some value 3" 
test_db.Add "entry4",     "some value 4" 

'3)--Test 1 List database content
test_db.list              'Display all database content

'4)--Display an entry for example entry3
Wscript.Echo "<br />Entry 3 = " & test_db.Item("entry3")

'5)--Delete entry for example entry3
test_db. Remove("entry3")
Wscript.Echo "<br />Deleting entry 3<br />"

'6)--Display an entry for example entry3
'    First check the entry exists

If test_db.Exists("entry") Then
  WScript.Echo "Key entry3 exits <br />" 
Else
  WScript.Echo "Key entry3 does NOT exits <br />" 
End If

</script>
</job>

Top

Summary

The above provides a quick properties and methods reference for the File DB class.
A full code listing for the class is provided you should save this to the common functions file.
A small test script demonstrates some of the class’s properties and methods.

Where to next

All scripts in this tutorial currently use a file extension .vbs or .wsf these expose the underlying technology used which is probably not desirable. Apache using URL rewriting can rewrite the extension to something else, for example htm this is covered on the next page.

Top