Adding Methods to Custom Class Objects in VBScript

In my last article I began showing you how to create your own custom class objects in VBScript. We started building the CompressedFolder class, a class that allows you to create and manipulate compressed folders natively. This article will expand on what you learned.

Contributed by
Rating: 4 stars4 stars4 stars4 stars4 stars / 2
March 17, 2009
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

We started by creating a class and adding various properties to it, but having a few properties doesn’t do much for this class.  We also need a way to create the compressed folder and to add to and remove files from it.  For that we need to add some methods.  These are the functions and subroutines that perform the magic when the class is called.

Just like Properties, these methods can be either Public or Private.  Again, the Public methods will be exposed to scripts through the class object.  The structure of methods is identical to that of functions and subroutines used outside of a class, with the simple exception that we’ll be providing either a private or public declaration.

   Public Sub Create(strFile)

       If objFso.FileExists(strFile) Then objFso.DeleteFile(strFile)

       FullName = strFile

       NewCompressedFolder FullName

   End Sub

 

   Private Sub NewCompressedFolder(strPath)

       Const adTypeBinary = 1

       Const adTypeText = 2

       Const adWriteChar = 0

       Const adSaveCreateNotExist = 1

       Const adSaveCreateOverwrite = 2

 

       With CreateObject("ADODB.Stream")

          .Open

          .Type = adTypeText

          .WriteText ChrB(&h50) & ChrB(&h4B) & ChrB(&h5) & ChrB(&h6)

          For i = 1 To 18

              .WriteText ChrB(&h0)

          Next

          .SaveToFile strPath, adSaveCreateNotExist

          .Close

          .Open

          .Type = adTypeBinary

          .LoadFromFile strPath

          .Position = 2

          arrBytes = .Read

          .Position = 0

          .SetEOS

          .Write arrBytes

          .SaveToFile strPath, adSaveCreateOverwrite

          .Close

       End With

   End Sub

Here I’ve added two methods to my class.  The Open() method is a Public method that can be used by the class object in my scripts.  When I pass a parameter to this method, the class will internally call the private NewCompressedFolder() method.

I could have easily housed all of the code in the NewCompressedFolder method within the Open method and eliminated the need for it.  I don’t like to do that.  I prefer to keep all of the internal workings of a class within its own private methods.  This is a pretty common practice for most programmers.

Adding methods to a class

As you can see, methods inside of a class are no different from the functions and subroutines you write in your scripts every day.  Here’s the full list of methods used by the CompressedFolder class.

   Public Sub Open(strFile)

       FullName = strFile

   End Sub

 

   Public Sub Create(strFile)

       If objFso.FileExists(strFile) Then objFso.DeleteFile(strFile)

       FullName = strFile

       NewCompressedFolder FullName

   End Sub

 

   Private Sub NewCompressedFolder(strPath)

       Const adTypeBinary = 1

       Const adTypeText = 2

       Const adWriteChar = 0

       Const adSaveCreateNotExist = 1

       Const adSaveCreateOverwrite = 2

 

       With CreateObject("ADODB.Stream")

          .Open

          .Type = adTypeText

          .WriteText ChrB(&h50) & ChrB(&h4B) & ChrB(&h5) & ChrB(&h6)

          For i = 1 To 18

              .WriteText ChrB(&h0)

          Next

          .SaveToFile strPath, adSaveCreateNotExist

          .Close

          .Open

          .Type = adTypeBinary

          .LoadFromFile strPath

          .Position = 2

          arrBytes = .Read

          .Position = 0

          .SetEOS

          .Write arrBytes

          .SaveToFile strPath, adSaveCreateOverwrite

          .Close

       End With

   End Sub

 

   Public Sub Add(strFile, blnKeepOriginal)

       AddFile FullName, strFile, blnKeepOriginal

   End Sub

 

   Private Function AddFile(strFolder, strFile, blnKeepOriginal)

       Set objFolder = objShell.NameSpace(strFolder)

       intCount = objFolder.Items.Count

       Select Case CBool(blnKeepOriginal)

          Case True

              objFolder.CopyHere strFile, 1548

          Case False

              objFolder.MoveHere strFile, 1548

       End Select

       Do Until objFolder.Items.Count = intCount + 1

          Sleep 200

          If Not ShellBusy Then Exit Do

       Loop

   End Function

 

   Public Sub AddMultiple(varSource, blnKeepOriginal)

       AddFiles FullName, varSource, blnKeepOriginal

   End Sub

 

   Private Function AddFiles(strFolder, varSource, blnKeepOriginal)

       If IsArray(varSource) Then

          For Each strPath In varSource

              AddFile strFolder, strPath, blnKeepOriginal

          Next

       Else

          Set colItems = objShell.NameSpace(strSource).Items

          intCount = .Items.Count

          Select Case CBool(blnKeepOriginal)

              Case True

                 objShell.NameSpace(strFolder).CopyHere colItems, 1548

              Case False

                 objShell.NameSpace(strFolder).MoveHere colItems, 1548

          End Select

          Do Until objShell.NameSpace(strFolder).Items.Count = intCount + colItems.Count

              Sleep 200

              If Not ShellBusy Then Exit Do

          Loop

       End If

   End Function

 

   Public Sub Extract(strFolder)

       ExtractAll FullName, strFolder

   End Sub

 

   Private Function ExtractAll(strZipFile, strFolder)

       If Not objFso.FolderExists(strFolder) Then objFso.CreateFolder(strFolder)

       intCount = objShell.NameSpace(strFolder).Items.Count

       Set colItems = objShell.NameSpace(strZipFile).Items

       objShell.NameSpace(strFolder).CopyHere colItems, 1548

       Do Until objShell.NameSpace(strFolder).Items.Count = intCount + colItems.Count

          Sleep 200

          If Not ShellBusy Then Exit Do

       Loop

   End Function

 

   Private Function GetItemCount(strZipFile)

       GetItemCount = objShell.NameSpace(strZipFile).Items.Count

   End Function

 

   Private Function ShellBusy()

       intStartSize = objFso.GetFile(FullName).Size

       Sleep 500

       ShellBusy = objFso.GetFile(FullName).Size > intStartSize

   End Function

 

   Private Sub Sleep(intDuration)

       'You must provide an applicable sleep routine for use in ASP.

       WScript.Sleep intDuration

   End Sub

Take the time to see which ones are Private and which are Public.  Do you see how they relate to each other?  I’m using the exposed (Public) methods to call the internal (Private) methods.  For a further explanation of the inner workings of these functions, stayed tuned for my Understanding the CompressedFolder class series.

Completing the class

All of the basic pieces for the CompressedFolder class are now in place.  We’ve provided all of the properties and methods along with their required code.  In VBScript there is no way to create your own custom events for your classes.  However, there are two intrinsic events that you can use, and I want to demonstrate how to handle those.

VBScript classes have Initialize and Terminate events.  The first fires when the class is instantiated, and the latter fires when that object is released.  These are handled in a typical VBS fashion using the object-underscore naming convention.  In this case, we can simply use the Class keyword for the event handle.

   Private Sub Class_Initialize

       Set objShell = CreateObject("Shell.Application")

       Set objFso   = CreateObject("Scripting.FileSystemObject")

   End Sub

 

   Private Sub Class_Terminate

       Set objShell = Nothing

       Set objFso   = Nothing

   End Sub

The Class_Initialize subroutine will be executed when the Initialize event occurs.  This happens when the programmer creates a reference to this class and instantiates its object.  This provides a nice opportunity for us to connect to any objects that will be used globally in our class.  Since we want these to be made available globally, we should also include the appropriate private statements at the beginning of the class to make the object variables global.

Class CompressedFolder

   Private m_fileName

   Private m_ignoreConflicts

   Private objShell

   Private objFso

Here I’ve added the objShell and objFso declarations to the top of my code class.  I’ve also added m_ignoreConflicts, which is another global variable used throughout some of my methods.

Finally, the Class_Terminate routine is executed when the class object is released.  This provides a good place to release any global objects.

Okay, some of you are scratching your heads wondering why I would bother releasing those objects, right?  It’s true that any objects will be released whenever the class terminates anyway.  I more or less just wanted to demonstrate how the Terminate event could be used.  This particular class doesn’t actually have a solid use for the Terminate event.

Implementing our new class

Now that you’ve built your class, you can begin implementing it in your scripts.  You’ll need to copy and paste the class into your script to begin with.  Just like a function or subroutine, it doesn’t matter where you place it as long as it’s in the global scope.  Then you’ll need to connect to it like this:

Set objZipFolder = New CompressedFolder

Remember that classes return objects, so you’ll need to use a Set statement to assign the return value.  The New keyword followed by a class name tells VBScript that we’re instantiating a class.  You can instantiate as many instances of a class as necessary.

If you’re using a script editor with an IntelliSense feature, it should have no problem displaying the public properties and methods for your object.  Here’s what it looks like in Sapien’s PrimalScript 2007.

If you plan on using this class in a development environment, I highly suggest that you take the time to download the latest version here.  I do update my scripts from time to time to add new features or fix bugs.  The full documentation for this class is also available here.

I hope you’ve had fun learning how to create your own VBScript classes.  Learning to use classes effectively can greatly reduce the amount of work you do, while providing a much more professional look to your code.  Until next time, keep coding!

blog comments powered by Disqus
CODE EXAMPLES ARTICLES

- Bipartite Graphs
- Connectivity in Graphs
- The Ford-Fulkerson Algorithm
- Critical Paths
- The Bellman-Ford and Roy-Floyd Algorithms
- Shortest Path Algorithms in Graphs
- Minimum Spanning Tree
- Articulation Edges and Vertexes
- Circles and Connectivity in Graphs
- Depth-First Search in Graphs
- Breadth-First Search in Graphs
- The Prufer Code and the Floyd-Warshall Algor...
- An Insight into Graphs
- Coding a Custom Object with WSC
- Creating a Custom Object with WSC

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 3 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials