HarePoint Explorer for SharePoint
 

Построение сценариев

Построение сценариев выполняется путем написания программного кода на языке C# или Visual Basic. Вся работа со сценариями происходит в окне построения сценариев.

При создании окна сценария HarePoint Explorer for SharePoint генерирует его минимальный программный код:

C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using MAPILab.SharePoint.Explorer.CodeForm;
using MAPILab.SharePoint.Explorer.Utilities.ScriptRunner;

public class Tester
{
    static void Main(
         MAPILab.SharePoint.Explorer.CodeForm.MLCodeForm thisForm
        ,MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.MLBrowser browser
        )
    {      
        
        
        // Output browser configuration
        //browser.Text = "Browser window";
        //browser.DisplayMode = MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.DisplayMode.Expanded;
        browser.ReturnValue = null;
    }
}

Visual Basic

Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Text
Imports MAPILab.SharePoint.Explorer.CodeForm
Imports MAPILab.SharePoint.Explorer.Utilities.ScriptRunner

Public Class Tester
    Shared Sub Main(ByVal thisForm As MAPILab.SharePoint.Explorer.CodeForm.MLCodeForm, 
                    ByVal browser As MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.MLBrowser)
               
               
        ' Output browser configuration
        'browser.Text = "Browser window"
        'browser.DisplayMode = MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.DisplayMode.Expanded
        browser.ReturnValue = Nothing
    End Sub
End Class

Этот код содержит описание класса Tester, включающего в себя статический метод main.

Метод main является стартовой точкой выполнения сценария. Сигнатура этого метода генерируется автоматически, на основе информации о выбранных объектах в окнах браузера. Вне зависимости от состояния окон браузера, метод main всегда получает параметр thisForm и параметр browser. Параметр thisForm содержит ссылку на само окно построения сценария. Объект, возвращаемый методом main через параметр browser отображается в новом окне браузера (за исключением тех случае, когда возвращается нулевая ссылка).

Пример использования параметра browser и его параметров

Парметр browser используется для визуализации и возврата одного или нескольких необходимых объектов в ходе выполнения сценария. Параметр browser имеет следующие свойства:

  1. Text - Заголовок вкладки браузера объектной модели, если свойство не задано, по умолчанию отображается имя объекта или его тип.
  2. DisplayMode - Способ отображения исследуемого объекта. Принимает значения Raw и Expanded. По умолчанию используется значение Raw. Но для удобства отображения объектов-коллекций или массивов объектов можно использовать Expanded.
  3. RaturnValue - Отображаемый в браузере объект.

Продемонстрируем использование параметра browser для отображения коллекции сервисов фермы SharePoint.

Пусть в окне браузера помечено свойство Services.

Показать скриншот

Пусть в окне браузера помечено свойство Services

Создадим новое окно сценария и выполним следующий код, возвращающий через параметр browser коллекцию сервисов в Raw моде:

C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using MAPILab.SharePoint.Explorer.CodeForm;
using MAPILab.SharePoint.Explorer.Utilities.ScriptRunner;

public class Tester
{
    static void Main(
         Microsoft.SharePoint.Administration.SPServiceCollection services1
        ,MAPILab.SharePoint.Explorer.CodeForm.MLCodeForm thisForm
        ,MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.MLBrowser browser
        )
    {        
        
        // Output browser configuration
        browser.Text = "Raw Display Mode";
        browser.DisplayMode = MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.DisplayMode.Raw;
        browser.ReturnValue = services1;
    }
}

Visual Basic

Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Text
Imports MAPILab.SharePoint.Explorer.CodeForm
Imports MAPILab.SharePoint.Explorer.Utilities.ScriptRunner

Public Class Tester
    Shared Sub Main(ByVal services1 As Microsoft.SharePoint.Administration.SPServiceCollection, 
                    ByVal thisForm As MAPILab.SharePoint.Explorer.CodeForm.MLCodeForm, 
                    ByVal browser As MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.MLBrowser)        
        
        ' Output browser configuration
        browser.Text = "Raw Display Mode"
        browser.DisplayMode = MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.DisplayMode.Raw
        browser.ReturnValue = services1
    End Sub
End Class

В результате выполнения сценария получим следующий результат:

Показать скриншот

Коллекция сервисов в Raw Display Mode

Теперь выполним следующий код, возвращающий через параметр browser коллекцию сервисов в Expanded моде:

C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using MAPILab.SharePoint.Explorer.CodeForm;
using MAPILab.SharePoint.Explorer.Utilities.ScriptRunner;

public class Tester
{
    static void Main(
         Microsoft.SharePoint.Administration.SPServiceCollection services1
        ,MAPILab.SharePoint.Explorer.CodeForm.MLCodeForm thisForm
        ,MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.MLBrowser browser
        )
    {        
        
        // Output browser configuration
        browser.Text = "Expanded Display Mode";
        browser.DisplayMode = MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.DisplayMode.Expanded;
        browser.ReturnValue = services1;
    }
}

Visual Basic

Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Text
Imports MAPILab.SharePoint.Explorer.CodeForm
Imports MAPILab.SharePoint.Explorer.Utilities.ScriptRunner

Public Class Tester
    Shared Sub Main(ByVal services1 As Microsoft.SharePoint.Administration.SPServiceCollection, 
                    ByVal thisForm As MAPILab.SharePoint.Explorer.CodeForm.MLCodeForm, 
                    ByVal browser As MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.MLBrowser)        
        
        ' Output browser configuration
        browser.Text = "Expanded Display Mode"
        browser.DisplayMode = MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.DisplayMode.Expanded
        browser.ReturnValue = services1
    End Sub
End Class

В результате выполнения сценария получим следующий результат:

Показать скриншот

Коллекция сервисов в Raw Display Mode

В программном коде сценария неизменными должны оставаться только имя класса Tester и сигнатура метода main – все остальное можно изменять как угодно. Можно добавлять в сценарий описание дополнительных типов, модифицировать описание как класса Tester, так и тело метода main и т.п.

Как уже было сказано ранее, сигнатура метода main генерируется автоматически, в зависимости от набора объектов, выделенных флагами в окнах браузера. Учитывая тот факт, что в окне браузера можно выделить флагом не только свойство или поле, но и какой-либо метод, результат генерации метода main будет сильно отличаться. Для демонстрации сказанного, рассмотрим два примера.

Пример генерации метода main при выборе свойства или поля

Пусть в окне браузера помечено несколько свойств или полей, как это показано на нижеследующем рисунке.

Показать скриншот

Пусть в окне браузера помечено несколько свойств или полей

В этом случае, при создании нового окна сценария, метод main будет иметь следующий вид:

C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using MAPILab.SharePoint.Explorer.CodeForm;
using MAPILab.SharePoint.Explorer.Utilities.ScriptRunner;

public class Tester
{
    static void Main(
         System.Version buildVersion1
        ,bool canRenameOnRestore2
        ,bool canSelectForBackup3
        ,MAPILab.SharePoint.Explorer.CodeForm.MLCodeForm thisForm
        ,MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.MLBrowser browser
        )
    {
                
        // Output browser configuration
        //browser.Text = "Browser window";
        //browser.DisplayMode = MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.DisplayMode.Expanded;
        
        browser.ReturnValue = null;
    }
}

Visual Basic

Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Text
Imports MAPILab.SharePoint.Explorer.CodeForm
Imports MAPILab.SharePoint.Explorer.Utilities.ScriptRunner

Public Class Tester
    Shared Sub Main(ByVal buildVersion1 As System.Version, 
                    ByVal canRenameOnRestore2 As Boolean, 
                    ByVal canSelectForBackup3 As Boolean, 
                    ByVal thisForm As MAPILab.SharePoint.Explorer.CodeForm.MLCodeForm, 
                    ByVal browser As MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.MLBrowser)        
        
        ' Output browser configuration
        'browser.Text = "Browser window"
        'browser.DisplayMode = MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.DisplayMode.Expanded
        
        browser.ReturnValue = Nothing
    End Sub
End Class

Из примера видно, что сгенерированная сигнатура метода main содержит, помимо обязательного параметра thisForm еще и автоматически добавленные параметры buildVersion1, canRenameOnRestore2, canSelectForBackup3, соответствующие объектам, выбранным в окне браузера.

Выполним простейшую модификацию сгенерированного метода. Поместим строковое представление версии SharePoint в заголовок окна сценария, а также выведем строку Current SharePoint version is … в поле вывода результатов:

C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using MAPILab.SharePoint.Explorer.CodeForm;
using MAPILab.SharePoint.Explorer.Utilities.ScriptRunner;

public class Tester
{
    static void Main(
         System.Version buildVersion1
        ,bool canRenameOnRestore2
        ,bool canSelectForBackup3
        ,MAPILab.SharePoint.Explorer.CodeForm.MLCodeForm thisForm
        ,MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.MLBrowser browser
        )
    {   
        // Put SharePoint version to code windows caption
        thisForm.Text = buildVersion1.ToString();

        // Make debug output
        Debug.Print("Current SharePoint version is {0}", buildVersion1);
        
        // Output browser configuration
        //browser.Text = "Browser window";
        //browser.DisplayMode = MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.DisplayMode.Expanded;
        
        browser.ReturnValue = null;
    }
}

Visual Basic

Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Text
Imports MAPILab.SharePoint.Explorer.CodeForm
Imports MAPILab.SharePoint.Explorer.Utilities.ScriptRunner

Public Class Tester
    Shared Sub Main(ByVal buildVersion1 As System.Version, 
                    ByVal canRenameOnRestore2 As Boolean, 
                    ByVal canSelectForBackup3 As Boolean, 
                    ByVal thisForm As MAPILab.SharePoint.Explorer.CodeForm.MLCodeForm, 
                    ByVal browser As MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.MLBrowser)
        
        'Put SharePoint version to code windows caption
        thisForm.Text = buildVersion1.ToString()

        'Make debug output
        Debug.Print("Current SharePoint version is {0}", buildVersion1)
        ' Output browser configuration
        'browser.Text = "Browser window"
        'browser.DisplayMode = MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.DisplayMode.Expanded
        
        browser.ReturnValue = Nothing
    End Sub
End Class

Для того чтобы убедиться в отсутствии ошибок в программном коде его можно откомпилировать, нажав клавишу F7 или F6 или выбрав пункт меню Action – Compile.

Для того чтобы выполнить сценарий, нужно нажать клавишу F5 или выбрать пункт меню Action – Run.

Сценарий можно выполнять как в синхронном режиме так и в асинхронном. Асинхронный режим позволяет останавливать "зависшие" сценарии.

После выполнения приведенного здесь сценария, окно примет следующий вид (обратите внимание на места, обведенные красными прямоугольниками):

Показать скриншот

После выполнения приведенного здесь сценария...

Пример генерации метода main при выборе метода

При выборе в дереве браузера какого-либо метода, генерируется не только сигнатура метода main, но и часть его тела – в него заранее подставляется шаблон вызова выбранного метода. Продемонстрируем сказанное на примере.

Пусть в окне браузера помечен один из методов (один – для простоты), как это показано на нижеследующем рисунке (кстати, для примера выбран метод, позволяющий получить описание возможности SharePoint в формате XML).

Показать скриншот

В окне браузера помечен один из методов

В этом случае, при создании нового окна сценария, метод main будет иметь следующий вид:

C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using MAPILab.SharePoint.Explorer.CodeForm;
using MAPILab.SharePoint.Explorer.Utilities.ScriptRunner;

public class Tester
{
    static void Main(
         Microsoft.SharePoint.Administration.SPFeatureDefinition mo_getXmlDefinition1
        ,System.Reflection.MethodInfo getXmlDefinition1
        ,MAPILab.SharePoint.Explorer.CodeForm.MLCodeForm thisForm
        ,MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.MLBrowser browser
        )
    {
        // Calling method GetXmlDefinition
        System.Globalization.CultureInfo value1 = ;
        
        System.Xml.XmlNode value2 = 
            mo_getXmlDefinition1.GetXmlDefinition(
                value1);
                       
        // Output browser configuration
        //browser.Text = "Browser window";
        //browser.DisplayMode = MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.DisplayMode.Expanded;
        browser.ReturnValue = null;
    }
}

Visual Basic

Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Text
Imports MAPILab.SharePoint.Explorer.CodeForm
Imports MAPILab.SharePoint.Explorer.Utilities.ScriptRunner

Public Class Tester
    Shared Sub Main(ByVal mo_getXmlDefinition1 As Microsoft.SharePoint.Administration.SPFeatureDefinition, 
                    ByVal getXmlDefinition1 As System.Reflection.MethodInfo, ByVal thisForm As MAPILab.SharePoint.Explorer.CodeForm.MLCodeForm, 
                    ByVal browser As MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.MLBrowser)
        
        ' Calling method GetXmlDefinition
        Dim value1 As System.Globalization.CultureInfo = 
        Dim value2 As System.Xml.XmlNode = mo_getXmlDefinition1.GetXmlDefinition(value1)
                       
        ' Output browser configuration
        'browser.Text = "Browser window"
        'browser.DisplayMode = MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.DisplayMode.Expanded
        
        browser.ReturnValue = Nothing
    End Sub
End Class

Из этого примера видно, что теперь помимо самого объекта типа MethodInfo, выбранного в браузере, в список параметров метода main входит еще и параметр mo_getXmlDefinition1, содержащий ссылку на тот объект, чей метод нужно вызвать. Более того, тело метода уже содержит шаблон, максимально облегчающий вызов выбранного метода. Остается только дополнить его (а именно задать значение переменной value1) и как-то распорядиться результатом вызова, который будет помещен в переменную value2. Модифицируем этот код таким образом, чтобы xml, описывающий свойства возможности SharePoint сначала был показан во всплывающем окне, а потом объект типа XmlNode, появился в новом окне браузера:

C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using MAPILab.SharePoint.Explorer.CodeForm;
using MAPILab.SharePoint.Explorer.Utilities.ScriptRunner;

public class Tester
{
    static void Main(
         Microsoft.SharePoint.Administration.SPFeatureDefinition mo_getXmlDefinition1
        ,System.Reflection.MethodInfo getXmlDefinition1
        ,MAPILab.SharePoint.Explorer.CodeForm.MLCodeForm thisForm
        ,MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.MLBrowser browser
        )
    {
        // Calling method GetXmlDefinition
        System.Globalization.CultureInfo value1 = System.Threading.Thread.CurrentThread.CurrentCulture;
        
        System.Xml.XmlNode value2 = 
            mo_getXmlDefinition1.GetXmlDefinition(
                value1);
        
        // Show Feature XML using MessageBox class
        System.Windows.Forms.MessageBox.Show(value2.OuterXml);
                              
        // Output browser configuration
        //browser.Text = "Browser window";
        //browser.DisplayMode = MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.DisplayMode.Expanded;
        
        // Return results to the new object browser
        browser.ReturnValue = value2;
    }
}

Visual Basic

Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Text
Imports MAPILab.SharePoint.Explorer.CodeForm
Imports MAPILab.SharePoint.Explorer.Utilities.ScriptRunner

Public Class Tester
    Shared Sub Main(ByVal mo_getXmlDefinition1 As Microsoft.SharePoint.Administration.SPFeatureDefinition, ByVal getXmlDefinition1 As System.Reflection.MethodInfo, ByVal thisForm As MAPILab.SharePoint.Explorer.CodeForm.MLCodeForm, ByVal browser As MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.MLBrowser)
        
        ' Calling method GetXmlDefinition
        Dim value1 As System.Globalization.CultureInfo
        value1 = System.Threading.Thread.CurrentThread.CurrentCulture
        
        Dim value2 As System.Xml.XmlNode
        value2 = mo_getXmlDefinition1.GetXmlDefinition(value1)
             
        'Show Feature XML using MessageBox class
        System.Windows.Forms.MessageBox.Show(value2.OuterXml)
                       
        ' Output browser configuration
        'browser.Text = "Browser window"
        'browser.DisplayMode = MAPILab.SharePoint.Explorer.Utilities.ScriptRunner.DisplayMode.Expanded
        
        'Return results to the new object browser
        browser.ReturnValue = value2
    End Sub
End Class

В результате выполнения сценария (клавиша F5), мы последовательно увидим:

Показать скриншот

Показать скриншот

Здесь мы рассмотрели случаи работы с выбранными свойствами или методами по отдельности, однако ничего не мешает выбирать в браузере и то и другое одновременно. В этом случае будет сгенерирована сигнатура метода main, включающая как первый, так и второй варианты.