Classes In VBScript

Author Message
Wakawaka

  • Total Posts : 456
  • Scores: 23
  • Reward points : 0
  • Joined: 8/27/2009
  • Status: offline
Classes In VBScript Friday, March 04, 2011 4:14 PM (permalink)
0
Classes are available to VBScript 5.0 and up (installed with IE5).

Classes allow a user to group similar methods together as well as properties that describe the class.  They allow us to increase the modularity of our code as well as let us write less lines of code in script that use it.

For example, imagine you have a script that does work and then logs the results of your work.  You might have methods that allow you to write a header, a line of data, footer, and then close the file.  To actually write to the file, you would need to use the FileSystemObject, OpenTextFile, and the Close methods.  All of these methods and object are associated with each other and need each other to work together.  Instead of re-creating the code each time, you can create a class that encompasses the basic methods for file manipulation and the associated objects.

To declare a class, you will need to use the Class statement.

  
 Class LogKeeper  
 End Class  
 


Now that you have your class declared, we will add class-wide variables that are meaningful to our class.

  
 Class LogKeeper  
 Private m_OpenFile 'Stores an TextSteamObject we will be using to write the data to  
 Private m_LogPath 'Stores the path we will write the log to  
 Private m_IOMode 'Stores how the OpenTextFile method will treat the file stream  
 End Class  
 


You might have noticed the “Private” in front of the variables.  This is an access modifier keyword.  It allows you to specify the scope of the method or variable.  In this case, we will be working with the Public and Private modifiers.  Private means the method/variable is only available to the objects within the class and the Public modifier means the method/variable is available to the objects outside of the class.

Sometimes  you will have a class-wide  variable that you need to access, but you don’t want to always declare it or pass it to the methods.  In this case, you would make it a property of a class.  In this example, we will make a property for the m_LogPath variable so we can set and get the value of the variable.

  
 Class LogKeeper  
 Private m_OpenFile  
 Private m_LogPath  
 Private m_IOMode  
 
 'The "Get" property allows an external object to get the value of the m_LogPath variable  
 Public Property Get LogPath  
 LogPath = m_LogPath  
 End Property  
 
 'The "Let" property allows an external object to set the value of the m_LogPath variable  
 Public Property Let LogPath(value)  
 m_LogPath = value  
 End Property  
 
 Public Property Get IOMode  
 IOMode = m_IOMode  
 End Property  
 
 'We check to see if the value provided is a acceptable value  
 'If it isn't we default to IOMode of appending to the text file  
 Public Property Let IOMode(value)  
 If value <> 2 And value <> 8 Then  
 m_IOMode = 8  
 Else  
 m_IOMode = value  
 End If  
 End Property  
 End Class  
 


By adding a property to the class, it allows us to retrieve and set the value of the private variable.  This lets us set the value once and allow the class to make the necessary calls to it instead of passing it multiple times or having it clutter the code of the main work script.
<message edited by Wakawaka on Friday, March 04, 2011 4:47 PM>
 
#1
    Wakawaka

    • Total Posts : 456
    • Scores: 23
    • Reward points : 0
    • Joined: 8/27/2009
    • Status: offline
    Re:Classes In VBScript Friday, March 04, 2011 4:16 PM (permalink)
    0
    Next we will add an Initializer method. This method is automatically executed when you instantiate the class.

       
     Class LogKeeper   
     Private m_OpenFile   
     Private m_LogPath   
     
     Private m_IOMode   
     
     Public Property Get LogPath   
     LogPath = m_LogPath   
     End Property   
     
     Public Property Let LogPath(value)   
     m_LogPath = value   
     End Property   
     
     Public Property Get IOMode   
     IOMode = m_IOMode   
     End Property   
     
     Public Property Let IOMode(value)   
     If value <> 2 And value <> 8 Then   
     m_IOMode = 8   
     Else   
     m_IOMode = value   
     End If   
     End Property   
     
     Private Sub Class_Initialize   
     'Set the value of the m_LogPath variable so if one isn’t defined, you won’t have issues   
     m_LogPath = "LogKeeper.log"   
     m_IOMode = 8   
     End Sub   
     End Class   
     

    <message edited by Wakawaka on Friday, March 04, 2011 5:02 PM>
     
    #2
      Wakawaka

      • Total Posts : 456
      • Scores: 23
      • Reward points : 0
      • Joined: 8/27/2009
      • Status: offline
      Re:Classes In VBScript Friday, March 04, 2011 4:23 PM (permalink)
      0
      Finally, we need to add the Public methods that the object will use to do work when the class is instantiated.

        
       Class LogKeeper  
       Private m_OpenFile  
       Private m_LogPath  
       Private m_IOMode  
       
       Public Property Get LogPath  
       LogPath = m_LogPath  
       End Property  
       
       Public Property Let LogPath(value)  
       m_LogPath = value  
       End Property  
       
       Public Property Get IOMode  
       IOMode = m_IOMode  
       End Property  
       
       Public Property Let IOMode(value)  
       If value <> 2 And value <> 8 Then  
       m_IOMode = 8  
       Else  
       m_IOMode = value  
       End If  
       End Property  
       
       Private Sub Class_Initialize  
       m_LogPath = "LogKeeper.log"  
       m_IOMode = 8  
       End Sub  
       
       Public Function CreateLog()  
       On Error Resume Next  
       
       Dim isLogCreated : isLogCreated = False  
       
       'We use this check to see if the m_OpenFile variable has been initialized  
       'If it hasn't we don't need to do anything, if it is, that means we created  
       'a TextStreamObject and assigned it to m_OpenFile so we need to close the current  
       'file before opening a new one.  
       If Not(IsEmpty(m_OpenFile)) Then  
       m_OpenFile.Close()  
       End If  
       
       Set m_OpenFile = CreateObject("Scripting.FileSystemObject").OpenTextFile(m_LogPath, m_IOMode, True)  
       
       If Err.Number = 0 Then  
       isLogCreated = True  
       WriteHeader  
       End If  
       
       Err.Clear  
       CreateLog = isLogCreated  
       End Function  
       
       Public Function Write(data, newLine)  
       If newLine Then  
       m_OpenFile.WriteLine data  
       Else  
       m_openFile.Write data  
       End If  
       End Function  
       
       Public Sub CloseLog()  
       WriteFooter  
       Write "", True  
       m_OpenFile.Close()  
       End Sub  
       
       Private Sub WriteHeader()  
       Write "Log created: " & Now, True  
       Write String(20, "-"), True  
       End Sub  
       
       Private Sub WriteFooter()  
       Write String(20, "-"), True  
       Write "Log closed: " & Now, True  
       End Sub  
       End Class  
       

      <message edited by Wakawaka on Friday, March 04, 2011 5:02 PM>
       
      #3
        Wakawaka

        • Total Posts : 456
        • Scores: 23
        • Reward points : 0
        • Joined: 8/27/2009
        • Status: offline
        Re:Classes In VBScript Friday, March 04, 2011 4:27 PM (permalink)
        0
        To create an instance of the class, you would use the New keyword.

           
         Dim myLogger : Set myLogger = New LogKeeper   
         
         Msgbox "Current log path: " & myLogger.LogPath & vbCrLf & _   
         "Current IO Mode: " & myLogger.IOMode, vbOkOnly, "Logger Variables"   
         
         myLogger.LogPath = "TestLog.log"   
         myLogger.IOMode = 2   
         
         Msgbox "Current log path: " & myLogger.LogPath & vbCrLf & _   
         "Current IO Mode: " & myLogger.IOMode, vbOkOnly, "Logger Variables"   
         
         'If the log was successfully created, write to it   
         'Otherwise display an error   
         If myLogger.CreateLog() Then   
         For i=0 To 100 Step 2   
         myLogger.Write i, True   
         Next   
         Else   
         Msgbox "There was an error while creating the log file." & vbCrLf &_   
         "Check your log settings and try again.", vbOkOnly + vbCritical, "Log Error"   
         WScript.Quit(6400)   
         End If   
         
         myLogger.CloseLog()   
         


        Now that we have the class created, we can create a new instance whenever we want and use it without having to recreate the code and variables needed over and over.

        The LogKeeper class is just a simple sample of the use of a class.  You could make classes for practically anything, a class to get the hardware or software of a system, a class with methods to connected maintain a database connection and queries against it, or a class to manipulate a XML file.
        <message edited by Wakawaka on Friday, March 04, 2011 5:08 PM>
         
        #4
          TNO

          • Total Posts : 2094
          • Scores: 36
          • Reward points : 0
          • Joined: 12/18/2004
          • Location: Earth
          • Status: offline
          Re:Classes In VBScript Friday, March 04, 2011 6:10 PM (permalink)
          To iterate is human, to recurse divine. -- L. Peter Deutsch
           
          #5

            Online Bookmarks Sharing: Share/Bookmark

            Jump to:

            Current active users

            There are 0 members and 1 guests.

            Icon Legend and Permission

            • New Messages
            • No New Messages
            • Hot Topic w/ New Messages
            • Hot Topic w/o New Messages
            • Locked w/ New Messages
            • Locked w/o New Messages
            • Read Message
            • Post New Thread
            • Reply to message
            • Post New Poll
            • Submit Vote
            • Post reward post
            • Delete my own posts
            • Delete my own threads
            • Rate post

            2000-2012 ASPPlayground.NET Forum Version 3.9