TransactedInstaller Класс

Определение

Определяет установщик, который либо завершается успешно, либо, если происходит сбой, оставляет компьютер в исходном состоянии.

public ref class TransactedInstaller : System::Configuration::Install::Installer
public class TransactedInstaller : System.Configuration.Install.Installer
type TransactedInstaller = class
    inherit Installer
Public Class TransactedInstaller
Inherits Installer
Наследование

Примеры

В следующем примере показаны методы TransactedInstallerTransactedInstaller , Install и Uninstall класса .

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

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

try
{
   for ( int i = 1; 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' an 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.
         myOptions->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( "\nError : {0} - Assembly file doesn't exist.",
               args[ i ] );
            return 0;
         }
         
         // Create a instance of 'AssemblyInstaller' that installs the given assembly.
         myAssemblyInstaller =
            gcnew AssemblyInstaller( args[ i ],
               (array<String^>^)( myOptions->ToArray( String::typeid ) ) );
         // 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 0;
   }
   
   // Create a instance of 'InstallContext' with the options specified.
   myInstallContext =
      gcnew InstallContext( "Install.log",
         (array<String^>^)( myOptions->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( "\nException raised : {0}", e->Message );
}
using System;
using System.ComponentModel;
using System.Collections;
using System.Configuration.Install;
using System.IO;

public class TransactedInstaller_Example
{
   public static void Main(String[] args)
   {
      ArrayList myOptions = 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' an 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.
               myOptions.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("\nError : {0} - Assembly file doesn't exist.",
                     args[i]);
                  return;
               }

               // Create a instance of 'AssemblyInstaller' that installs the given assembly.
               myAssemblyInstaller =
                  new AssemblyInstaller(args[i],
                  (string[]) myOptions.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 a instance of 'InstallContext' with the options specified.
         myInstallContext =
            new InstallContext("Install.log",
            (string[]) myOptions.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("\nException raised : {0}", e.Message);
      }
   }

   public static void PrintHelpMessage()
   {
      Console.WriteLine("Usage : TransactedInstaller [/u | /uninstall] [option [...]] assembly" +
         "[[option [...]] assembly] [...]]");
      Console.WriteLine("TransactedInstaller executes the installers in each of" +
         " the given assembly. If /u or /uninstall option" +
         " is given it uninstalls the assemblies.");
   }
}
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' an 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(ControlChars.Newline + _
                     "Error : {0} - Assembly file doesn't exist.", args(i))
            Return
         End If

         ' Create a 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 a 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(ControlChars.Newline + "Exception raised : {0}", e.Message)
End Try

Комментарии

Чтобы запустить установщики в транзакции, добавьте их в Installers свойство этого TransactedInstaller экземпляра.

Конструкторы

TransactedInstaller()

Инициализирует новый экземпляр класса TransactedInstaller.

Свойства

CanRaiseEvents

Возвращает значение, показывающее, может ли компонент вызывать событие.

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

Возвращает объект IContainer, который содержит коллекцию Component.

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

Получает или задает сведения о текущей установке.

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

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

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

Возвращает список обработчиков событий, которые прикреплены к этому объекту Component.

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

Получает текст справки для всех установщиков из коллекции установщиков.

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

Получает коллекцию установщиков, содержащуюся в данном установщике.

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

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

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

Получает или задает ISite объекта Component.

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

Методы

Commit(IDictionary)

Завершает транзакцию установки, если переопределен в наследующем классе.

(Унаследовано от Installer)
CreateObjRef(Type)

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

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

Освобождает все ресурсы, занятые модулем Component.

(Унаследовано от Component)
Dispose(Boolean)

Освобождает неуправляемые ресурсы, используемые объектом Component, а при необходимости освобождает также управляемые ресурсы.

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

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

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

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

(Унаследовано от Object)
GetLifetimeService()
Устаревшие..

Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра.

(Унаследовано от MarshalByRefObject)
GetService(Type)

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

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

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

(Унаследовано от Object)
InitializeLifetimeService()
Устаревшие..

Получает объект службы времени существования для управления политикой времени существования для этого экземпляра.

(Унаследовано от MarshalByRefObject)
Install(IDictionary)

Производит установку.

MemberwiseClone()

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

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

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

(Унаследовано от MarshalByRefObject)
OnAfterInstall(IDictionary)

Вызывает событие AfterInstall.

(Унаследовано от Installer)
OnAfterRollback(IDictionary)

Вызывает событие AfterRollback.

(Унаследовано от Installer)
OnAfterUninstall(IDictionary)

Вызывает событие AfterUninstall.

(Унаследовано от Installer)
OnBeforeInstall(IDictionary)

Вызывает событие BeforeInstall.

(Унаследовано от Installer)
OnBeforeRollback(IDictionary)

Вызывает событие BeforeRollback.

(Унаследовано от Installer)
OnBeforeUninstall(IDictionary)

Вызывает событие BeforeUninstall.

(Унаследовано от Installer)
OnCommitted(IDictionary)

Вызывает событие Committed.

(Унаследовано от Installer)
OnCommitting(IDictionary)

Вызывает событие Committing.

(Унаследовано от Installer)
Rollback(IDictionary)

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

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

Возвращает объект String, содержащий имя Component, если оно есть. Этот метод не следует переопределять.

(Унаследовано от Component)
Uninstall(IDictionary)

Удаляет компоненты установки.

События

AfterInstall

Происходит после выполнения методов Install(IDictionary) всех установщиков из свойства Installers.

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

Происходит после отката установок всех установщиков из свойства Installers.

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

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

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

Происходит до того, как был запущен метод Install(IDictionary) каждого установщика из коллекции установщиков.

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

Происходит до отката установщиков из свойства Installers.

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

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

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

Происходит после фиксации установки всеми установщиками из свойства Installers.

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

Происходит до фиксации установок установщиками из свойства Installers.

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

Возникает при удалении компонента путем вызова метода Dispose().

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

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