<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<title><![CDATA[Серый форум &mdash; VBScript: имитация Include для целей повторного использования кода]]></title>
		<link>https://forum.script-coding.com/viewtopic.php?id=1060</link>
		<atom:link href="https://forum.script-coding.com/extern.php?action=feed&amp;tid=1060&amp;type=rss" rel="self" type="application/rss+xml" />
		<description><![CDATA[Недавние сообщения в теме «VBScript: имитация Include для целей повторного использования кода».]]></description>
		<lastBuildDate>Sun, 20 Jan 2008 11:32:20 +0000</lastBuildDate>
		<generator>PunBB</generator>
		<item>
			<title><![CDATA[Re: VBScript: имитация Include для целей повторного использования кода]]></title>
			<link>https://forum.script-coding.com/viewtopic.php?pid=8124#p8124</link>
			<description><![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>]]></description>
			<author><![CDATA[null@example.com (The gray Cardinal)]]></author>
			<pubDate>Sun, 20 Jan 2008 11:32:20 +0000</pubDate>
			<guid>https://forum.script-coding.com/viewtopic.php?pid=8124#p8124</guid>
		</item>
		<item>
			<title><![CDATA[Re: VBScript: имитация Include для целей повторного использования кода]]></title>
			<link>https://forum.script-coding.com/viewtopic.php?pid=8123#p8123</link>
			<description><![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>]]></description>
			<author><![CDATA[null@example.com (The gray Cardinal)]]></author>
			<pubDate>Sun, 20 Jan 2008 11:28:11 +0000</pubDate>
			<guid>https://forum.script-coding.com/viewtopic.php?pid=8123#p8123</guid>
		</item>
		<item>
			<title><![CDATA[VBScript: имитация Include для целей повторного использования кода]]></title>
			<link>https://forum.script-coding.com/viewtopic.php?pid=8122#p8122</link>
			<description><![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>]]></description>
			<author><![CDATA[null@example.com (The gray Cardinal)]]></author>
			<pubDate>Sun, 20 Jan 2008 11:01:36 +0000</pubDate>
			<guid>https://forum.script-coding.com/viewtopic.php?pid=8122#p8122</guid>
		</item>
	</channel>
</rss>
