<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
	<title type="html"><![CDATA[Серый форум &mdash; VBScript: имитация Include для целей повторного использования кода]]></title>
	<link rel="self" href="https://forum.script-coding.com/extern.php?action=feed&amp;tid=1060&amp;type=atom" />
	<updated>2008-01-20T11:32:20Z</updated>
	<generator>PunBB</generator>
	<id>https://forum.script-coding.com/viewtopic.php?id=1060</id>
		<entry>
			<title type="html"><![CDATA[Re: VBScript: имитация Include для целей повторного использования кода]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=8124#p8124" />
			<content type="html"><![CDATA[<p>Сымитировать Include также поможет формат WSF:<br /></p><div class="codebox"><pre><code>&lt;job&gt;
&lt;script language=&#039;VBScript&#039;&gt;
  &#039; некоторый код (начало)
&lt;/script&gt;
&lt;script language=&#039;VBScript&#039; src=&#039;external_file.inc&#039;/&gt;
&lt;script language=&#039;VBScript&#039;&gt;
  &#039; некоторый код (конец)
&lt;/script&gt;
&lt;/job&gt;</code></pre></div><p>И наконец, самым &quot;правильным&quot; методом повторного использования кода является создание <a href="http://forum.script-coding.com/viewtopic.php?id=1037">WSC-серверов</a>.</p>]]></content>
			<author>
				<name><![CDATA[The gray Cardinal]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=2</uri>
			</author>
			<updated>2008-01-20T11:32:20Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=8124#p8124</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[Re: VBScript: имитация Include для целей повторного использования кода]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=8123#p8123" />
			<content type="html"><![CDATA[<p>Основное ограничение при использовании оператора <strong>ExecuteGlobal</strong>, на котором, собственно, и покоится вся подобная функциональность - возникновение ошибки при повторном описании классов, констант, переменных, процедур, функций. Ниже приводится пример с классом для включения &quot;библиотек&quot;, который имеет специальное свойство SimpleReEntrant. Если перед включением библиотеки установить это свойство в True, дублирующиеся определения не будут добавлены в глобальный контекст скрипта.<br />Библиотека C:\Мои проекты\My Scripts\MyLib1.vbh:<br /></p><div class="codebox"><pre><code>Option Explicit

&#039; Несколько констант
Const ForReading   = 1
Const ForWriting   = 2
Const ForAppending = 8

&#039; Простая функция
Function Add(intValue1, intValue2)
    Add = intValue1 + intValue2
End Function</code></pre></div><p>Библиотека C:\Program Files\My Scripts\Library\MyLib2.vbh:<br /></p><div class="codebox"><pre><code>Option Explicit

&#039; Опишем простой класс, умеющий складывать и вычитать
Class MyCalc
    Private Sub Class_Initialize
    End Sub
    
    Private Sub Class_Terminate
    End Sub
    
    Public Function Multiply(intArg1, intArg2)
        Multiply = intArg1 + intArg2
    End Function
    
    Public Function Divide(intArg1, intArg2)
        Divide = intArg1 - intArg2
    End Function
End Class</code></pre></div><p>Пример включения и использования библиотек:<br /></p><div class="codebox"><pre><code>Option Explicit

Const ForReading = 100
Const ForWriting = 200

Dim objIncludeLibrary
Set objIncludeLibrary = New IncludeLibrary

With objIncludeLibrary
    .PathToLibraries = &quot;%ProgramFiles%\My Scripts\Library&quot;
    .SimpleReEntrant = True
    
    .LoadLibrary &quot;C:\Мои проекты\My Scripts\MyLib1.vbh&quot;
    .LoadLibrary &quot;MyLib2.vbh&quot;
End With

Set objIncludeLibrary = Nothing

WScript.Echo &quot;ForReading = &quot; &amp; ForReading
WScript.Echo &quot;ForWriting = &quot; &amp; ForWriting
WScript.Echo &quot;Add(2, 2) = &quot; &amp; Add(2, 2)

Dim objMyCalc
Set objMyCalc = New MyCalc

WScript.Echo &quot;objMyCalc.Multiply(3, 2) = &quot; &amp; objMyCalc.Multiply(3, 2)
WScript.Echo &quot;objMyCalc.Divide(3, 2)   = &quot; &amp; objMyCalc.Divide(3, 2)

Set objMyCalc = Nothing

WScript.Quit 0
&#039; ================================================================================

&#039; ================================================================================
Class IncludeLibrary
    Private objFSO
    Private objWshShell
    
    Private strRegKey
    Private blnSimpleReEntrant
    &#039; ---------------------------------------------------------------------------
    Private Sub Class_Initialize
        Set objFSO = WScript.CreateObject(&quot;Scripting.FileSystemObject&quot;)
        Set objWshShell = WScript.CreateObject(&quot;WScript.Shell&quot;)
        
        strRegKey = &quot;HKEY_CURRENT_USER\Software\VBScript\PathToLibraries&quot;
        blnSimpleReEntrant = False
    End Sub
    &#039; ---------------------------------------------------------------------------
    Private Sub Class_Terminate
        Set objWshShell = Nothing
        Set objFSO = Nothing
    End Sub
    &#039; ---------------------------------------------------------------------------
    Public Default Sub LoadLibrary(ByVal strFileName)
        Dim objTS
        Dim strValue
        Dim strErrDescription
        
        If Not objFSO.FileExists(strFileName) Then
            If Not objFSO.FileExists(objFSO.BuildPath( _
                objWshShell.ExpandEnvironmentStrings(PathToLibraries()), strFileName)) Then
                
                Err.Raise 53, &quot;IncludeLibrary.LoadLibrary&quot;, _
                    &quot;Library [&quot; &amp; strFileName &amp; &quot;] not found&quot;
                Exit Sub
            Else
                strFileName = objFSO.BuildPath(objWshShell.ExpandEnvironmentStrings(PathToLibraries()), strFileName)
            End If
        End If
        
        On Error Resume Next
        
        Set objTS = objFSO.OpenTextFile(strFileName, 1, False, 0)
        
        If Err.Number &lt;&gt; 0 Then
            strErrDescription = Err.Description
            Err.Clear
            On Error Goto 0
            Err.Raise 1200, &quot;IncludeLibrary.LoadLibrary&quot;, _
                &quot;Can&#039;t open library [&quot; &amp; strFileName &amp; &quot;]:&quot; &amp; strErrDescription
            Exit Sub
        End If
        
        strValue = objTS.ReadAll
        
        If Err.Number &lt;&gt; 0 Then
            strErrDescription = Err.Description
            Err.Clear
            
            objTS.Close
            Set objTS = Nothing
            
            On Error Goto 0
            Err.Raise 1201, &quot;IncludeLibrary.LoadLibrary&quot;, _
                &quot;Can&#039;t read from library [&quot; &amp; strFileName &amp; &quot;]:&quot; &amp; strErrDescription
            Exit Sub
        End If
        
        strValue = Trim(strValue)
        
        objTS.Close
        Set objTS = Nothing
        
        If Len(strValue) = 0 Then
            On Error Goto 0
            Err.Raise 1202, &quot;IncludeLibrary.LoadLibrary&quot;, _
                &quot;Library [&quot; &amp; strFileName &amp; &quot;] is empty&quot;
            Exit Sub
        End If
        
        ExecuteGlobal strValue
        
        If Err.Number &lt;&gt; 0 Then
            If Err.Number = 1041 And SimpleReEntrant Then
                Err.Clear
                &#039; Nothing to do
            Else
                strErrDescription = Err.Description
                Err.Clear
                On Error Goto 0
                Err.Raise 1002, &quot;IncludeLibrary.LoadLibrary&quot;, _
                    &quot;Error found in library [&quot; &amp; strFileName &amp; &quot;] while loading:&quot; &amp; strErrDescription
                Exit Sub
            End If
        End If
        
        On Error Goto 0
    End Sub
    &#039; ---------------------------------------------------------------------------
    Public Property Let PathToLibraries(strValue)
        Dim strErrDescription
        
        On Error Resume Next
        
        objWshShell.RegWrite strRegKey, strValue, &quot;REG_EXPAND_SZ&quot;
        
        If Err.Number &lt;&gt; 0 Then
            strErrDescription = Err.Description
            Err.Clear
            On Error Goto 0
            Err.Raise 1203, &quot;IncludeLibrary.PathToLibraries&quot;, _
                &quot;Can&#039;t let PathToLibraries [&quot; &amp; strFileName &amp; &quot;]:&quot; &amp; strErrDescription
            Exit Property
        End If
        
        On Error Goto 0
    End Property
    &#039; ---------------------------------------------------------------------------
    Public Property Get PathToLibraries()
        Dim strValue
        
        On Error Resume Next
        
        strValue = objWshShell.RegRead(strRegKey)
        
        If Err.Number &lt;&gt; 0 Then
            Err.Clear
            PathToLibraries = &quot;&quot;
            Exit Property
        End If
        
        On Error Goto 0
        
        PathToLibraries = strValue
    End Property
    &#039; ---------------------------------------------------------------------------
    Public Property Let SimpleReEntrant(blnValue)
        If UCase(TypeName(blnValue)) = &quot;BOOLEAN&quot; Then
            blnSimpleReEntrant = blnValue
        Else
            Err.Raise 1204, &quot;IncludeLibrary.SimpleReEntrant&quot;, _
                &quot;Can&#039;t let SimpleReEntrant property: parameter [&quot; &amp; blnValue &amp; &quot;] is not boolean&quot;
            Exit Property
        End If
    End Property
    &#039; ---------------------------------------------------------------------------
    Public Property Get SimpleReEntrant()
        SimpleReEntrant = blnSimpleReEntrant
    End Property
End Class
&#039; ================================================================================</code></pre></div><p>Класс <strong>IncludeLibrary</strong> реализует два свойства и один метод.</p><p>Свойство <strong>PathToLibraries</strong>: string, Read/Write; значение по умолчанию берётся из ключа реестра &quot;HKEY_CURRENT_USER\Software\VBScript\PathToLibraries&quot;, если оно присутствует; там же сохраняется заданное значение свойства.</p><p>Свойство <strong>SimpleReEntrant</strong>: boolean, Read/Write; значение по умолчанию - False.</p><p>Метод <strong>LoadLibrary(strValue)</strong>: метод по умолчанию; загружает текст указанной библиотеки.<br />strValue — string, путь к файлу библиотеки. Если не указан полный путь, сначала происходит поиск файла библиотеки в текущей папке (не в папке скрипта!), затем - с использованием значения свойства PathToLibraries.</p><p>Автор примеров - <strong>alexii</strong>.</p>]]></content>
			<author>
				<name><![CDATA[The gray Cardinal]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=2</uri>
			</author>
			<updated>2008-01-20T11:28:11Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=8123#p8123</id>
		</entry>
		<entry>
			<title type="html"><![CDATA[VBScript: имитация Include для целей повторного использования кода]]></title>
			<link rel="alternate" href="https://forum.script-coding.com/viewtopic.php?pid=8122#p8122" />
			<content type="html"><![CDATA[<p>Простейший пример имитации Include.<br />Код файла test.vbs, являющегося подключаемой &quot;библиотекой&quot;:<br /></p><div class="codebox"><pre><code>Dim param
param = &quot;Test&quot;</code></pre></div><p>Использование &quot;библиотеки&quot;:<br /></p><div class="codebox"><pre><code>&#039;/// Файл, код которого включаем
Include &quot;test.vbs&quot;

&#039;/// Переменная, созданая в результате включения
msgbox Param

&#039;/// Функция включения
Function Include(FilePath)
    Set FileSystemObject = CreateObject(&quot;Scripting.FileSystemObject&quot;)
    ParentFolderName = FileSystemObject.GetParentFolderName(WScript.ScriptFullName)
    FilePath = FileSystemObject.BuildPath(ParentFolderName, FilePath)
    ExecuteGlobal FileSystemObject.OpenTextFile(FilePath, 1).ReadAll
End Function</code></pre></div><p>Автор примера - <strong>Xameleon</strong>.</p>]]></content>
			<author>
				<name><![CDATA[The gray Cardinal]]></name>
				<uri>https://forum.script-coding.com/profile.php?id=2</uri>
			</author>
			<updated>2008-01-20T11:01:36Z</updated>
			<id>https://forum.script-coding.com/viewtopic.php?pid=8122#p8122</id>
		</entry>
</feed>
