Aracılığıyla paylaş


Bir Özel hedef bileşen geliştirme

Microsoft SQL Server Integration Services Geliştiriciler, bağlanmak ve verileri özel tüm verileri depolamak özel hedef bileşenleri yazma olanağı verir... kaynak.Varolan kaynak bileşenleri ile birlikte verilen birini kullanarak erişilemiyor veri kaynaklarına bağlanmak gerektiğinde özel hedef bileşenleri yararlıdır. Integration Services.

Hedef bileşenler, bir veya daha fazla girdi ve sıfır çıkışlarını sahiptir.Tasarım sırasında saat, bunlar oluşturmak ve bağlantıları yapılandırmak ve dış veri kaynağından sütun meta veriler okunamıyor.Yürütme sırasında dış verilerine bağlandıklarında kaynak ve bileşenlerin upstream veri akışı için bir dış veri alınan satırlar eklemek kaynak.Varsa dış verileri kaynak bileşen yürütülmesi için önceden varsa, hedef bileşeni bileşen alan sütunların veri türleri, dış veri sütunların veri türleri aynı da emin olmalısınız kaynak.

Bu bölümde, hedef bileşenleri geliştir nasıl ayrıntılarını anlatılır ve önemli kavram açıklığa kavuşturmak için kod örnekleri sağlar.Örnek hedef bileşen için bkz: DatasetDestination Component Sample. Veri akışı bileşen geliştirme genel bir bakış için bkz: Özel veri akışı bileşen geliştirme.

Tasarım zamanı

Uygulama tasarım-saat dış veri kaynağına bağlantı belirtme ve bileşen düzgün yapılandırılmış olduğunu doğrulama bir Hedef bileşeninin işlevselliğini içerir.Bir giriş ve bir hata çıktı, tanım olarak, bir hedef bileşeni vardır.

Bileşeni oluşturma

Hedef bileşenleri kullanarak dış veri kaynaklarına bağlanmak... ConnectionManager tanımlanan nesnelerin bir paket. Hedef bileşeni için bir Bağlantı Yöneticisi, gereksinimini gösterir SSIS Tasarımcı, bileşen için bir öğe ekleyerek, kullanıcılara ve RuntimeConnectionCollection() koleksiyon, ComponentMetaData(). Bu koleksiyon, iki amaca hizmet eder: ilk olarak, bir Bağlantı Yöneticisi için gereksinimini bildirirSSIS Tasarımcı; kullanıcının seçilen veya Bağlantı Yöneticisi oluşturulan sonra daha sonra bunu bağlantı yöneticisinde başvuru tutan paket bileşen tarafından kullanılıyor. Zaman bir IDTSRuntimeConnection100 eklenen koleksiyon, Gelişmiş Düzenleyici görüntüler.Bağlantı özellikleri sekmesi, seçmek veya kullanılacak paketin bileşeni tarafından bir bağlantı oluşturmak için kullanıcıdan.

Aşağıdaki kod örneği uygulaması gösterir. ProvideComponentProperties() bir girdi ekler ve ardından ekler bir IDTSRuntimeConnection100 nesneyi RuntimeConnectionCollection().

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

namespace Microsoft.Samples.SqlServer.Dts
{
    [DtsPipelineComponent(DisplayName = "Destination Component",ComponentType =ComponentType.DestinationAdapter)]
    public class DestinationComponent : PipelineComponent 
    {
        public override void ProvideComponentProperties()
        {
            // Reset the component.
            base.RemoveAllInputsOutputsAndCustomProperties();
            ComponentMetaData.RuntimeConnectionCollection.RemoveAll();

            IDTSInput100 input = ComponentMetaData.InputCollection.New();
            input.Name = "Input";

            IDTSRuntimeConnection100 connection = ComponentMetaData.RuntimeConnectionCollection.New();
            connection.Name = "ADO.net";
        }
    }
}
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports Microsoft.SqlServer.Dts.Pipeline
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime

Namespace Microsoft.Samples.SqlServer.Dts

    <DtsPipelineComponent(DisplayName:="Destination Component", ComponentType:=ComponentType.DestinationAdapter)> _
    Public Class DestinationComponent
        Inherits PipelineComponent

        Public Overrides Sub ProvideComponentProperties()

            ' Reset the component.
            Me.RemoveAllInputsOutputsAndCustomProperties()
            ComponentMetaData.RuntimeConnectionCollection.RemoveAll()

            Dim input As IDTSInput100 = ComponentMetaData.InputCollection.New()
            input.Name = "Input"

            Dim connection As IDTSRuntimeConnection100 = ComponentMetaData.RuntimeConnectionCollection.New()
            connection.Name = "ADO.net"

        End Sub
    End Class
End Namespace

Bir dış veri bağlama kaynak

Bir bağlantı için eklendikten sonra RuntimeConnectionCollection(), size geçersiz AcquireConnections(Object) dış veri bağlantısı için bir yöntem kaynak. Bu yöntem, tasarım zamanı ve çalışma saat olarak adlandırılır.Bileşen çalışma zamanı bağlantı tarafından belirtilen Bağlantı Yöneticisi ve daha sonra dış veri bağlantısı kurmalısınız kaynak.Oluşturulan bileşen bağlantı dahili olarak önbelleğe ve serbest zaman ReleaseConnections() denir. Geliştiriciler bu yöntem geçersiz kılmak ve sırasında bileşen tarafından kurulan bir bağlantı bırakın AcquireConnections(Object). Bu yöntemlerin her ikisi de ReleaseConnections() ve AcquireConnections(Object), tasarım zamanı ve çalışma saat olarak adlandırılır.

Aşağıdaki kod örneği, ADO.NET bağlantınız bağlanan bir bileşeni gösterir AcquireConnections(Object) yöntem ve sonra bağlantıyı kapatır ReleaseConnections().

using Microsoft.SqlServer.Dts.Runtime.Wrapper;

private SqlConnection sqlConnection;

public override void AcquireConnections(object transaction)
{
    if (ComponentMetaData.RuntimeConnectionCollection[0].ConnectionManager != null)
    {
        ConnectionManager cm = Microsoft.SqlServer.Dts.Runtime.DtsConvert.GetWrapper(ComponentMetaData.RuntimeConnectionCollection[0].ConnectionManager);
        ConnectionManagerAdoNet cmado = cm.InnerObject as ConnectionManagerAdoNet;

        if (cmado == null)
            throw new Exception("The ConnectionManager " + cm.Name + " is not an ADO.NET connection.");

        sqlConnection = cmado.AcquireConnection(transaction) as SqlConnection;
        sqlConnection.Open();
    }
}

public override void ReleaseConnections()
{
    if (sqlConnection != null && sqlConnection.State != ConnectionState.Closed)
        sqlConnection.Close();
}
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper

Private sqlConnection As SqlConnection

Public Overrides Sub AcquireConnections(ByVal transaction As Object)

    If IsNothing(ComponentMetaData.RuntimeConnectionCollection(0).ConnectionManager) = False Then

        Dim cm As ConnectionManager = DtsConvert.GetWrapper(ComponentMetaData.RuntimeConnectionCollection(0).ConnectionManager)
        Dim cmado As ConnectionManagerAdoNet = CType(cm.InnerObject,ConnectionManagerAdoNet)

        If IsNothing(cmado) Then
            Throw New Exception("The ConnectionManager " + cm.Name + " is not an ADO.NET connection.")
        End If

        sqlConnection = CType(cmado.AcquireConnection(transaction), SqlConnection)
        sqlConnection.Open()

    End If
End Sub

Public Overrides Sub ReleaseConnections()

    If IsNothing(sqlConnection) = False And sqlConnection.State <> ConnectionState.Closed Then
        sqlConnection.Close()
    End If

End Sub

Bileşen doğrulanıyor

Bileşen geliştiricileri hedef doğrulama açıklandığı biçimde çalışmalıdır Bileşeni doğrulaması.Buna ek olarak, bunlar bileşen giriş sütun koleksiyonunda tanımlanan sütunların veri türü özelliklerini dış veri sütunları eşleştiğini doğrulayın kaynak.Bazen, girdi sütunları karşı dış veri doğrulama kaynak olanaksız ya da, örneğin istenmeyen bileşen veya SSIS Tasarımcı bağlantısı kesik duruma veya yuvarlak gezilerinde sunucuya kabul edilemez olur. Bu durumda, giriş sütun koleksiyon sütunlarda hala kullanarak onaylanabildiğini ExternalMetadataColumnCollection() Giriş nesnesinin.

Bu koleksiyon, giriş ve çıkış nesnelerde bulunan ve bileşen geliştirici dış veri kaynağına adresindeki sütunlarından doldurulması gerekir.Bu koleksiyon giriş sütunları doğrulamak için kullanılan, SSIS Tasarımcı çevrimdışıysa, bileşenin bağlantısı kesildi veya zaman ValidateExternalMetadata() özellik false.

Aşağıdaki örnek kod, varolan bir girdi sütun temel alan bir dış meta veriler sütun ekler.

private void AddExternalMetaDataColumn(IDTSInput100 input,IDTSInputColumn100 inputColumn)
{
    // Set the properties of the external metadata column.
    IDTSExternalMetadataColumn100 externalColumn = input.ExternalMetadataColumnCollection.New();
    externalColumn.Name = inputColumn.Name;
    externalColumn.Precision = inputColumn.Precision;
    externalColumn.Length = inputColumn.Length;
    externalColumn.DataType = inputColumn.DataType;
    externalColumn.Scale = inputColumn.Scale;

    // Map the external column to the input column.
    inputColumn.ExternalMetadataColumnID = externalColumn.ID;
}
Private Sub AddExternalMetaDataColumn(ByVal input As IDTSInput100, ByVal inputColumn As IDTSInputColumn100)

    ' Set the properties of the external metadata column.
    Dim externalColumn As IDTSExternalMetadataColumn100 = input.ExternalMetadataColumnCollection.New()
    externalColumn.Name = inputColumn.Name
    externalColumn.Precision = inputColumn.Precision
    externalColumn.Length = inputColumn.Length
    externalColumn.DataType = inputColumn.DataType
    externalColumn.Scale = inputColumn.Scale

    ' Map the external column to the input column.
    inputColumn.ExternalMetadataColumnID = externalColumn.ID

End Sub

saat çalıştırın.

Yürütme sırasında hedef bileşeni bir çağrı alır ProcessInput(Int32, PipelineBuffer)Yöntem her saat tam bir PipelineBuffer Geliş yönündeki bileşenden kullanılabilir. Bu yöntem kadar daha çok arabellek kullanılabilir sürekli olarak adlandırılır ve EndOfRowset() özellik true. Bu yöntem sırasında hedef bileşenleri arabelleğindeki satır ve sütun okuyun ve dış veriler için ekledikten kaynak.

Arabellekte sütun bulma

Bir bileşen için giriş arabelleği bileşenlerinin upstream bileşen gelen çıktı sütun derlemeleri tanımlanan tüm sütunları içeren veri akışı.Hedef bileşeni, yalnızca iki sütun yazacaksınız olsa bile, çıktısı üç sütundaki bir kaynak bileşeni sağlar ve sonraki bileşeni bir ek çıktı sütunu ekler, hedef bileşeni için sağlanan arabellek, dört sütun içerir.

Giriş arabelleği sütun sırasını Hedef bileşeninin Giriş sütunu koleksiyonunda sütunun dizin tanımlı değil.Sütunları güvenilir bir arabellek satırı yalnızca bulunabilir FindColumnByLineageID(Int32, Int32) yöntem BufferManager(). Bu yöntem, belirtilen lineage KIMLIĞI Belirtilen arabellekte bulunan ve satırda konumunu verir sütun bulur.Sütun giriş dizinleri genellikle sırasında bulunan PreExecute() yöntem ve daha sonra sırasında kullanılacak geliştirici tarafından önbelleğe alınmış ProcessInput(Int32, PipelineBuffer).

Aşağıdaki kod örneği, sırasında arabellekte giriş sütunları konumunu bulur. PreExecute() ve bir dizi içinde saklar. Dizinin daha sonra sırasında kullanılır ProcessInput(Int32, PipelineBuffer) arabellekte sütun değerleri okumak için .

int[] cols;

public override void PreExecute()
{
    IDTSInput100 input = ComponentMetaData.InputCollection[0];

    cols = new int[input.InputColumnCollection.Count];

    for (int x = 0; x < input.InputColumnCollection.Count; x++)
    {
        cols[x] = BufferManager.FindColumnByLineageID(input.Buffer, input.InputColumnCollection[x].LineageID);
    }
}
Private cols As Integer()

Public Overrides Sub PreExecute()

    Dim input As IDTSInput100 = ComponentMetaData.InputCollection(0)

    ReDim cols(input.InputColumnCollection.Count)

    For x As Integer = 0 To input.InputColumnCollection.Count

        cols(x) = BufferManager.FindColumnByLineageID(input.Buffer, input.InputColumnCollection(x).LineageID)
    Next x

End Sub

Satır işleniyor

Giriş sütunları arabellekte bulunan bir kez, okuma ve olması dış veriler için yazılmış kaynak.

Hedef bileşen satırları dış veri kaynağına yazar, ancak "Satır okuma" veya "BLOB bayt okuma" performans sayaçlarını çaðýrarak güncelleştirmek istediğiniz IncrementPipelinePerfCounter(UInt32, UInt32) yöntem. Daha fazla bilgi için bkz:veri akışı altyapısı'nın performansını izleme.

Aşağıdaki örnek, bir bileşen tarafından sağlanan arabellek satırları okur gösterir. ProcessInput(Int32, PipelineBuffer). Dizin arabelleği sütun sırasında bulunamadı PreExecute() Önceki kod örneğinde.

public override void ProcessInput(int inputID, PipelineBuffer buffer)
{
        while (buffer.NextRow())
        {
            foreach (int col in cols)
            {
                if (!buffer.IsNull(col))
                {
                    //  TODO: Read the column data.
                }
            }
        }
}
Public Overrides Sub ProcessInput(ByVal inputID As Integer, ByVal buffer As PipelineBuffer)

        While (buffer.NextRow())

            For Each col As Integer In cols

                If buffer.IsNull(col) = False Then

                    '  TODO: Read the column data.
                End If

            Next col
        End While
End Sub

Örnek

Aşağıdaki örnek, Bağlantı Yöneticisi ikili veri veri akışına dosyaları kaydetmek için bir dosya kullanan basit hedef bileşeni gösterir.Bu örnek tüm yöntemleri ve bu konuda tartışılan işlevselliği gösteren değil.Bu önemli yöntemler her özel hedef bileşeni kılmalıdır ancak Tasarım-CVE-2006-kodunu içeren gösterir saat doğrulama.Bir daha örnek hedef bileşen için bkz: DatasetDestination Component Sample.

using System;
using System.IO;
using Microsoft.SqlServer.Dts.Pipeline;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;

namespace BlobDst
{
  [DtsPipelineComponent(DisplayName = "BLOB Extractor Destination", Description = "Writes values of BLOB columns to files")]
  public class BlobDst : PipelineComponent
  {
    string m_DestDir;
    int m_FileNameColumnIndex = -1;
    int m_BlobColumnIndex = -1;

    public override void ProvideComponentProperties()
    {
      IDTSInput100 input = ComponentMetaData.InputCollection.New();
      input.Name = "BLOB Extractor Destination Input";
      input.HasSideEffects = true;

      IDTSRuntimeConnection100 conn = ComponentMetaData.RuntimeConnectionCollection.New();
      conn.Name = "FileConnection";
    }

    public override void AcquireConnections(object transaction)
    {
      IDTSRuntimeConnection100 conn = ComponentMetaData.RuntimeConnectionCollection[0];
      m_DestDir = (string)conn.ConnectionManager.AcquireConnection(null);

      if (m_DestDir.Length > 0 && m_DestDir[m_DestDir.Length - 1] != '\\')
        m_DestDir += "\\";
    }

    public override IDTSInputColumn100 SetUsageType(int inputID, IDTSVirtualInput100 virtualInput, int lineageID, DTSUsageType usageType)
    {
      IDTSInputColumn100 inputColumn = base.SetUsageType(inputID, virtualInput, lineageID, usageType);
      IDTSCustomProperty100 custProp;

      custProp = inputColumn.CustomPropertyCollection.New();
      custProp.Name = "IsFileName";
      custProp.Value = (object)false;

      custProp = inputColumn.CustomPropertyCollection.New();
      custProp.Name = "IsBLOB";
      custProp.Value = (object)false;

      return inputColumn;
    }

    public override void PreExecute()
    {
      IDTSInput100 input = ComponentMetaData.InputCollection[0];
      IDTSInputColumnCollection100 inputColumns = input.InputColumnCollection;
      IDTSCustomProperty100 custProp;

      foreach (IDTSInputColumn100 column in inputColumns)
      {
        custProp = column.CustomPropertyCollection["IsFileName"];
        if ((bool)custProp.Value == true)
        {
          m_FileNameColumnIndex = (int)BufferManager.FindColumnByLineageID(input.Buffer, column.LineageID);
        }

        custProp = column.CustomPropertyCollection["IsBLOB"];
        if ((bool)custProp.Value == true)
        {
          m_BlobColumnIndex = (int)BufferManager.FindColumnByLineageID(input.Buffer, column.LineageID);
        }
      }
    }

    public override void ProcessInput(int inputID, PipelineBuffer buffer)
    {
      while (buffer.NextRow())
      {
        string strFileName = buffer.GetString(m_FileNameColumnIndex);
        int blobLength = (int)buffer.GetBlobLength(m_BlobColumnIndex);
        byte[] blobData = buffer.GetBlobData(m_BlobColumnIndex, 0, blobLength);

        strFileName = TranslateFileName(strFileName);

        // Make sure directory exists before creating file.
        FileInfo fi = new FileInfo(strFileName);
        if (!fi.Directory.Exists)
          fi.Directory.Create();

        // Write the data to the file.
        FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write, FileShare.None);
        fs.Write(blobData, 0, blobLength);
        fs.Close();
      }
    }

    private string TranslateFileName(string fileName)
    {
      if (fileName.Length > 2 && fileName[1] == ':')
        return m_DestDir + fileName.Substring(3, fileName.Length - 3);
      else
        return m_DestDir + fileName;
    }
  }
}
Imports System 
Imports System.IO 
Imports Microsoft.SqlServer.Dts.Pipeline 
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper 
Namespace BlobDst 

 <DtsPipelineComponent(DisplayName="BLOB Extractor Destination", Description="Writes values of BLOB columns to files")> _ 
 Public Class BlobDst 
 Inherits PipelineComponent 
   Private m_DestDir As String 
   Private m_FileNameColumnIndex As Integer = -1 
   Private m_BlobColumnIndex As Integer = -1 

   Public  Overrides Sub ProvideComponentProperties() 
     Dim input As IDTSInput100 = ComponentMetaData.InputCollection.New 
     input.Name = "BLOB Extractor Destination Input" 
     input.HasSideEffects = True 
     Dim conn As IDTSRuntimeConnection100 = ComponentMetaData.RuntimeConnectionCollection.New 
     conn.Name = "FileConnection" 
   End Sub 

   Public  Overrides Sub AcquireConnections(ByVal transaction As Object) 
     Dim conn As IDTSRuntimeConnection100 = ComponentMetaData.RuntimeConnectionCollection(0) 
     m_DestDir = CType(conn.ConnectionManager.AcquireConnection(Nothing), String) 
     If m_DestDir.Length > 0 AndAlso Not (m_DestDir(m_DestDir.Length - 1) = "\"C) Then 
       m_DestDir += "\" 
     End If 
   End Sub 

   Public  Overrides Function SetUsageType(ByVal inputID As Integer, ByVal virtualInput As IDTSVirtualInput100, ByVal lineageID As Integer, ByVal usageType As DTSUsageType) As IDTSInputColumn100 
     Dim inputColumn As IDTSInputColumn100 = MyBase.SetUsageType(inputID, virtualInput, lineageID, usageType) 
     Dim custProp As IDTSCustomProperty100 
     custProp = inputColumn.CustomPropertyCollection.New 
     custProp.Name = "IsFileName" 
     custProp.Value = CType(False, Object) 
     custProp = inputColumn.CustomPropertyCollection.New 
     custProp.Name = "IsBLOB" 
     custProp.Value = CType(False, Object) 
     Return inputColumn 
   End Function 

   Public  Overrides Sub PreExecute() 
     Dim input As IDTSInput100 = ComponentMetaData.InputCollection(0) 
     Dim inputColumns As IDTSInputColumnCollection100 = input.InputColumnCollection 
     Dim custProp As IDTSCustomProperty100 
     For Each column As IDTSInputColumn100 In inputColumns 
       custProp = column.CustomPropertyCollection("IsFileName") 
       If CType(custProp.Value, Boolean) = True Then 
         m_FileNameColumnIndex = CType(BufferManager.FindColumnByLineageID(input.Buffer, column.LineageID), Integer) 
       End If 
       custProp = column.CustomPropertyCollection("IsBLOB") 
       If CType(custProp.Value, Boolean) = True Then 
         m_BlobColumnIndex = CType(BufferManager.FindColumnByLineageID(input.Buffer, column.LineageID), Integer) 
       End If 
     Next 
   End Sub 

   Public  Overrides Sub ProcessInput(ByVal inputID As Integer, ByVal buffer As PipelineBuffer) 
     While buffer.NextRow 
       Dim strFileName As String = buffer.GetString(m_FileNameColumnIndex) 
       Dim blobLength As Integer = CType(buffer.GetBlobLength(m_BlobColumnIndex), Integer) 
       Dim blobData As Byte() = buffer.GetBlobData(m_BlobColumnIndex, 0, blobLength) 
       strFileName = TranslateFileName(strFileName) 
       Dim fi As FileInfo = New FileInfo(strFileName) 
       ' Make sure directory exists before creating file.
       If Not fi.Directory.Exists Then 
         fi.Directory.Create 
       End If 
       ' Write the data to the file.
       Dim fs As FileStream = New FileStream(strFileName, FileMode.Create, FileAccess.Write, FileShare.None) 
       fs.Write(blobData, 0, blobLength) 
       fs.Close 
     End While 
   End Sub 

   Private Function TranslateFileName(ByVal fileName As String) As String 
     If fileName.Length > 2 AndAlso fileName(1) = ":"C Then 
       Return m_DestDir + fileName.Substring(3, fileName.Length - 3) 
     Else 
       Return m_DestDir + fileName 
     End If 
   End Function 
 End Class 
End Namespace
Integration Services icon (small) Tümleştirme Hizmetleri ile güncel kalın

Karşıdan yüklemeler, makaleleri, örnekler ve en son Microsoft video yanı sıra, seçili topluluğun çözümleri için ziyaret Integration Services sayfa MSDN veya TechNet:

Bu güncelleştirmelerin otomatik bildirim için kullanılabilir RSS akışlarına abone olmak sayfa.