Бөлісу құралы:


InstallerCollection Класс

Определение

Содержит коллекцию установщиков, выполняемых во время установки.

public ref class InstallerCollection : System::Collections::CollectionBase
public class InstallerCollection : System.Collections.CollectionBase
type InstallerCollection = class
    inherit CollectionBase
Public Class InstallerCollection
Inherits CollectionBase
Наследование
InstallerCollection

Примеры

В следующем примере демонстрируется Add метод InstallerCollection класса. В этом примере представлена реализация, аналогичнаяInstallutil.exe (средство установщика). Он устанавливает сборки с параметрами, предшествующими этой конкретной сборке. Если параметр не указан для сборки, параметры предыдущей сборки принимаются при наличии предыдущей сборки в списке. Если указан параметр "/u" или "/uninstall", сборки удаляются. Если указан параметр "/?" или "/help", сведения справки отображаются в консоли.

#using <System.dll>
#using <System.Configuration.Install.dll>

using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Configuration::Install;
using namespace System::IO;

void PrintHelpMessage()
{
   Console::WriteLine( "Usage : InstallerCollection_Add [/u | /uninstall] [option [...]] assembly " +
      "[[option [...]] assembly] [...]]" );
   Console::WriteLine( "InstallerCollection_Add executes the installers in each of" +
      "the given assembly. If /u or /uninstall option" + 
      "option is given it uninstalls the assemblies." );
}

int main()
{
   array<String^>^ args = Environment::GetCommandLineArgs();
   ArrayList^ options = gcnew ArrayList;
   String^ myOption;
   bool toUnInstall = false;
   bool toPrintHelp = false;
   TransactedInstaller^ myTransactedInstaller = gcnew TransactedInstaller;
   AssemblyInstaller^ myAssemblyInstaller;
   InstallContext^ myInstallContext;

   try
   {
      for ( int i = 0; i < args->Length; i++ )
      {
         // Process the arguments.
         if ( args[ i ]->StartsWith( "/" ) || args[ i ]->StartsWith( "-" ) )
         {
            myOption = args[ i ]->Substring( 1 );
            // Determine whether the option is to 'uninstall' a assembly.
            if ( String::Compare( myOption, "u", true ) == 0 ||
               String::Compare( myOption, "uninstall", true ) == 0 )
            {
               toUnInstall = true;
               continue;
            }
            // Determine whether the option is for printing help information.
            if ( String::Compare( myOption, "?", true ) == 0 ||
               String::Compare( myOption, "help", true ) == 0 )
            {
               toPrintHelp = true;
               continue;
            }
            // Add the option encountered to the list of all options
            // encountered for the current assembly.
            options->Add( myOption );
         }
         else
         {
            // Determine whether the assembly file exists.
            if (  !File::Exists( args[ i ] ) )
            {
               // If assembly file doesn't exist then print error.
               Console::WriteLine( " Error : {0} - Assembly file doesn't exist.", args[ i ] );
               return 0;
            }
            // Create an instance of 'AssemblyInstaller' that installs the given assembly.
            myAssemblyInstaller = gcnew AssemblyInstaller( args[ i ],
              (array<String^>^)(options->ToArray( String::typeid )) );
            // Add the instance of 'AssemblyInstaller' to the 'TransactedInstaller'.
            myTransactedInstaller->Installers->Add( myAssemblyInstaller );
         }
      }
      // then print help message.
      if ( toPrintHelp || myTransactedInstaller->Installers->Count == 0 )
      {
         PrintHelpMessage();
         return 0;
      }

      // Create an instance of 'InstallContext' with the options specified.
      myInstallContext =
         gcnew InstallContext( "Install.log",
              (array<String^>^)(options->ToArray( String::typeid )) );
      myTransactedInstaller->Context = myInstallContext;

      // Install or Uninstall an assembly depending on the option provided.
      if (  !toUnInstall )
         myTransactedInstaller->Install( gcnew Hashtable );
      else
         myTransactedInstaller->Uninstall( nullptr );
   }
   catch ( Exception^ e ) 
   {
      Console::WriteLine( " Exception raised : {0}", e->Message );
   }
}
using System;
using System.ComponentModel;
using System.Collections;
using System.Configuration.Install;
using System.IO;

public class InstallerCollection_Add
{
   public static void Main(String[] args)
   {
      ArrayList options = new ArrayList();
      String myOption;
      bool toUnInstall = false;
      bool toPrintHelp = false;
      TransactedInstaller myTransactedInstaller = new TransactedInstaller();
      AssemblyInstaller myAssemblyInstaller;
      InstallContext myInstallContext;

      try
      {
         for(int i = 0; i < args.Length; i++)
         {
            // Process the arguments.
            if(args[i].StartsWith("/") || args[i].StartsWith("-"))
            {
               myOption = args[i].Substring(1);
               // Determine whether the option is to 'uninstall' a assembly.
               if(String.Compare(myOption, "u", true) == 0 ||
                  String.Compare(myOption, "uninstall", true) == 0)
               {
                  toUnInstall = true;
                  continue;
               }
               // Determine whether the option is for printing help information.
               if(String.Compare(myOption, "?", true) == 0 ||
                  String.Compare(myOption, "help", true) == 0)
               {
                  toPrintHelp = true;
                  continue;
               }
               // Add the option encountered to the list of all options
               // encountered for the current assembly.
               options.Add(myOption);
            }
            else
            {
               // Determine whether the assembly file exists.
               if(!File.Exists(args[i]))
               {
                  // If assembly file doesn't exist then print error.
                  Console.WriteLine(" Error : {0} - Assembly file doesn't exist.", args[i]);
                  return;
               }
               // Create an instance of 'AssemblyInstaller' that installs the given assembly.
               myAssemblyInstaller = new AssemblyInstaller(args[i],
                  (string[]) options.ToArray(typeof(string)));
               // Add the instance of 'AssemblyInstaller' to the 'TransactedInstaller'.
               myTransactedInstaller.Installers.Add(myAssemblyInstaller);
            }
         }
         // If user requested help or didn't provide any assemblies to install
         // then print help message.
         if(toPrintHelp || myTransactedInstaller.Installers.Count == 0)
         {
            PrintHelpMessage();
            return;
         }

         // Create an instance of 'InstallContext' with the options specified.
         myInstallContext =
            new InstallContext("Install.log",
            (string[]) options.ToArray(typeof(string)));
         myTransactedInstaller.Context = myInstallContext;

         // Install or Uninstall an assembly depending on the option provided.
         if(!toUnInstall)
            myTransactedInstaller.Install(new Hashtable());
         else
            myTransactedInstaller.Uninstall(null);
      }
      catch(Exception e)
      {
         Console.WriteLine(" Exception raised : {0}", e.Message);
      }
   }

   public static void PrintHelpMessage()
   {
      Console.WriteLine("Usage : InstallerCollection_Add [/u | /uninstall] [option [...]] assembly" +
         "[[option [...]] assembly] [...]]");
      Console.WriteLine("InstallerCollection_Add executes the installers in each of" +
         " the given assembly. If /u or /uninstall option" +
         " is given it uninstalls the assemblies.");
   }
}
Imports System.ComponentModel
Imports System.Collections
Imports System.Configuration.Install
Imports System.IO

Public Class InstallerCollection_Add
   
   'Entry point which delegates to C-style main Private Function
   Public Overloads Shared Sub Main()
      Main(System.Environment.GetCommandLineArgs())
   End Sub
   
   Overloads Public Shared Sub Main(args() As String)
      Dim options As New ArrayList()
      Dim myOption As String
      Dim toUnInstall As Boolean = False
      Dim toPrintHelp As Boolean = False
      Dim myTransactedInstaller As New TransactedInstaller()
      Dim myAssemblyInstaller As AssemblyInstaller
      Dim myInstallContext As InstallContext
      
      Try
         Dim i As Integer
         For i = 1 To args.Length - 1
            ' Process the arguments.
            If args(i).StartsWith("/") Or args(i).StartsWith("-") Then
               myOption = args(i).Substring(1)
               ' Determine whether the option is to 'uninstall' a assembly.
               If String.Compare(myOption, "u", True) = 0 Or String.Compare(myOption, "uninstall", _
                                                                              True) = 0 Then
                  toUnInstall = True
                  GoTo ContinueFor1
               End If
               ' Determine whether the option is for printing help information.
               If String.Compare(myOption, "?", True) = 0 Or String.Compare(myOption, "help", _
                                                                                 True) = 0 Then
                  toPrintHelp = True
                  GoTo ContinueFor1
               End If
               ' Add the option encountered to the list of all options
               ' encountered for the current assembly.
               options.Add(myOption)
            Else
               ' Determine whether the assembly file exists.
               If Not File.Exists(args(i)) Then
                  ' If assembly file doesn't exist then print error.
                  Console.WriteLine(" Error : {0} - Assembly file doesn't exist.", args(i))
                  Return
               End If
               ' Create an instance of 'AssemblyInstaller' that installs the given assembly.
               myAssemblyInstaller = New AssemblyInstaller(args(i), CType(options.ToArray _
                                                               (GetType(String)), String()))
               ' Add the instance of 'AssemblyInstaller' to the 'TransactedInstaller'.
               myTransactedInstaller.Installers.Add(myAssemblyInstaller)
            End If
         ContinueFor1: 
         Next i
         ' If user requested help or didn't provide any assemblies to install
         ' then print help message.
         If toPrintHelp Or myTransactedInstaller.Installers.Count = 0 Then
            PrintHelpMessage()
            Return
         End If
         
         ' Create an instance of 'InstallContext' with the options specified.
         myInstallContext = New InstallContext("Install.log", CType(options.ToArray _
                                                               (GetType(String)), String()))
         myTransactedInstaller.Context = myInstallContext
         
         ' Install or Uninstall an assembly depending on the option provided.
         If Not toUnInstall Then
            myTransactedInstaller.Install(New Hashtable())
         Else
            myTransactedInstaller.Uninstall(Nothing)
         End If
      Catch e As Exception
         Console.WriteLine(" Exception raised : {0}", e.Message)
      End Try
   End Sub

   Public Shared Sub PrintHelpMessage()
      Console.WriteLine("Usage : InstallerCollection_Add [/u | /uninstall] [option [...]]assembly"+ _
                                                               "[[option [...]] assembly] [...]]")
      Console.WriteLine("InstallerCollection_Add executes the installers in each of" + _
      " the given assembly. If /u or /uninstall option is given it uninstalls the assemblies.")
   End Sub
End Class

Комментарии

Предоставляет InstallerCollection методы и свойства, необходимые приложению для управления коллекцией Installer объектов.

Используйте любой из следующих трех способов добавления установщиков в коллекцию:

  • Этот Add метод добавляет в коллекцию один установщик.

  • Методы AddRange добавляют несколько установщиков в коллекцию.

  • Insert Метод и Item[] свойство, являющееся InstallerCollection индексатором, добавляют один установщик в коллекцию по указанному индексу.

Удалите установщики с помощью Remove метода. Проверьте, находится ли установщик в коллекции с помощью Contains метода. Найдите расположение установщика в коллекции с помощью IndexOf метода.

Установщики в коллекции выполняются, когда установщик, содержащий коллекцию, как указано Installer.Parent в свойстве, вызывает их Install, CommitRollbackили Uninstall методы.

Примеры использования коллекции установщика см. в AssemblyInstaller разделе и TransactedInstaller классах.

Свойства

Имя Описание
Capacity

Возвращает или задает количество элементов, которые CollectionBase могут содержаться.

(Унаследовано от CollectionBase)
Count

Возвращает количество элементов, содержащихся в экземпляре CollectionBase . Это свойство нельзя переопределить.

(Унаследовано от CollectionBase)
InnerList

ArrayList Возвращает список элементов в экземпляреCollectionBase.

(Унаследовано от CollectionBase)
Item[Int32]

Возвращает или задает установщик по указанному индексу.

List

IList Возвращает список элементов в экземпляреCollectionBase.

(Унаследовано от CollectionBase)

Методы

Имя Описание
Add(Installer)

Добавляет указанный установщик в эту коллекцию установщиков.

AddRange(Installer[])

Добавляет указанный массив установщиков в эту коллекцию.

AddRange(InstallerCollection)

Добавляет указанную коллекцию установщиков в эту коллекцию.

Clear()

Удаляет все объекты из экземпляра CollectionBase . Этот метод нельзя переопределить.

(Унаследовано от CollectionBase)
Contains(Installer)

Определяет, включен ли указанный установщик в коллекцию.

CopyTo(Installer[], Int32)

Копирует элементы из коллекции в массив, начиная с указанного индекса.

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetEnumerator()

Возвращает перечислитель, который выполняет итерацию по экземпляру CollectionBase .

(Унаследовано от CollectionBase)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает Type текущего экземпляра.

(Унаследовано от Object)
IndexOf(Installer)

Определяет индекс указанного установщика в коллекции.

Insert(Int32, Installer)

Вставляет указанный установщик в коллекцию по указанному индексу.

MemberwiseClone()

Создает неглубокую копию текущей Object.

(Унаследовано от Object)
OnClear()

Выполняет дополнительные пользовательские процессы при очистке содержимого экземпляра CollectionBase .

(Унаследовано от CollectionBase)
OnClearComplete()

Выполняет дополнительные пользовательские процессы после очистки содержимого экземпляра CollectionBase .

(Унаследовано от CollectionBase)
OnInsert(Int32, Object)

Выполняет дополнительные пользовательские процессы перед вставкой нового установщика в коллекцию.

OnInsertComplete(Int32, Object)

Выполняет дополнительные пользовательские процессы после вставки нового элемента в CollectionBase экземпляр.

(Унаследовано от CollectionBase)
OnRemove(Int32, Object)

Выполняет дополнительные пользовательские процессы перед удалением установщика из коллекции.

OnRemoveComplete(Int32, Object)

Выполняет дополнительные пользовательские процессы после удаления элемента из экземпляра CollectionBase .

(Унаследовано от CollectionBase)
OnSet(Int32, Object, Object)

Выполняет дополнительные пользовательские процессы до установки нового значения существующего установщика.

OnSetComplete(Int32, Object, Object)

Выполняет дополнительные пользовательские процессы после задания значения в экземпляре CollectionBase .

(Унаследовано от CollectionBase)
OnValidate(Object)

Выполняет дополнительные пользовательские процессы при проверке значения.

(Унаследовано от CollectionBase)
Remove(Installer)

Удаляет указанный Installer из коллекции.

RemoveAt(Int32)

Удаляет элемент по указанному индексу экземпляра CollectionBase . Этот метод не переопределяется.

(Унаследовано от CollectionBase)
ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Явные реализации интерфейса

Имя Описание
ICollection.CopyTo(Array, Int32)

Копирует все CollectionBase в совместимое одномерное Arrayзначение, начиная с указанного индекса целевого массива.

(Унаследовано от CollectionBase)
ICollection.IsSynchronized

Возвращает значение, указывающее, синхронизирован ли доступ к CollectionBase синхронизированному (потокобезопасно).

(Унаследовано от CollectionBase)
ICollection.SyncRoot

Получает объект, который можно использовать для синхронизации доступа к объекту CollectionBase.

(Унаследовано от CollectionBase)
IList.Add(Object)

Добавляет объект в конец CollectionBase.

(Унаследовано от CollectionBase)
IList.Contains(Object)

Определяет, содержит ли CollectionBase определенный элемент.

(Унаследовано от CollectionBase)
IList.IndexOf(Object)

Выполняет поиск указанного Object и возвращает отсчитываемый от нуля индекс первого вхождения в течение всего CollectionBase.

(Унаследовано от CollectionBase)
IList.Insert(Int32, Object)

Вставляет элемент в CollectionBase указанный индекс.

(Унаследовано от CollectionBase)
IList.IsFixedSize

Возвращает значение, указывающее, имеет ли CollectionBase размер фиксированного размера.

(Унаследовано от CollectionBase)
IList.IsReadOnly

Возвращает значение, указывающее, доступен ли доступ CollectionBase только для чтения.

(Унаследовано от CollectionBase)
IList.Item[Int32]

Возвращает или задает элемент по указанному индексу.

(Унаследовано от CollectionBase)
IList.Remove(Object)

Удаляет первое вхождение определенного объекта из CollectionBase.

(Унаследовано от CollectionBase)

Методы расширения

Имя Описание
AsParallel(IEnumerable)

Включает параллелизацию запроса.

AsQueryable(IEnumerable)

Преобразует IEnumerable в IQueryable.

Cast<TResult>(IEnumerable)

Приведение элементов IEnumerable к указанному типу.

OfType<TResult>(IEnumerable)

Фильтрует элементы IEnumerable на основе указанного типа.

Применяется к

См. также раздел