65.9K
CodeProject 正在变化。 阅读更多。
Home

在Microsoft Windows中加载和执行SSIS包

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.56/5 (15投票s)

2010年3月21日

CPOL

7分钟阅读

viewsIcon

92824

downloadIcon

3338

本文介绍了一种在 Microsoft Windows 中加载和执行 SSIS 包的方法,并提供了一个演示 WPF 应用程序。

引言

本文介绍了一种在 Microsoft Windows 中加载和执行 SSIS 包的方法,并提供了一个演示 WPF 应用程序。

背景 

熟悉 SSIS 包的 IT 专业人士会知道,有两种运行 SSIS 包的方法。在 Visual Studio 中开发 SSIS 包时,我们可以在调试模式下运行它。当完成 SSIS 包的开发后,我们可以将其安装到 SQL Server 中并运行。我们可以将 SSIS 包作为任务或计划的 SQL 作业在 SQL Server 中运行。

我们没有 Visual Studio 中的源项目,或者我们没有 SQL Server 来执行现有 SSIS 包的情况也很常见。在这种情况下,拥有一个桌面应用程序允许我们加载和运行包将会很方便。

如果我们查看 .NET Framework 中实现的 "Microsoft.SQLServer.ManagedDTS.dll" 程序集中的 .NET 命名空间 "Microsoft.SqlServer.Dts.Runtime",我们会发现 Microsoft 提供了所有工具来在我们自己的应用程序中加载和执行 SSIS 包。本文旨在介绍一种使用提供的工具在 Windows 应用程序中执行 SSIS 包的方法。"dtexe" 是一个很好的实用工具,但命令行工具并不容易使用。

本文无意演示如何创建和使用 SSIS 包。如果您不熟悉 SSIS 包,这个链接是一个非常好的参考。

本文中的演示 Visual Studio 解决方案是在 Visual Studio 2008 和 SQL Server 2008 中开发的。

Visual Studio 解决方案概述

下图显示了在名为 "SSISWindowsLauncher" 的解决方案资源管理器中组织的三个项目

SolutionExporer.JPG

其中一个项目是 .NET 类库 "SSISWindowsLibrary",它封装了 "Microsoft.SqlServer.Dts.Runtime" 命名空间提供的功能。该库用于在 WPF 项目 "SSISWindowsLauncher" 中加载、执行和报告 SSIS 包的执行状态。为了测试 WPF 应用程序 "SSISWindowsLauncher",我还开发了一个简单的 SSIS 包 "SamplePackage.dtsx",位于 Integration Service 项目 "SampleSSIS" 中。

我将从类库 "SSISWindowsLibrary" 开始,对这些项目进行一些详细的解释。

类库 "SSISWindowsLibrary"

该类库实现了两个类 "DTSPackage" 和 "SSISEventListener"。类 "DTSPackage" 是加载和执行 SSIS 包的主要类,而类 "SSISEventListener" 继承自 "Microsoft.SqlServer.Dts.Runtime" 命名空间中的 "DefaultEvents",为执行 SSIS 包的应用程序提供运行时信息。

以下是类 "DTSPackage" 的实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Dts.Runtime;
 
namespace SSISWindowsLibrary
{
    public enum DTSPackageStatus
    {
        Empty, LoadFailed, Loaded
    };
 
    public class DTSPackage
    {
        private string _PkgLocation;
        private DTSPackageStatus _Status;
        private Package _Pkg;
        private Microsoft.SqlServer.Dts.Runtime.Application _app;
 
        public string PkgLocation
        {
            get { return _PkgLocation; }
        }
 
        public DTSPackageStatus PackageStatus
        {
            get { return _Status; }
        }
 
        public DTSPackage()
        {
            _PkgLocation = null;
            _Status = DTSPackageStatus.Empty;
            _Pkg = null;
            _app = new Microsoft.SqlServer.Dts.Runtime.Application();
        }
 
        private void DisposePackage()
        {
            if (_Pkg != null)
            {
                _Pkg.Dispose();
                _Pkg = null;
            }
        }
 
        public void ClearPackage()
        {
            _PkgLocation = null;
            _Status = DTSPackageStatus.Empty;
            DisposePackage();
        }
 
        public void LoadPackage(string PkgLocation)
        {
            _PkgLocation = PkgLocation;
 
            if (PkgLocation != null)
            {
                DisposePackage();
                try
                {
                    _Pkg = _app.LoadPackage(PkgLocation, null);
                    _Status = DTSPackageStatus.Loaded;
                }
                catch
                {
                    _Status = DTSPackageStatus.LoadFailed;
                }
            }
        }
 
        public void SetPakageConnections(System.Collections.Hashtable ConnectionCollection)
        {
            if (_Status == DTSPackageStatus.Loaded)
            {
                Connections connections = _Pkg.Connections;
                for (int Idex = 0; Idex < connections.Count; Idex++)
                {
                    ConnectionManager connection = connections[Idex];
                    string ConName = connection.Name;
 
                    if (ConnectionCollection.Contains(ConName))
                    {
                        connection.ConnectionString = 
                            ConnectionCollection[ConName].ToString();
                    }
                }
            }
        }
 
        public System.Collections.Hashtable GetPackageConnections()
        {
            System.Collections.Hashtable ConnectionCollection = 
                               new System.Collections.Hashtable();
 
            if (_Status == DTSPackageStatus.Loaded)
            {
                Connections connections = _Pkg.Connections;
                for (int Idex = 0; Idex < connections.Count; Idex++)
                {
                    ConnectionManager connection = connections[Idex];
                    string ConName = connection.Name;
                    string ConStr = connection.ConnectionString;
 
                    ConnectionCollection.Add(ConName, ConStr);
                }
            }
 
            return ConnectionCollection;
        }
 
        public DTSExecResult Execute()
        {
            return _Pkg.Execute();
        }
 
        public DTSExecResult Execute(SSISEventListener Listerner)
        {
            return _Pkg.Execute(null, null, Listerner, null, null);
        }
 
        ~DTSPackage()
        {
            DisposePackage();
        }
    }
}

要加载 SSIS 包,我们可以简单地创建一个 "DTSPackage" 类的对象,并使用 "LoadPackage" 方法,通过提供 "dtsx" 文件的路径来加载包。要执行包,只需调用 "Execute" 方法。

类 "DTSPackage" 还提供了两个方法 "GetPackageConnections" 和 "SetPakageConnections"。这两个方法可用于在包加载到应用程序后查看和更改 SSIS 包中连接的连接字符串。

有两种调用 "Execute" 方法的方式。如果您不关心包执行的细节,可以不带任何参数调用它。如果您想了解细节,可以创建一个 "SSISEventListerner" 对象并将其传递给 "Execute" 方法。在执行完成时,监听器对象可以为我们提供执行的详细信息。

"SSISEventListerner" 类的实现如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Dts.Runtime;
 
namespace SSISWindowsLibrary
{
    public class SSISEventListener : 
                 Microsoft.SqlServer.Dts.Runtime.DefaultEvents
    {
        private System.Data.DataTable _EventLogTable;
        private int _EventCount;
 
        public SSISEventListener()
        {
            _EventCount = 0;
  
            _EventLogTable = new System.Data.DataTable();
            _EventLogTable.Columns.Add("Status", 
                 System.Type.GetType("System.Int16"));
            _EventLogTable.Columns.Add("Event Sequence", 
           	System.Type.GetType("System.Int16"));
            _EventLogTable.Columns.Add("Time", 
                System.Type.GetType("System.DateTime"));
            _EventLogTable.Columns.Add("SSIS Execution Status", 
           	System.Type.GetType("System.String"));
        }
 
        public int EventCount
        {
            get { return _EventCount; }
        }
 
        public System.Data.DataTable EventLogTable
        {
            get { return _EventLogTable; }
        }
 
        public override bool OnError(DtsObject source, int errorCode, 
               string subComponent, string description, string helpFile, 
               int helpContext, string idofInterfaceWithError)
        {
            _EventCount++;
 
            string[] LogData = { "2", _EventCount.ToString(), 
                                 System.DateTime.Now.ToLongTimeString(), 
           	description };
            _EventLogTable.Rows.Add(LogData);
 
            return base.OnError(source, errorCode, subComponent, 
                                description, helpFile, 
                                helpContext, idofInterfaceWithError);
        }
 
        public override void OnInformation(DtsObject source, int informationCode, 
               string subComponent, string description, string helpFile, 
               int helpContext, string idofInterfaceWithError, ref bool fireAgain)
        {
            _EventCount++;
 
            string[] LogData = { "0", _EventCount.ToString(), 
                System.DateTime.Now.ToLongTimeString(), description };
                _EventLogTable.Rows.Add(LogData);
 
            base.OnInformation(source, informationCode, subComponent, 
                               description, helpFile, helpContext, 
           	idofInterfaceWithError, ref fireAgain);
        }
 
        public override void OnWarning(DtsObject source, int warningCode, 
               string subComponent, string description, string helpFile, 
               int helpContext, string idofInterfaceWithError)
        {
            _EventCount++;
 
            string[] LogData = { "1", _EventCount.ToString(), 
                     System.DateTime.Now.ToString(), description };
            _EventLogTable.Rows.Add(LogData);
 
            base.OnWarning(source, warningCode, subComponent, description, helpFile, 
          	helpContext, idofInterfaceWithError);
        }
    }
}

"SSISEventListener" 类继承自 "DefaultEvents" 类。我的实现只保留了部分事件。如果您觉得需要 SSIS 包执行的更多信息,可以更改我的实现并添加其余的事件。

WPF 应用程序 "SSISWindowsLauncher"

WPF 应用程序 "SSISWindowsLauncher" 使用了 Class Library "SSISWindowsLibrary"。用户可以使用此应用程序浏览和加载 SSIS 包,查看包中连接的连接字符串,并可能更改连接字符串,执行 SSIS 包,以及查看执行状态。应用程序的主要功能部分构建在 "WinMain.xaml" 及其代码隐藏 C# 文件中。

"WinMain.xaml" 如下所示

<Window x:Class="SSISWindowsLauncher.WinMain"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:kit="http://schemas.microsoft.com/wpf/2008/toolkit"
    xmlns:WF="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
    Background="#E0E5FF" BorderThickness="1" BorderBrush="AliceBlue"
    Title="SSIS Package Windows Launcher" WindowState="Maximized" 
    FontFamily="Verdana" FontSize="12">
    
    <Grid Margin="10, 10, 10, 10">
        <Grid.RowDefinitions>
            <RowDefinition Height="40"/>
            <RowDefinition Height="155"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="40"/>
        </Grid.RowDefinitions>
        
        <Grid Grid.Row="0" Margin="0, 10, 0, 0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="10" />
                <ColumnDefinition Width="155" />
                <ColumnDefinition Width="10" />
                <ColumnDefinition Width="155" />
            </Grid.ColumnDefinitions>
            
            <Label Grid.Column="0" x:Name="lblPackagePath" 
               Foreground="Blue" Cursor="Hand" 
               FontSize="14" HorizontalAlignment="Right" 
               MouseDown="lblPackagePath_MouseDown">lblPackagePath</Label>
            <Button Grid.Column="2" x:Name="btnLocatePackage" 
               Click="btnLocatePackage_Click">Load SSIS Package</Button>
            <Button Grid.Column="4" x:Name="btnClearPackage" 
               Click="btnClearPackage_Click">Clear Package</Button>
        </Grid>
 
        <WindowsFormsHost Grid.Row="1" 
                 Name="WFHTBConnections" Margin="0, 15, 0, 0">
            <WF:DataGridView x:Name="TBConnections" 
                 BackgroundColor="White" 
                 AutoSizeColumnsMode="AllCells"></WF:DataGridView>
        </WindowsFormsHost>
 
        <WindowsFormsHost Grid.Row="2" 
                Name="WFHTBExecutionLog" Margin="0, 15, 0, 0">
            <WF:DataGridView x:Name="TBExecutionLog" 
                BackgroundColor="White" ReadOnly="True" 
                AutoSizeColumnsMode="AllCells"></WF:DataGridView>
        </WindowsFormsHost>
 
        <Grid Grid.Row="3" Margin="0, 10, 0, 0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*" />
                <ColumnDefinition Width="300" />
                <ColumnDefinition Width="10" />
                <ColumnDefinition Width="180" />
                <ColumnDefinition Width="10" />
                <ColumnDefinition Width="180" />
            </Grid.ColumnDefinitions>
 
            <Button Grid.Column="1" x:Name="btnLaunchSSIS" 
               Click="btnLaunchSSIS_Click">Execute SSIS Package</Button>
            <Button Grid.Column="3" x:Name="btnClearExecutionLog" 
               Click="btnClearExecutionLog_Click">Clear SSIS Execution Log</Button>
            <Button Grid.Column="5" x:Name="btnClose" 
                Click="btnClose_Click">Close</Button>
        </Grid>
        
    </Grid>
</Window>

此 "XAML" 文件的代码隐藏文件如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using SSISWindowsLibrary;
using Microsoft.SqlServer.Dts.Runtime;
 
namespace SSISWindowsLauncher
{
    /// <summary>
    /// Interaction logic for WinMain.xaml
    /// </summary>
    public partial class WinMain : Window
    {
        private DTSPackage Pkg;
 
        public WinMain()
        {
            InitializeComponent();
 
            TBConnections.ColumnHeadersHeight = 30;
            TBConnections.ColumnHeadersDefaultCellStyle.BackColor = 
                          System.Drawing.Color.SeaShell;
            TBConnections.ColumnHeadersDefaultCellStyle.Font = 
                          new System.Drawing.Font("Verdana", 8, 
          	System.Drawing.FontStyle.Bold);
            TBConnections.CellBeginEdit += 
                 new System.Windows.Forms.DataGridViewCellCancelEventHandler(
                 TBConnections_CellBeginEdit);
            TBConnections.CellEndEdit += 
               new System.Windows.Forms.DataGridViewCellEventHandler(
               TBConnections_CellEndEdit);
 
            TBExecutionLog.ColumnHeadersHeight = 30;
            TBExecutionLog.ColumnHeadersDefaultCellStyle.BackColor = 
                           System.Drawing.Color.SeaShell;
            TBExecutionLog.DefaultCellStyle.WrapMode = 
                           System.Windows.Forms.DataGridViewTriState.True;
            TBExecutionLog.AutoSizeColumnsMode = 
          	System.Windows.Forms.DataGridViewAutoSizeColumnsMode.DisplayedCells;
            TBExecutionLog.ColumnHeadersDefaultCellStyle.Font = 
          	new System.Drawing.Font("Verdana", 8, System.Drawing.FontStyle.Bold);
            TBExecutionLog.RowsAdded += 
                new System.Windows.Forms.DataGridViewRowsAddedEventHandler(
                TBExecutionLog_RowsAdded);
 
            this.WindowStyle = WindowStyle.ThreeDBorderWindow;
            Pkg = new DTSPackage();
            UpdatelblPackagePath();
        }
 
        private void TBConnections_CellBeginEdit(object sender, 
          System.Windows.Forms.DataGridViewCellCancelEventArgs e)
        {
            System.Windows.Forms.DataGridViewCell Cell = 
          TBConnections.Rows[e.RowIndex].Cells[e.ColumnIndex];
            Cell.Style.Font = new System.Drawing.Font("Verdana", 8, 
          System.Drawing.FontStyle.Italic|System.Drawing.FontStyle.Bold);
        }
 
        private void TBConnections_CellEndEdit(object sender, 
          System.Windows.Forms.DataGridViewCellEventArgs e)
        {
            System.Windows.Forms.DataGridViewCell Cell = 
          TBConnections.Rows[e.RowIndex].Cells[e.ColumnIndex];
            Cell.Style.Font = new System.Drawing.Font("Verdana", 8, 
          System.Drawing.FontStyle.Regular);
        }
 
        private void TBExecutionLog_RowsAdded(Object sender, 
          System.Windows.Forms.DataGridViewRowsAddedEventArgs e)
        {
            if (TBExecutionLog.DataSource == null)
            {
                return;
            }
 
            foreach (System.Windows.Forms.DataGridViewRow Row in TBExecutionLog.Rows)
            {
                string ResultCode = Row.Cells[0].Value.ToString();
 
                System.Drawing.Color TextColor;
                if (ResultCode == "0")
                {
                    TextColor = System.Drawing.Color.Green;
                }
                else if (ResultCode == "1")
                {
                    TextColor = System.Drawing.Color.DarkOrange;
                }
                else
                {
                    TextColor = System.Drawing.Color.Red;
                }
 
                foreach (System.Windows.Forms.DataGridViewCell Cell in Row.Cells)
                {
                    Cell.Style.ForeColor = TextColor;
                }
            }
        }
 
        private void UpdatelblPackagePath()
        {
            string PkgLocation = Pkg.PkgLocation;
 
            if (PkgLocation == null)
            {
                lblPackagePath.Content = "Please select the SSIS Package to run";
            }
            else {
                lblPackagePath.Content = "SSIS Package to run: " + PkgLocation;
            }
        }
 
        private void btnLaunchSSIS_Click(object sender, RoutedEventArgs e)
        {
            SSISEventListener Listerner = new SSISEventListener();
 
            string PkgLocation = Pkg.PkgLocation;
            if (PkgLocation == null)
            {
                MessageBox.Show("Please locate the SSIS Package to run");
                return;
            }
 
            System.IO.FileInfo file = new System.IO.FileInfo(PkgLocation);
            if (!file.Exists)
            {
                MessageBox.Show("The package file does not exist, 
           	please make sure you have the SSIS package file in the right place.");
                return;
            }
 
            if (Pkg.PackageStatus != DTSPackageStatus.Loaded)
            {
                MessageBox.Show("The package file is not loaded successfully. 
           	Please check if the package file is a valid one.");
                return;
            }
 
            btnClearExecutionLog_Click(null, null);
            DispatcherHelper.DoEvents();
 
            System.Data.DataView aView = (System.Data.DataView) TBConnections.DataSource;
            System.Collections.Hashtable aHashTable = new System.Collections.Hashtable();
 
            for (int Idex = 0; Idex < aView.Count; Idex++)
            {
                aHashTable.Add(aView[Idex][0], aView[Idex][1]);
            }
 
            Pkg.SetPakageConnections(aHashTable);
 
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
            DTSExecResult PkgResult = Pkg.Execute(Listerner);
            System.Windows.Forms.Cursor.Current = null;
 
            int ResultCode = 0;
            if (PkgResult.ToString() != "Success")
            {
                ResultCode = 3;
            }
 
            int EventCount = Listerner.EventCount;
 
            string[] LogData = new string[4];
            LogData[0] = ResultCode.ToString();
            LogData[1] = (EventCount + 1).ToString();
            LogData[2] = System.DateTime.Now.ToLongTimeString();
            LogData[3] = PkgResult.ToString();
            Listerner.EventLogTable.Rows.Add(LogData);
 
            System.Data.DataView EventLogTableView = Listerner.EventLogTable.DefaultView;
            EventLogTableView.AllowNew = false;
            EventLogTableView.AllowDelete = false;
            EventLogTableView.AllowEdit = false;
 
            TBExecutionLog.DataSource = EventLogTableView;
            TBExecutionLog.Columns[0].Visible = false;
            TBExecutionLog.Columns[2].DefaultCellStyle.Format = 
                                      "MM/dd/yyyy hh:mm:ss tt";
 
        }
 
        private void btnLocatePackage_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".txt";
            dlg.Filter = "SSIS Package (.dtsx)|*.dtsx";
 
            string PkgLocation = null;
            Nullable<bool> result = dlg.ShowDialog();
            if (result != true)
            {
                return;
            }
 
            PkgLocation = dlg.FileName;
 
            try
            {
                Pkg.LoadPackage(PkgLocation);
            }
            catch (System.Exception EX)
            {
                MessageBox.Show("The is a problem to load the SSIS package, 
           	please make sure that it is a valid SSIS package file - " + 
           	System.DateTime.Now.ToString() + ".\n\n" + EX.ToString());
                btnClearPackage_Click(null, null);
                UpdatelblPackagePath();
                return;
            }
 
            if (Pkg.PackageStatus != DTSPackageStatus.Loaded) {
                MessageBox.Show("There is a problem to load the package. 
           	Please make sure the SSIS package is valid.");
                btnClearPackage_Click(null, null);
                UpdatelblPackagePath();
            }
 
            System.Collections.Hashtable PackageConnections = Pkg.GetPackageConnections();
            System.Data.DataTable PackageConnectionsTable = new System.Data.DataTable();
            PackageConnectionsTable.Columns.Add("SSIS Connection Name", 
          	System.Type.GetType("System.String"));
            PackageConnectionsTable.Columns.Add("Connection String", 
          	System.Type.GetType("System.String"));
 
            foreach (System.Collections.DictionaryEntry DE in PackageConnections)
            {
                string[] RowData = { (string)DE.Key, (string)DE.Value };
                PackageConnectionsTable.Rows.Add(RowData);
            }
 
            PackageConnectionsTable.Columns[0].ReadOnly = true;
            System.Data.DataView PackageConnectionTableView = 
          	PackageConnectionsTable.DefaultView;
            PackageConnectionTableView.AllowDelete = false;
            PackageConnectionTableView.AllowNew = false;
            TBConnections.DataSource = PackageConnectionTableView;
            TBExecutionLog.DataSource = null;
 
            UpdatelblPackagePath();
        }
 
        private void btnClearPackage_Click(object sender, RoutedEventArgs e)
        {
            Pkg.ClearPackage();
            UpdatelblPackagePath();
            TBConnections.DataSource = null;
            TBExecutionLog.DataSource = null;
        }
 
        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }
 
        private void lblPackagePath_MouseDown(object sender, MouseButtonEventArgs e)
        {
            btnLocatePackage_Click(null, null);
        }
 
        private void btnClearExecutionLog_Click(object sender, RoutedEventArgs e)
        {
            TBExecutionLog.DataSource = null;
        }
    }
}

SSIS 包

为了测试 WPF 应用程序,我创建了一个简单的 SSIS 包。我选择 SQL Server 2008 作为我的测试平台来构建 SSIS 包。在我构建 SSIS 包之前,我运行以下 SQL 查询来创建两个表 [SSISExperiment] 和 [SSISExperimentTarget],并向 [SSISExperiment] 表中插入一些数据。

-- Setup the tables needed for the SSIS package "SampleSSIS"
-- Create two tables [SSISExperiment] and [SSISExperimentTarget]
-- Insert some data into the table [SSISExperiment]
 
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = 
            OBJECT_ID(N'[dbo].[SSISExperiment]') AND type in (N'U'))
DROP TABLE [dbo].[SSISExperiment]
 
CREATE TABLE [dbo].[SSISExperiment](
 [ID] [int] NOT NULL,
 [Name] [varchar](50) NOT NULL,
 [Time] [datetime] NOT NULL
) ON [PRIMARY]
 
INSERT INTO [SSISExperiment] VALUES(1, 'Name 1', GETDATE())
INSERT INTO [SSISExperiment] VALUES(2, 'Name 2', GETDATE())
INSERT INTO [SSISExperiment] VALUES(3, 'Name 3', GETDATE())
INSERT INTO [SSISExperiment] VALUES(4, 'Name 4', GETDATE())
 
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = 
            OBJECT_ID(N'[dbo].[SSISExperimentTarget]') AND type in (N'U'))
DROP TABLE [dbo].[SSISExperimentTarget]
 
CREATE TABLE [dbo].[SSISExperimentTarget](
 [ID] [int] NOT NULL,
 [Name] [varchar](50) NOT NULL,
 [Time] [datetime] NOT NULL
) ON [PRIMARY]
 
GO

示例 SSIS 包会将数据从 [SSISExperiment] 传输到 [SSISExperimentTarget]。下图显示了 SSIS 包的数据流映射。

DataFlowMapping.jpg

运行应用程序

编译整个 Visual Studio 解决方案,包括类库、WPF 应用程序和 SSIS 包。然后,我们可以通过调试模式或双击编译后的 EXE 来启动 WPF 应用程序 "SSISWindowsLauncher"。之后,我们可以点击 WPF 应用程序上的 "Load SSIS Package" 按钮,浏览到 "SampleSSIS" 项目的 "bin" 文件夹,并选择我们刚刚创建的 "SamplePackage.dtsx" 文件。

BrowseSSIS.jpg

点击 "Open" 按钮,我们就可以加载 SSIS 包了。

LoadSSIS.jpg

SSIS 包成功加载后,应用程序会显示 SSIS 包中使用的连接的连接字符串。在我们的 "SamplePackage.dtsx" 中,只有一个连接。如果您点击连接字符串文本,您会发现应用程序允许您更改连接字符串。在这个简单的测试中,我不做任何连接字符串的更改。但是,如果您多花点时间玩弄这个 WPF 应用程序,您可能会发现它在支持加载和执行 SSIS 包方面还有其他一些不错的功能。

RunSSIS.jpg

点击 "Execute SSIS Package" 按钮;应用程序将开始执行已加载的 SSIS 包。应用程序会显示执行过程中一些重要步骤的状态。在这种情况下,SSIS 包已成功执行。

现在我们可以去 SQL Server 查看 [SSISExperimentTarget] 表,数据确实已成功传输。

RunSSISResult.jpg

关注点

  • 本文介绍了一种在 Microsoft Windows 应用程序中加载和执行 SSIS 包的方法。本文附带的示例 WPF 应用程序与商业级软件应用程序相去甚远。但它几乎具备了在 Microsoft Windows 中加载和执行 SSIS 包的所有基本功能。如果愿意,可以按原样使用它,或对其进行任何更改以更好地满足您的需求。
  • 如果您想自己编译和测试此应用程序,并且想使用我的示例 SSIS 包,您将需要 SQL Server,并且需要对其拥有必要的权限。就我而言,我是我的 SQL Server 的服务器管理员。您需要在运行 SSIS 包之前运行本文附带的 SQL 脚本,并且需要更改 "SamplePackage.dtsx" 中连接 "Experiment" 中的服务器名称和数据库名称。如果您熟悉数据库连接字符串,您可能会在 "SSISWindowsLauncher" 应用程序中加载 SSIS 包后更改 SQL Server 名称和数据库名称。
  • 在 WPF 应用程序中,您可能会注意到我使用了两个 "WindowsFormsHost" 容器来将两个为 Windows Forms 应用程序设计的 "DataGridView" 控件插入到 WPF 应用程序中。这仅仅是个人偏好问题,因为我喜欢"老派"控件中显示的字体。WPF 应用程序无论如何都需要 .NET Framework 才能运行,因此在 WPF 应用程序中混合 Windows Forms 控件不应该造成部署和维护问题。
  • 我用这个应用程序测试了很多 SSIS 包,并注意到 SSIS 包不会进行延迟评估。这意味着所有执行步骤都会在包执行开始之前独立评估。虽然这是一种安全的方法,但它限制了开发人员创建更强大的 SSIS 包。
  • 另一件事要提醒读者的是,您可能会注意到我可以查看 SSIS 包中所有连接的整个连接字符串,包括用户名和密码。因此,最好使用集成身份验证而不是 SQL Server 身份验证,除非您能找到一种好的方法来加密您的用户名和密码。
  • 本文随附的应用程序肯定还有很大的改进空间,特别是 "SSISEventListener" 类。如果您想要更详细的 SSIS 执行信息,并且希望信息是实时的,您可以创建自己的监听器并适当地使用它。
  • 通过查看本文随附的应用程序,您将对 SSIS 包有更好的了解,并更好地理解 SSIS "技术"。

历史

这是本文的第一个修订版。

© . All rights reserved.