How to check if a Script defines a particular Class or Property using MSScriptControl?

72 views Asked by At

I'm currently idiot-proofing a legacy VB6 program that uses an MSScriptControl. It takes a file name as input, then gets some strings defined in a Property of a Class defined in said file.

Here's the current code:

Dim oScript As New ScriptControl
With oScript
    .Language = "VBSCRIPT"
    .Reset
    .UseSafeSubset = False
    .Timeout = -1

    sScriptCode = "ScriptLoadedFromSomeFileDefinedSomewhereElse" 'This variable contains the entire length of the script file

    'This Len() should guard against Test:FileIsBlank
    If Len(sScriptCode) = 0 Then GoTo DoTheRest

    'This InStr() should guard against Test:FileDoesNotContainClassDef
    If InStr(1, sScriptCode, "Class myClassName", vbTextCompare) = 0 Then GoTo DoTheRest

    .AddCode sScriptCode
    .AddCode "Dim myClassName"
    .AddCode "Set myClassObject = New myClassName"

    'These InStr()s should guard against Test:FileDoesNotContainExpectedSubs
    If InStr(1, sScriptCode, "Property Get PropStringA", vbTextCompare) = 0 Then GoTo DoTheRest
    sPropStringA = .Eval("myClassObject.PropStringA")

    If InStr(1, sScriptCode, "Property Get PropStringB", vbTextCompare) = 0 Then GoTo DoTheRest
    sPropStringB = .Eval("myClassObject.PropStringB")

    'This should guard against everything else. That is, Test:FileContainsInvalidVBCode
    If Err Then GoTo DoTheRest
End With

DoTheRest:
'Rest of Code

Here's the pertinent part of the input script file:

Class myClassName

Public Property Get PropStringA()
  PropStringA = _
    "StringA" 
End Property

Public Property Get PropStringB()
  PropStringB = _
    "StringB,StringC,StringD,StringE"
End Property

The above is loaded into the sScriptCode variable via FileSystemObject.OpenTextFile().

The entire purpose of using ScriptControl is to get the strings defined in the file's Class Properties PropStringA and PropStringB, by instantiating the Class and using ScriptControl.Eval.

Here's my question: this (hack) works, but is there a better, more refined way for me to check that the input script actually contains the things I need, specifically a Class definition and Public Get Property(ies)? What about if the file is not blank but doesn't actually contain VB code, say, a text file?

Bonus: Should I have asked this over on CodeReview instead?

0

There are 0 answers