2012-06-29 2 views
2

SSIS Team Blog에서 다음 코드를 가져와 AcquireConnection() 메서드에서 사용할 수 있도록 OLEDB 연결 유형을 형 변환합니다. 이제는 Dts.Connections 파트가 작동하지 않는 이유가 확실하지 않습니다. 나는 그것을 작동하게 만들기 위해 추가해야 할 라이브러리를 모른다. 나는 Dts.RuntimeWrap을 포함하여 가장 중요한 것들을 추가했다. 질문에 대한 자세한 정보가 필요하면 알려주십시오.OLEDB 연결 유형을 참조하는 누락 된 라이브러리

ConnectionManager cm = Dts.Connections["oledb"]; 
Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSConnectionManagerDatabaseParameters100 cmParams = cm.InnerObject as Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSConnectionManagerDatabaseParameters100; 
OleDbConnection conn = cmParams.GetConnectionForSchema() as OleDbConnection; 

편집 다음은이 구성 요소에 대한 전체 코드입니다.

using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Data.SqlClient; 
using Microsoft.SqlServer.Dts.Runtime; 
using System.Data.OleDb; 
using System.Data.Common; 
using System.Linq; 
using System.Configuration; 
using System.Collections; 

//using System.Data.OleDb; 

namespace AOC.SqlServer.Dts.Tasks 
{ 

    [DtsTask(
     DisplayName = "Custom Logging Task", 
     Description = "Writes logging info into a table")] 
    public class CustomLoggingTask : Task 
    { 

     private string _packageName; 
     private string _taskName; 
     private string _errorCode; 
     private string _errorDescription; 
     private string _machineName; 
     private double _packageDuration; 

     private string _connectionName; 
     private string _eventType; 
     private string _executionid; 
     private DateTime _handlerdatetime; 
     private string _uid; 
     public string ConnectionName 
     { 
      set 
      { 
       _connectionName = value; 
      } 
      get 
      { 
       return _connectionName; 
      } 
     } 


     public string Event 
     { 
      set 
      { 
       _eventType = value; 
      } 
      get 
      { 
       return _eventType; 
      } 
     } 

public override DTSExecResult Validate(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log) 
     { 
      const string METHOD_NAME = "CustomLoggingTask-Validate"; 

      try 
      { 

       if (string.IsNullOrEmpty(_eventType)) 
       { 
        componentEvents.FireError(0, METHOD_NAME, "The event property must be specified", "", -1); 
        return DTSExecResult.Failure; 
       } 


       if (string.IsNullOrEmpty(_connectionName)) 
       { 
        componentEvents.FireError(0, METHOD_NAME, "No connection has been specified", "", -1); 
        return DTSExecResult.Failure; 
       } 


       //SqlConnection connection = connections[_connectionName].AcquireConnection(null) as SqlConnection; 
       DbConnection connection = connections[_connectionName].AcquireConnection(null) as DbConnection; 

       ConnectionManager cm = Dts.Connections["oledb"]; 
       Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSConnectionManagerDatabaseParameters100 cmParams = cm.InnerObject as Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSConnectionManagerDatabaseParameters100; 
       OleDbConnection conn = cmParams.GetConnectionForSchema() as OleDbConnection; 



       if (connection == null) 
       { 
        componentEvents.FireError(0, METHOD_NAME, "The connection is not a valid ADO.NET connection", "", -1); 
        return DTSExecResult.Failure; 
       } 

       if (!variableDispenser.Contains("System::SourceID")) 
       { 
        componentEvents.FireError(0, METHOD_NAME, "No System::SourceID variable available. This task can only be used in an Event Handler", "", -1); 
        return DTSExecResult.Failure; 
       } 

       return DTSExecResult.Success; 
      } 
      catch (Exception exc) 
      { 
       componentEvents.FireError(0, METHOD_NAME, "Validation Failed: " + exc.ToString(), "", -1); 
       return DTSExecResult.Failure; 
      } 
     } 


public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction) 
     { 
      try 
      { 
       string commandText = 
@"INSERT INTO SSISLog (EventType, PackageName, TaskName, EventCode, EventDescription, PackageDuration, Host, ExecutionID, EventHandlerDateTime,UID) 
VALUES (@EventType, @PackageName, @TaskName, @EventCode, @EventDescription, @PackageDuration, @Host, @Executionid, @handlerdatetime,@uid)"; 

       ReadVariables(variableDispenser); 
       DbConnection connection = connections[_connectionName].AcquireConnection(transaction) as DbConnection; 
       //SqlConnection connection = (SqlConnection)connections[_connectionName].AcquireConnection(transaction); 
       DbCommand command = null; 
       //using (SqlCommand command = new SqlCommand()) 
       if (connection is SqlConnection) 
        command = new SqlCommand(); 
       else if (connection is OleDbConnection) 
        command = new OleDbCommand(); 

       { 
        command.CommandText = commandText; 
        command.CommandType = CommandType.Text; 
        command.Connection = connection; 

        command.Parameters.Add(new SqlParameter("@EventType", _eventType)); 
        command.Parameters.Add(new SqlParameter("@PackageName", _packageName)); 
        command.Parameters.Add(new SqlParameter("@TaskName", _taskName)); 
        command.Parameters.Add(new SqlParameter("@EventCode", _errorCode ?? string.Empty)); 
        command.Parameters.Add(new SqlParameter("@EventDescription", _errorDescription ?? string.Empty)); 
        command.Parameters.Add(new SqlParameter("@PackageDuration", _packageDuration)); 
        command.Parameters.Add(new SqlParameter("@Host", _machineName)); 
        command.Parameters.Add(new SqlParameter("@ExecutionID", _executionid)); 
        command.Parameters.Add(new SqlParameter("@handlerdatetime", _handlerdatetime)); 
        command.Parameters.Add(new SqlParameter("@uid", _uid)); 
        command.ExecuteNonQuery(); 
       } 
       connection.Close(); 
       return DTSExecResult.Success; 

      } 
      catch (Exception exc) 
      { 
       componentEvents.FireError(0, "CustomLoggingTask-Execute", "Task Errored: " + exc.ToString(), "", -1); 
       return DTSExecResult.Failure; 
      } 

     } 


     private void ReadVariables(VariableDispenser variableDispenser) 
     { 
      variableDispenser.LockForRead("System::StartTime"); 
      variableDispenser.LockForRead("System::PackageName"); 
      variableDispenser.LockForRead("System::SourceName"); 
      variableDispenser.LockForRead("System::MachineName"); 
      variableDispenser.LockForRead("System::ExecutionInstanceGUID"); 
      variableDispenser.LockForRead("System::EventHandlerStartTime"); 
      variableDispenser.LockForRead("User::UID"); 
      bool includesError = variableDispenser.Contains("System::ErrorCode"); 
      if (includesError) 
      { 
       variableDispenser.LockForRead("System::ErrorCode"); 
       variableDispenser.LockForRead("System::ErrorDescription"); 
      } 

      Variables vars = null; 
      variableDispenser.GetVariables(ref vars); 

      DateTime startTime = (DateTime)vars["System::StartTime"].Value; 
      _packageDuration = DateTime.Now.Subtract(startTime).TotalSeconds; 
      _packageName = vars["System::PackageName"].Value.ToString(); 
      _taskName = vars["System::SourceName"].Value.ToString(); 
      _machineName = vars["System::MachineName"].Value.ToString(); 
      _executionid = vars["System::ExecutionInstanceGUID"].Value.ToString(); 
      _handlerdatetime = (DateTime)vars["System::EventHandlerStartTime"].Value; 
      _uid = vars["User::UID"].Value.ToString(); 
      if (includesError) 
      { 
       _errorCode = vars["System::ErrorCode"].Value.ToString(); 
       _errorDescription = vars["System::ErrorDescription"].Value.ToString(); 
      } 

      // release the variable locks. 
      vars.Unlock(); 

      // reset the dispenser 
      variableDispenser.Reset(); 
     } 
    } 

} 
+1

어떤 오류가 발생합니까? 내가 지적한 코드를 테스트 한 결과 올바른 것으로 보입니다. – Chopin

+0

Oledb 연결을 사용하여 비슷한 문제가 발생했습니다. 포기하고 방금 ADO.net 연결을 사용하여 이러한 문제가 발생하지 않습니다. 비록 당신의 사건에 가능성이 있는지는 모르겠지만 ... – cfrag

+0

@Chopin. 오류 메시지가 나타납니다. "오류 \t 1 형식 또는 네임 스페이스 이름 'Connections'이 (가) 네임 스페이스 'AOC.SqlServer.Dts'에 없습니다 (어셈블리 참조가 누락 되었습니까?)"모든 참조 및 내용을 확인했지만 내가 뭘 놓치고 있는지 모르겠다. – rvphx

답변

3

게시 한 코드를 통해 나는 당신이 성취하고자하는 것을 마침내 알게되었습니다.

이 얻을 수있는 내가했던 일들은 그것이 작동 할 수 있습니다

A) 컴파일 에러는 수신있어 :

"Error 1 The type or namespace name 'Connections' does not exist in the namespace 'AOC.SqlServer.Dts' (are you missing an assembly reference?)" 

은 단순히 당신이하려는 방식 때문에 OLEDB 연결 관리자를 얻을 :

ConnectionManager cm = Dts.Connections["oledb"]; 

Dts 개체는이다 스크립트 태스크 구성 요소에서 사용할 수있는 기능 그래서 어쩌면 당신은 그냥 남아 것이었다,이 방법으로 Connection Manager에 액세스 난 당신의 코드에서 본 적이

ConnectionManager cm = connections["oledb"]; 

: 당신과 함께 그 라인을 교체해야합니다. 연결 관리자는 ADO.NET 연결 관리자 또는 OLEDB 하나 하나가있는 경우

B)가 확인하려면, 코드의이 부분을 변경 :

DbConnection connection = connections[_connectionName].AcquireConnection(null) as DbConnection; 

ConnectionManager cm = Dts.Connections["oledb"]; 
Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSConnectionManagerDatabaseParameters100 cmParams = cm.InnerObject as Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSConnectionManagerDatabaseParameters100; 
OleDbConnection conn = cmParams.GetConnectionForSchema() as OleDbConnection; 

if (connection == null) 
{ 
    componentEvents.FireError(0, METHOD_NAME, "The connection is not a valid ADO.NET connection", "", -1); 
    return DTSExecResult.Failure; 
} 

첫째, 클래스에서 개인 변수를 추가 레벨은 연결 저장하기 :

private DbConnection _connection; 

을하고, 연결이 ADO.NET 수 있는지 확인하는 유효성 검사를 수정하고, 경우에 그것은 OLEDB가 있는지 확인하기 위해, 아니다 :

두 경우 모두에서 null의 경우 나는 또한 _connectionName 변수로 하드 코드 "oledb"을 교체하고, 0
_connection = connections[_connectionName].AcquireConnection(null) as DbConnection; 

if (_connection == null) 
{ 
    ConnectionManager cm = connections[_connectionName]; 
    Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSConnectionManagerDatabaseParameters100 cmParams = cm.InnerObject as Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSConnectionManagerDatabaseParameters100; 
    _connection = cmParams.GetConnectionForSchema() as OleDbConnection; 

    if (_connection == null) 
    { 
     componentEvents.FireError(0, METHOD_NAME, "The connection is not a valid ADO.NET or OLEDB connection", "", -1); 
     return DTSExecResult.Failure; 
    } 
} 

참고 오류 문자열을 수정했습니다.

  • 를 사용하여 새로운 _connection 변수, 느릅 나무는 이전에 검색 연결을 원하는 분야

    C)이었다가 다음과 같이 변경 모든 necesary OLEDB 공급자를 사용하여 명령을 실행합니다.

  • 명령에 추가 된 매개 변수는 SqlParameter 대신 OleDbParameter이어야합니다.
  • OLE DB .NET Provider은 명명 된 매개 변수를 지원하지 않습니다.따라서 INSERT 문 명령의 VALUES 부분을 ?으로 수정해야합니다.

D)이 전체 작업 코드 : 그냥 레코드에 대한

using System; 
using System.Data; 
using System.Data.Common; 
using System.Data.OleDb; 
using System.Data.SqlClient; 
using Microsoft.SqlServer.Dts.Runtime; 

//using System.Data.OleDb; 

namespace AOC.SqlServer.Dts.Tasks 
{ 
    [DtsTask(
     DisplayName = "Custom Logging Task", 
     Description = "Writes logging info into a table")] 
    public class CustomLoggingTask : Task 
    { 
     private string _packageName; 
     private string _taskName; 
     private string _errorCode; 
     private string _errorDescription; 
     private string _machineName; 
     private double _packageDuration; 

     private string _connectionName; 
     private string _eventType; 
     private string _executionid; 
     private DateTime _handlerdatetime; 
     private string _uid; 

     public string ConnectionName 
     { 
      set { _connectionName = value; } 
      get { return _connectionName; } 
     } 

     public string Event 
     { 
      set { _eventType = value; } 
      get { return _eventType; } 
     } 

     private DbConnection _connection; 

     public override DTSExecResult Validate(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log) 
     { 
      const string METHOD_NAME = "CustomLoggingTask-Validate"; 

      try 
      { 
       if (string.IsNullOrEmpty(_eventType)) 
       { 
        componentEvents.FireError(0, METHOD_NAME, "The event property must be specified", "", -1); 
        return DTSExecResult.Failure; 
       } 

       if (string.IsNullOrEmpty(_connectionName)) 
       { 
        componentEvents.FireError(0, METHOD_NAME, "No connection has been specified", "", -1); 
        return DTSExecResult.Failure; 
       } 

       //SqlConnection connection = connections[_connectionName].AcquireConnection(null) as SqlConnection; 
       _connection = connections[_connectionName].AcquireConnection(null) as DbConnection; 

       if (_connection == null) 
       { 
        ConnectionManager cm = connections[_connectionName]; 
        Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSConnectionManagerDatabaseParameters100 cmParams = cm.InnerObject as Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSConnectionManagerDatabaseParameters100; 
        _connection = cmParams.GetConnectionForSchema() as OleDbConnection; 

        if (_connection == null) 
        { 
         componentEvents.FireError(0, METHOD_NAME, "The connection is not a valid ADO.NET or OLEDB connection", "", -1); 
         return DTSExecResult.Failure; 
        } 
       } 

       if (!variableDispenser.Contains("System::SourceID")) 
       { 
        componentEvents.FireError(0, METHOD_NAME, "No System::SourceID variable available. This task can only be used in an Event Handler", "", -1); 
        return DTSExecResult.Failure; 
       } 

       return DTSExecResult.Success; 
      } 
      catch (Exception exc) 
      { 
       componentEvents.FireError(0, METHOD_NAME, "Validation Failed: " + exc.ToString(), "", -1); 
       return DTSExecResult.Failure; 
      } 
     } 

     public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction) 
     { 
      try 
      { 
       string commandText = null; 

       ReadVariables(variableDispenser); 
       //DbConnection connection = connections[_connectionName].AcquireConnection(transaction) as DbConnection; 
       //SqlConnection connection = (SqlConnection)connections[_connectionName].AcquireConnection(transaction); 
       DbCommand command = null; 

       //using (SqlCommand command = new SqlCommand()) 
       if (_connection is SqlConnection) 
       { 
        commandText = @"INSERT INTO SSISLog (EventType, PackageName, TaskName, EventCode, EventDescription, PackageDuration, Host, ExecutionID, EventHandlerDateTime,UID) 
            VALUES (@EventType, @PackageName, @TaskName, @EventCode, @EventDescription, @PackageDuration, @Host, @Executionid, @handlerdatetime,@uid)"; 

        command = new SqlCommand(); 

        command.Parameters.Add(new SqlParameter("@EventType", _eventType)); 
        command.Parameters.Add(new SqlParameter("@PackageName", _packageName)); 
        command.Parameters.Add(new SqlParameter("@TaskName", _taskName)); 
        command.Parameters.Add(new SqlParameter("@EventCode", _errorCode ?? string.Empty)); 
        command.Parameters.Add(new SqlParameter("@EventDescription", _errorDescription ?? string.Empty)); 
        command.Parameters.Add(new SqlParameter("@PackageDuration", _packageDuration)); 
        command.Parameters.Add(new SqlParameter("@Host", _machineName)); 
        command.Parameters.Add(new SqlParameter("@ExecutionID", _executionid)); 
        command.Parameters.Add(new SqlParameter("@handlerdatetime", _handlerdatetime)); 
        command.Parameters.Add(new SqlParameter("@uid", _uid)); 
       } 
       else if (_connection is OleDbConnection) 
       { 
        commandText = @"INSERT INTO SSISLog (EventType,PackageName,TaskName,EventCode,EventDescription,PackageDuration,Host,ExecutionID,EventHandlerDateTime,UID) 
            VALUES (?,?,?,?,?,?,?,?,?,?)"; 

        command = new OleDbCommand(); 

        command.Parameters.Add(new OleDbParameter("@EventType", _eventType)); 
        command.Parameters.Add(new OleDbParameter("@PackageName", _packageName)); 
        command.Parameters.Add(new OleDbParameter("@TaskName", _taskName)); 
        command.Parameters.Add(new OleDbParameter("@EventCode", _errorCode ?? string.Empty)); 
        command.Parameters.Add(new OleDbParameter("@EventDescription", _errorDescription ?? string.Empty)); 
        command.Parameters.Add(new OleDbParameter("@PackageDuration", _packageDuration)); 
        command.Parameters.Add(new OleDbParameter("@Host", _machineName)); 
        command.Parameters.Add(new OleDbParameter("@ExecutionID", _executionid)); 
        command.Parameters.Add(new OleDbParameter("@handlerdatetime", _handlerdatetime)); 
        command.Parameters.Add(new OleDbParameter("@uid", _uid)); 
       } 

       command.CommandText = commandText; 
       command.CommandType = CommandType.Text; 
       command.Connection = _connection; 

       command.ExecuteNonQuery(); 
       _connection.Close(); 
       return DTSExecResult.Success; 

      } 
      catch (Exception exc) 
      { 
       componentEvents.FireError(0, "CustomLoggingTask-Execute", "Task Errored: " + exc.ToString(), "", -1); 
       return DTSExecResult.Failure; 
      } 
     } 

     private void ReadVariables(VariableDispenser variableDispenser) 
     { 
      variableDispenser.LockForRead("System::StartTime"); 
      variableDispenser.LockForRead("System::PackageName"); 
      variableDispenser.LockForRead("System::SourceName"); 
      variableDispenser.LockForRead("System::MachineName"); 
      variableDispenser.LockForRead("System::ExecutionInstanceGUID"); 
      variableDispenser.LockForRead("System::EventHandlerStartTime"); 
      variableDispenser.LockForRead("User::UID"); 
      bool includesError = variableDispenser.Contains("System::ErrorCode"); 
      if (includesError) 
      { 
       variableDispenser.LockForRead("System::ErrorCode"); 
       variableDispenser.LockForRead("System::ErrorDescription"); 
      } 

      Variables vars = null; 
      variableDispenser.GetVariables(ref vars); 

      DateTime startTime = (DateTime)vars["System::StartTime"].Value; 
      _packageDuration = DateTime.Now.Subtract(startTime).TotalSeconds; 
      _packageName = vars["System::PackageName"].Value.ToString(); 
      _taskName = vars["System::SourceName"].Value.ToString(); 
      _machineName = vars["System::MachineName"].Value.ToString(); 
      _executionid = vars["System::ExecutionInstanceGUID"].Value.ToString(); 
      _handlerdatetime = (DateTime)vars["System::EventHandlerStartTime"].Value; 
      _uid = vars["User::UID"].Value.ToString(); 
      if (includesError) 
      { 
       _errorCode = vars["System::ErrorCode"].Value.ToString(); 
       _errorDescription = vars["System::ErrorDescription"].Value.ToString(); 
      } 

      // release the variable locks. 
      vars.Unlock(); 

      // reset the dispenser 
      variableDispenser.Reset(); 
     } 
    } 
} 

, 나는 당신에게 내가 개발, 배포 및 디버깅 사용자 정의 구성 요소에 유용 발견 한 몇 가지 링크를 떠나 (하지만 어쩌면 당신은 이미 겪었있다)!

http://bennyaustin.wordpress.com/2009/06/30/steps-to-build-and-deploy-custom-ssis-components/

http://msdn.microsoft.com/en-us/library/ms403356%28v=sql.105%29.aspx

http://toddmcdermid.blogspot.com.ar/2009/06/converting-your-script-task-into-custom_22.html

건배.

+0

지식을 공유해 주셔서 감사합니다. 나는이 작업을 보니 정말 기뻐요 :) 감사합니다 !!!! – rvphx

+0

나는 그것을 듣게되어 기쁘다! 천만에요! – Chopin

+0

매우 솔직히 말하면, 코드를 변경하는 방법을 알지 못했습니다. 나는 열심히 노력해 보려고 노력했지만 광범위한 C# 지식이 부족하기 때문에 현상금을 게시해야했습니다. 나는 코드를 다시 밟았으며 모든 것이 이제는 훨씬 더 의미가 있습니다! – rvphx

관련 문제