Share via


Manipulando eventos programaticamente

O tempo de execução SSIS fornece uma coleção de eventos que ocorrem antes, durante e depois da validação e execução de um pacote. Esses eventos podem ser capturados de duas formas. O primeiro método é através da implementação da interface IDTSEvents em uma classe e do fornecimento da classe como um parâmetro para os métodos Execute e Validate do pacote. O segundo método é através da criação de objetos DtsEventHandler, que podem conter outros objetos SSIS, tais como tarefas e loops, que são executados quando ocorre um evento em IDTSEvents. Essa seção descreve esses dois métodos e fornece exemplos de código para demonstrar o seu uso.

Recebendo retornos de chamada de IDTSEvents

Desenvolvedores que criam e executam pacotes programaticamente podem receber notificações de eventos durante o processo de validação e execução através da interface IDTSEvents. Isso é feito através da criação de uma classe que implementa a interface IDTSEvents e do fornecimento dessa classe como um parâmetro para os métodos Validate e Execute de um pacote. Os métodos da classe são chamados, então, pelo mecanismo de tempo de execução quando os eventos ocorrem.

A classe DefaultEvents é uma classe que já implementa a interface IDTSEvents; portanto, outro alternativa à implementação direta de IDTSEvents é derivar de DefaultEvents e substituir os eventos específicos aos quais você deseja responder. Depois, você fornece sua classe como um parâmetro para os métodos Validate e Execute do Package para receber retornos de chamada de eventos.

O exemplo de código a seguir demonstra uma classe que deriva de DefaultEventse substitui o método OnPreExecute. Portanto, a classe é fornecida como um parâmetro para os métodos Validate e Execute do pacote.

using System;
using Microsoft.SqlServer.Dts.Runtime;

namespace Microsoft.SqlServer.Dts.Samples
{
  class Program
  {
    static void Main(string[] args)
    {
      Package p = new Package();
      MyEventsClass eventsClass = new MyEventsClass();

      p.Validate(null, null, eventsClass, null);
      p.Execute(null, null, eventsClass, null, null);

      Console.Read();
    }
  }
  class MyEventsClass : DefaultEvents
  {
    public override void OnPreExecute(Executable exec, ref bool fireAgain)
    {
      // TODO: Add custom code to handle the event.
      Console.WriteLine("The PreExecute event of the " +
        exec.ToString() + " has been raised.");
    }
  }
}
Imports Microsoft.SqlServer.Dts.Runtime

Module Module1

  Sub Main()

    Dim p As Package = New Package()
    Dim eventsClass As MyEventsClass = New MyEventsClass()

    p.Validate(Nothing, Nothing, eventsClass, Nothing)
    p.Execute(Nothing, Nothing, eventsClass, Nothing, Nothing)

    Console.Read()

  End Sub

End Module

Class MyEventsClass
  Inherits DefaultEvents

  Public Overrides Sub OnPreExecute(ByVal exec As Executable, ByRef fireAgain As Boolean)

    ' TODO: Add custom code to handle the event.
    Console.WriteLine("The PreExecute event of the " & _
      exec.ToString() & " has been raised.")

  End Sub

End Class

Criando objetos DtsEventHandler

O mecanismo de tempo de execução fornece um sistema de tratamento e notificação de eventos robusto, altamente flexível através do objeto DtsEventHandler. Esses objetos permitem que você crie fluxos de trabalho inteiros dentro do manipulador de eventos, que só são executados quando ocorre o evento ao qual pertence o manipulador de eventos. O objeto DtsEventHandler é um contêiner que é executado quando o evento correspondente de seu objeto pai dispara. Essa arquitetura permite criar fluxos de trabalho isolados que são executados em resposta a eventos que ocorrem em um contêiner. Como objetos DtsEventHandler são síncronos, a execução só continua quando os manipuladores de eventos anexados ao evento retornam.

O código a seguir demonstra como criar um objeto DtsEventHandler. O código adiciona um FileSystemTask à coleção Executables do pacote e, depois, cria um objeto DtsEventHandler para o evento OnError da tarefa. Um FileSystemTask é adicionado ao manipulador de eventos, que é executado quando o evento OnError ocorre para o primeiro FileSystemTask. Esse exemplo pressupõe que você tem um arquivo chamado C:\Windows\Temp\DemoFile.txt para teste. Na primeira execução do exemplo, o arquivo é copiado com êxito e o manipulador de eventos não é chamado. Na segunda execução do exemplo, o FileSystemTask não consegue copiar o arquivo (pois o valor de OverwriteDestinationFile é false), o manipulador de eventos é chamado, o segundo FileSystemTask exclui o arquivo de origem e o pacote relata falha em função do erro ocorrido.

Exemplo

using System;
using System.IO;
using Microsoft.SqlServer.Dts.Runtime;
using Microsoft.SqlServer.Dts.Tasks.FileSystemTask;

namespace Microsoft.SqlServer.Dts.Samples
{
  class Program
  {
    static void Main(string[] args)
    {
      string f = "DemoFile.txt";
      Executable e;
      TaskHost th;
      FileSystemTask fst;

      Package p = new Package();

      p.Variables.Add("sourceFile", true, String.Empty,
        @"C:\Windows\Temp\" + f);
      p.Variables.Add("destinationFile", true, String.Empty,
        Path.Combine(Directory.GetCurrentDirectory(), f));

      // Create a first File System task and add it to the package.
      // This task tries to copy a file from one folder to another.
      e = p.Executables.Add("STOCK:FileSystemTask");
      th = e as TaskHost;
      th.Name = "FileSystemTask1";
      fst = th.InnerObject as FileSystemTask;

      fst.Operation = DTSFileSystemOperation.CopyFile;
      fst.OverwriteDestinationFile = false;
      fst.Source = "sourceFile";
      fst.IsSourcePathVariable = true;
      fst.Destination = "destinationFile";
      fst.IsDestinationPathVariable = true;

      // Add an event handler for the FileSystemTask's OnError event.
      DtsEventHandler ehOnError = (DtsEventHandler)th.EventHandlers.Add("OnError");

      // Create a second File System task and add it to the event handler.
      // This task deletes the source file if the event handler is called.
      e = ehOnError.Executables.Add("STOCK:FileSystemTask");
      th = e as TaskHost;
      th.Name = "FileSystemTask2";
      fst = th.InnerObject as FileSystemTask;

      fst.Operation = DTSFileSystemOperation.DeleteFile;
      fst.Source = "sourceFile";
      fst.IsSourcePathVariable = true;

      DTSExecResult vr = p.Validate(null, null, null, null);
      Console.WriteLine("ValidationResult = " + vr.ToString());
      if (vr == DTSExecResult.Success)
      {
        DTSExecResult er = p.Execute(null, null, null, null, null);
        Console.WriteLine("ExecutionResult = " + er.ToString());
        if (er == DTSExecResult.Failure)
          if (!File.Exists(@"C:\Windows\Temp\" + f))
            Console.WriteLine("Source file has been deleted by the event handler.");
      }
      Console.Read();
    }
  }
}
Imports System.IO
Imports Microsoft.SqlServer.Dts.Runtime
Imports Microsoft.SqlServer.Dts.Tasks.FileSystemTask

Module Module1

  Sub Main()

    Dim f As String = "DemoFile.txt"
    Dim e As Executable
    Dim th As TaskHost
    Dim fst As FileSystemTask

    Dim p As Package = New Package()

    p.Variables.Add("sourceFile", True, String.Empty, _
      "C:\Windows\Temp\" & f)
    p.Variables.Add("destinationFile", True, String.Empty, _
      Path.Combine(Directory.GetCurrentDirectory(), f))

    ' Create a first File System task and add it to the package.
    ' This task tries to copy a file from one folder to another.
    e = p.Executables.Add("STOCK:FileSystemTask")
    th = CType(e, TaskHost)
    th.Name = "FileSystemTask1"
    fst = CType(th.InnerObject, FileSystemTask)

    fst.Operation = DTSFileSystemOperation.CopyFile
    fst.OverwriteDestinationFile = False
    fst.Source = "sourceFile"
    fst.IsSourcePathVariable = True
    fst.Destination = "destinationFile"
    fst.IsDestinationPathVariable = True

    ' Add an event handler for the FileSystemTask's OnError event.
    Dim ehOnError As DtsEventHandler = CType(th.EventHandlers.Add("OnError"), DtsEventHandler)

    ' Create a second File System task and add it to the event handler.
    ' This task deletes the source file if the event handler is called.
    e = ehOnError.Executables.Add("STOCK:FileSystemTask")
    th = CType(e, TaskHost)
    th.Name = "FileSystemTask1"
    fst = CType(th.InnerObject, FileSystemTask)

    fst.Operation = DTSFileSystemOperation.DeleteFile
    fst.Source = "sourceFile"
    fst.IsSourcePathVariable = True

    Dim vr As DTSExecResult = p.Validate(Nothing, Nothing, Nothing, Nothing)
    Console.WriteLine("ValidationResult = " + vr.ToString())
    If vr = DTSExecResult.Success Then
      Dim er As DTSExecResult = p.Execute(Nothing, Nothing, Nothing, Nothing, Nothing)
      Console.WriteLine("ExecutionResult = " + er.ToString())
      If er = DTSExecResult.Failure Then
        If Not File.Exists("C:\Windows\Temp\" + f) Then
          Console.WriteLine("Source file has been deleted by the event handler.")
        End If
      End If
    End If
    Console.Read()

  End Sub

End Module
Ícone do Integration Services (pequeno) Fique atualizado com o Integration Services

Para obter os mais recentes downloads, artigos, exemplos e vídeos da Microsoft, bem como soluções selecionadas da comunidade, visite a página do Integration Services no MSDN ou TechNet:

Para receber uma notificação automática das atualizações, assine os feeds RSS disponíveis na página.