33
Table of Contents Table of Contents Running and Managing Packages Programmatically Understanding the Differences between Local and Remote Execution Loading and Running a Local Package Programmatically Loading and Running a Remote Package Programmatically Loading the Output of a Local Package Enumerating Available Packages Programmatically Managing Packages and Folders Programmatically Managing Running Packages Programmatically Managing Package Roles Programmatically (SSIS Service)

Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

Table of ContentsTable of Contents

Running and Managing Packages Programmatically Understanding the Differences between Local and Remote Execution Loading and Running a Local Package Programmatically Loading and Running a Remote Package Programmatically Loading the Output of a Local Package Enumerating Available Packages Programmatically Managing Packages and Folders Programmatically Managing Running Packages Programmatically Managing Package Roles Programmatically (SSIS Service)

Page 2: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

Running and Managing Packages Programmatically3/24/2017 • 2 min to read • Edit Online

Running Packages on the Integration Services Server

In This Section

If you need manage and run Integration Services packages outside the development environment, you canmanipulate packages programmatically. In this approach, you have a range of options:

Load and run an existing package without modification.

Load an existing package, reconfigure it (for example, for a different data source), and run it.

Create a new package, add and configure components object by object and property by property, save it, andrun it.

You can load and run an existing package from a client application by writing only a few lines of code.

This section describes and demonstrates how to run an existing package programmatically and how toaccess the output of the data flow from other applications. As an advanced programming option, you canprogrammatically create an Integration Services package line by line as described in the topic, BuildingPackages Programmatically.

This section also discusses other administrative tasks that you can perform programmatically to managestored packages, running packages, and package roles.

When you deploy packages to the Integration Services server, you can run the packages programmatically by usingthe Microsoft.SqlServer.Management.IntegrationServices namespace. TheMicrosoft.SqlServer.Management.IntegrationServices assembly is compiled with .NET Framework 3.5. If you arebuilding a .NET Framework 4.0 application, you might need to add the assembly reference directly to your projectfile.

You can also use the namespace to deploy and manage Integration Services projects on the Integration Servicesserver. For an overview of the namespace and code snippets, see the blog entry, A Glimpse of the SSIS CatalogManaged Object Model, on blogs.msdn.com.

Understanding the Differences between Local and Remote ExecutionDiscusses critical differences between executing a package locally or on the server.

Loading and Running a Local Package ProgrammaticallyDescribes how to execute an existing package from a client application on the local computer.

Loading and Running a Remote Package ProgrammaticallyDescribes how to execute an existing package from a client application and to ensure that the package runs on theserver.

Loading the Output of a Local PackageDescribes how to execute a package on the local computer and how to load the data flow output into a clientapplication by using the DataReader destination and the DtsClient namespace.

Enumerating Available Packages ProgrammaticallyDescribes how to discover available packages that are managed by the Integration Services service.

Page 3: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

Reference

Related Sections

See Also

Managing Packages and Folders ProgrammaticallyDescribes how to create, rename, and delete both packages and folders.

Managing Running Packages ProgrammaticallyDescribes how to list packages that are currently running, examine their properties, and stop a running package.

Managing Package Roles Programmatically (SSIS Service)Describes how to get or set information about the roles assigned to a package or a folder.

Integration Services Error and Message ReferenceLists the predefined Integration Services error codes with their symbolic names and descriptions.

Extending Packages with ScriptingDiscusses how to extend the control flow by using the Script task, and how to extend the data flow by using theScript component.

Extending Packages with Custom ObjectsDiscusses how to create program custom tasks, data flow components, and other package objects for use inmultiple packages.

Building Packages ProgrammaticallyDiscusses how to create, configure, and save Integration Services packages programmatically.

SQL Server Integration Services

Page 4: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

Understanding the Differences between Local andRemote Execution3/24/2017 • 1 min to read • Edit Online

See Also

Package developers and administrators should be aware that there are restrictions related to where an IntegrationServices package runs.

A package runs on the same computer as the program that launches it. Even when a program loads apackage that is stored remotely on another server, the package runs on the local computer.

You can only run a package outside the development environment on a computer that hasIntegration Services installed. You cannot run packages outside of SQL Server Data Tools (SSDT) on aclient computer that does not have Integration Services installed, and the terms of your SQL Server licensingmay not permit you to install Integration Services on additional computers. SQL Server Integration Servicesis a server component and is not redistributable to client computers. To run packages from a clientcomputer, you need to launch them in a manner that ensures that the packages run on the server.

For more information about loading and running a saved package, see:

Loading and Running a Local Package Programmatically

Loading and Running a Remote Package Programmatically

For more information about running a package and loading its output into a custom program, see:

Loading the Output of a Local Package

Loading and Running a Local Package ProgrammaticallyLoading and Running a Remote Package ProgrammaticallyLoading the Output of a Local Package

Page 5: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

Loading and Running a Local PackageProgrammatically4/25/2017 • 4 min to read • Edit Online

Loading a Package Programmatically

STORAGE LOCATION METHOD TO CALL

File LoadPackage

SSIS Package Store LoadFromDtsServer

SQL Server LoadFromSqlServer

IMPORTANTIMPORTANT

Running a Package Programmatically

To run a package on the local computer programmaticallyTo run a package on the local computer programmatically

You can run Integration Services packages as needed or at predetermined times by using the methods describedin Running Packages. However, with only a few lines of code, you can also run a package from a customapplication such as a Windows Forms application, a console application, an ASP.NET Web form or Web service, ora Windows service.

This topic discusses:

Loading a package programmatically

Running a package programmatically

All of the methods used in this topic to load and run packages require a reference to theMicrosoft.SqlServer.ManagedDTS assembly. After adding the reference in a new project, import theMicrosoft.SqlServer.Dts.Runtime namespace with a using or Imports statement.

To load a package programmatically on the local computer, whether the package is stored locally or remotely, callone of the following methods:

The methods of the Application class for working with the SSIS Package Store only support ".", localhost, or the server namefor the local server. You cannot use "(local)".

Developing a custom application in managed code that runs a package on the local computer requires thefollowing approach. The steps summarized here are demonstrated in the sample console application that follows.

1. Start the Visual Studio development environment, and create a new application in your preferreddevelopment language. This example uses a console application; however you can also run a package froma Windows Forms application, an ASP.NET Web form or Web service, or a Windows service.

2. On the Project menu, click Add Reference and add a reference toMicrosoft.SqlServer.ManagedDTS.dll. Click OK.

3. Use the Visual Basic Imports statement or the C# using statement to import the

Page 6: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

Sample CodeSample Code

Imports Microsoft.SqlServer.Dts.Runtime

Module Module1

Sub Main()

Dim pkgLocation As String Dim pkg As New Package Dim app As New Application Dim pkgResults As DTSExecResult

pkgLocation = _ "C:\Program Files\Microsoft SQL Server\100\Samples\Integration Services" & _ "\Package Samples\CalculatedColumns Sample\CalculatedColumns\CalculatedColumns.dtsx" pkg = app.LoadPackage(pkgLocation, Nothing) pkgResults = pkg.Execute()

Console.WriteLine(pkgResults.ToString()) Console.ReadKey()

End Sub

End Module

NOTENOTE

Microsoft.SqlServer.Dts.Runtime namespace.

4. Add the following code in the main routine. The completed console application should look like thefollowing example.

The sample code demonstrates loading the package from the file system by using the LoadPackage method.However you can also load the package from the MSDB database by calling the LoadFromSqlServer method, or fromthe Integration Services package store by calling the LoadFromDtsServer method.

5. Run the project. The sample code executes the CalculatedColumns sample package that is installed with theSQL Server samples. The result of package execution is displayed in the console window.

Page 7: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

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

namespace RunFromClientAppCS { class Program { static void Main(string[] args) { string pkgLocation; Package pkg; Application app; DTSExecResult pkgResults;

pkgLocation = @"C:\Program Files\Microsoft SQL Server\100\Samples\Integration Services" + @"\Package Samples\CalculatedColumns Sample\CalculatedColumns\CalculatedColumns.dtsx"; app = new Application(); pkg = app.LoadPackage(pkgLocation, null); pkgResults = pkg.Execute();

Console.WriteLine(pkgResults.ToString()); Console.ReadKey(); } } }

Capturing Events from a Running Package

To run a package on the local computer programmatically and capture package eventsTo run a package on the local computer programmatically and capture package events

Sample CodeSample Code

When you run a package programmatically as shown in the preceding sample, you may also want to captureerrors and other events that occur as the package executes. You can accomplish this by adding a class that inheritsfrom the DefaultEvents class, and by passing a reference to that class when you load the package. Although thefollowing example captures only the OnError event, there are many other events that the DefaultEvents class letsyou capture.

1. Follow the steps in the preceding example to create a project for this example.

2. Add the following code in the main routine. The completed console application should look like thefollowing example.

3. Run the project. The sample code executes the CalculatedColumns sample package that is installed with theSQL Server samples. The result of package execution is displayed in the console window, along with anyerrors that occur.

Page 8: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

Imports Microsoft.SqlServer.Dts.Runtime

Module Module1

Sub Main()

Dim pkgLocation As String Dim pkg As New Package Dim app As New Application Dim pkgResults As DTSExecResult

Dim eventListener As New EventListener()

pkgLocation = _ "C:\Program Files\Microsoft SQL Server\100\Samples\Integration Services" & _ "\Package Samples\CalculatedColumns Sample\CalculatedColumns\CalculatedColumns.dtsx" pkg = app.LoadPackage(pkgLocation, eventListener) pkgResults = pkg.Execute(Nothing, Nothing, eventListener, Nothing, Nothing)

Console.WriteLine(pkgResults.ToString()) Console.ReadKey()

End Sub

End Module

Class EventListener Inherits DefaultEvents

Public Overrides Function OnError(ByVal source As Microsoft.SqlServer.Dts.Runtime.DtsObject, _ ByVal errorCode As Integer, ByVal subComponent As String, ByVal description As String, _ ByVal helpFile As String, ByVal helpContext As Integer, _ ByVal idofInterfaceWithError As String) As Boolean

' Add application–specific diagnostics here. Console.WriteLine("Error in {0}/{1} : {2}", source, subComponent, description) Return False

End Function

End Class

Page 9: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

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

namespace RunFromClientAppWithEventsCS { class MyEventListener : DefaultEvents { public override bool OnError(DtsObject source, int errorCode, string subComponent, string description, string helpFile, int helpContext, string idofInterfaceWithError) { // Add application-specific diagnostics here. Console.WriteLine("Error in {0}/{1} : {2}", source, subComponent, description); return false; } } class Program { static void Main(string[] args) { string pkgLocation; Package pkg; Application app; DTSExecResult pkgResults;

MyEventListener eventListener = new MyEventListener();

pkgLocation = @"C:\Program Files\Microsoft SQL Server\100\Samples\Integration Services" + @"\Package Samples\CalculatedColumns Sample\CalculatedColumns\CalculatedColumns.dtsx"; app = new Application(); pkg = app.LoadPackage(pkgLocation, eventListener); pkgResults = pkg.Execute(null, null, eventListener, null, null);

Console.WriteLine(pkgResults.ToString()); Console.ReadKey(); } } }

See AlsoUnderstanding the Differences between Local and Remote ExecutionLoading and Running a Remote Package ProgrammaticallyLoading the Output of a Local Package

Page 10: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

Loading and Running a Remote PackageProgrammatically3/24/2017 • 10 min to read • Edit Online

NOTENOTE

Running a Remote Package on the Remote Computer

Using SQL Server Agent to Run a Remote Package Programmatically on the ServerUsing SQL Server Agent to Run a Remote Package Programmatically on the Server

NOTENOTE

Sample CodeSample Code

To run remote packages from a local computer that does not have Integration Services installed, start the packagesso that they run on the remote computer on which Integration Services is installed. You do this by having the localcomputer use SQL Server Agent, a Web service, or a remote component to start the packages on the remotecomputer. If you try to start the remote packages directly from the local computer, the packages will load onto andtry to run from the local computer. If the local computer does not have Integration Services installed, the packageswill not run.

You cannot run packages outside SQL Server Data Tools on a client computer that does not have Integration Servicesinstalled, and the terms of your SQL Server licensing might not let you install Integration Services on additional computers.Integration Services is a server component and is not redistributable to client computers.

Alternately, you can run a remote package from a local computer that has Integration Services installed. For moreinformation, see Loading and Running a Local Package Programmatically.

As mentioned above, there are multiple ways in which you can run a remote package on a remote server:

Use SQL Server Agent to run the remote package programmatically

Use a Web service or remote component to run the remote package programmatically

Almost all the methods that are used in this topic to load and save packages require a reference to theMicrosoft.SqlServer.ManagedDTS assembly. The exception is the ADO.NET approach demonstrated inthis topic for executing the sp_start_job stored procedure, which requires only a reference to System.Data.After you add the reference to the Microsoft.SqlServer.ManagedDTS assembly in a new project, importthe Microsoft.SqlServer.Dts.Runtime namespace with a using or Imports statement.

The following code sample demonstrates how to programmatically use SQL Server Agent to run a remote packageon the server. The code sample calls the system stored procedure, sp_start_job, which launches a SQL ServerAgent job. The job that the procedure launches is named RunSSISPackage , and this job is on the remote computer.The RunSSISPackage job then runs the package on the remote computer.

The return value of the sp_start_job stored procedure indicates whether the stored procedure was able to start the SQLServer Agent job successfully. The return value does not indicate whether the package succeeded or failed.

For information on troubleshooting packages that are run from SQL Server Agent jobs, see the Microsoft article,An SSIS package does not run when you call the SSIS package from a SQL Server Agent job step.

Page 11: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

Imports System.Data Imports System.Data.SqlClient

Module Module1

Sub Main()

Dim jobConnection As SqlConnection Dim jobCommand As SqlCommand Dim jobReturnValue As SqlParameter Dim jobParameter As SqlParameter Dim jobResult As Integer

jobConnection = New SqlConnection("Data Source=(local);Initial Catalog=msdb;Integrated Security=SSPI") jobCommand = New SqlCommand("sp_start_job", jobConnection) jobCommand.CommandType = CommandType.StoredProcedure

jobReturnValue = New SqlParameter("@RETURN_VALUE", SqlDbType.Int) jobReturnValue.Direction = ParameterDirection.ReturnValue jobCommand.Parameters.Add(jobReturnValue)

jobParameter = New SqlParameter("@job_name", SqlDbType.VarChar) jobParameter.Direction = ParameterDirection.Input jobCommand.Parameters.Add(jobParameter) jobParameter.Value = "RunSSISPackage"

jobConnection.Open() jobCommand.ExecuteNonQuery() jobResult = DirectCast(jobCommand.Parameters("@RETURN_VALUE").Value, Integer) jobConnection.Close()

Select Case jobResult Case 0 Console.WriteLine("SQL Server Agent job, RunSISSPackage, started successfully.") Case Else Console.WriteLine("SQL Server Agent job, RunSISSPackage, failed to start.") End Select Console.Read()

End Sub

End Module

Page 12: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

using System; using System.Data; using System.Data.SqlClient;

namespace LaunchSSISPackageAgent_CS { class Program { static void Main(string[] args) { SqlConnection jobConnection; SqlCommand jobCommand; SqlParameter jobReturnValue; SqlParameter jobParameter; int jobResult;

jobConnection = new SqlConnection("Data Source=(local);Initial Catalog=msdb;Integrated Security=SSPI"); jobCommand = new SqlCommand("sp_start_job", jobConnection); jobCommand.CommandType = CommandType.StoredProcedure;

jobReturnValue = new SqlParameter("@RETURN_VALUE", SqlDbType.Int); jobReturnValue.Direction = ParameterDirection.ReturnValue; jobCommand.Parameters.Add(jobReturnValue);

jobParameter = new SqlParameter("@job_name", SqlDbType.VarChar); jobParameter.Direction = ParameterDirection.Input; jobCommand.Parameters.Add(jobParameter); jobParameter.Value = "RunSSISPackage";

jobConnection.Open(); jobCommand.ExecuteNonQuery(); jobResult = (Int32)jobCommand.Parameters["@RETURN_VALUE"].Value; jobConnection.Close();

switch (jobResult) { case 0: Console.WriteLine("SQL Server Agent job, RunSISSPackage, started successfully."); break; default: Console.WriteLine("SQL Server Agent job, RunSISSPackage, failed to start."); break; } Console.Read(); } } }

Using a Web Service or Remote Component to Run a Remote Package ProgrammaticallyUsing a Web Service or Remote Component to Run a Remote Package ProgrammaticallyThe previous solution for running packages programmatically on the server does not require any custom code onthe server. However, you may prefer a solution that does not rely on SQL Server Agent to execute packages. Thefollowing example demonstrates a Web service that can be created on the server to start Integration Servicespackages locally, and a test application that can be used to call the Web service from a client computer. If youprefer to create a remote component instead of a Web service, you can use the same code logic with very fewchanges in a remote component. However a remote component may require more extensive configuration than aWeb service.

Page 13: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

IMPORTANTIMPORTANT

IMPORTANTIMPORTANT

Sample CodeSample Code

Creating the Web ServiceCreating the Web Service

To c re a t e a W e b s e rv i c e t o ru n p a c k a g e s o n t h e s e rv e r p ro g ra mma t i c a l l yTo c re a t e a W e b s e rv i c e t o ru n p a c k a g e s o n t h e s e rv e r p ro g ra mma t i c a l l y

Imports System.Web Imports System.Web.Services Imports System.Web.Services.Protocols Imports Microsoft.SqlServer.Dts.Runtime Imports System.IO

<WebService(Namespace:="http://dtsue/")> _ <WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _ <Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Public Class LaunchSSISPackageService Inherits System.Web.Services.WebService

' LaunchPackage Method Parameters: ' 1. sourceType: file, sql, dts ' 2. sourceLocation: file system folder, (none), logical folder ' 3. packageName: for file system, ".dtsx" extension is appended

<WebMethod()> _ Public Function LaunchPackage( _ ByVal sourceType As String, _

With its default settings for authentication and authorization, a Web service generally does not have sufficient permissionsto access SQL Server or the file system to load and execute packages. You may have to assign appropriate permissions tothe Web service by configuring its authentication and authorization settings in the web.config file and assigning databaseand file system permissions as appropriate. A complete discussion of Web, database, and file system permissions is beyondthe scope of this topic.

The methods of the Application class for working with the SSIS Package Store support only ".", localhost, or the server namefor the local server. You cannot use "(local)".

The following code samples show how to create and test the Web service.

An Integration Services package can be loaded directly from a file, directly from SQL Server, or from the SSISPackage Store, which manages package storage in both SQL Server and special file system folders. This samplesupports all the available options by using a Select Case or switch construct to select the appropriate syntax forstarting the package and to concatenate the input arguments appropriately. The LaunchPackage Web servicemethod returns the result of package execution as an integer instead of a DTSExecResult value so that clientcomputers do not require a reference to any Integration Services assemblies.

1. Open Visual Studio and create a Web service project in your preferred programming language. The samplecode uses the name LaunchSSISPackageService for the project.

2. Add a reference to Microsoft.SqlServer.ManagedDTS and add an Imports or using statement to thecode file for the Microsoft.SqlServer.Dts.Runtime namespace.

3. Paste the sample code for the LaunchPackage Web service method into the class. (The sample shows thewhole contents of the code window.)

4. Build and test the Web service by providing a set of valid values for the input arguments of theLaunchPackage method that point to an existing package. For example, if package1.dtsx is stored on theserver in C:\My Packages, pass "file" as the value of the sourceType, "C:\My Packages" as the value ofsourceLocation, and "package1" (without the extension) as the value of packageName.

Page 14: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

ByVal sourceType As String, _ ByVal sourceLocation As String, _ ByVal packageName As String) As Integer 'DTSExecResult

Dim packagePath As String Dim myPackage As Package Dim integrationServices As New Application

' Combine path and file name. packagePath = Path.Combine(sourceLocation, packageName)

Select Case sourceType Case "file" ' Package is stored as a file. ' Add extension if not present. If String.IsNullOrEmpty(Path.GetExtension(packagePath)) Then packagePath = String.Concat(packagePath, ".dtsx") End If If File.Exists(packagePath) Then myPackage = integrationServices.LoadPackage(packagePath, Nothing) Else Throw New ApplicationException( _ "Invalid file location: " & packagePath) End If Case "sql" ' Package is stored in MSDB. ' Combine logical path and package name. If integrationServices.ExistsOnSqlServer(packagePath, ".", String.Empty, String.Empty) Then myPackage = integrationServices.LoadFromSqlServer( _ packageName, "(local)", String.Empty, String.Empty, Nothing) Else Throw New ApplicationException( _ "Invalid package name or location: " & packagePath) End If Case "dts" ' Package is managed by SSIS Package Store. ' Default logical paths are File System and MSDB. If integrationServices.ExistsOnDtsServer(packagePath, ".") Then myPackage = integrationServices.LoadFromDtsServer(packagePath, "localhost", Nothing) Else Throw New ApplicationException( _ "Invalid package name or location: " & packagePath) End If Case Else Throw New ApplicationException( _ "Invalid sourceType argument: valid values are 'file', 'sql', and 'dts'.") End Select

Return myPackage.Execute()

End Function

End Class

using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using Microsoft.SqlServer.Dts.Runtime; using System.IO;

[WebService(Namespace = "http://dtsue/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] public class LaunchSSISPackageServiceCS : System.Web.Services.WebService { public LaunchSSISPackageServiceCS() { }

Page 15: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

}

// LaunchPackage Method Parameters: // 1. sourceType: file, sql, dts // 2. sourceLocation: file system folder, (none), logical folder // 3. packageName: for file system, ".dtsx" extension is appended

[WebMethod] public int LaunchPackage(string sourceType, string sourceLocation, string packageName) {

string packagePath; Package myPackage; Application integrationServices = new Application();

// Combine path and file name. packagePath = Path.Combine(sourceLocation, packageName);

switch(sourceType) { case "file": // Package is stored as a file. // Add extension if not present. if (String.IsNullOrEmpty(Path.GetExtension(packagePath))) { packagePath = String.Concat(packagePath, ".dtsx"); } if (File.Exists(packagePath)) { myPackage = integrationServices.LoadPackage(packagePath, null); } else { throw new ApplicationException("Invalid file location: "+packagePath); } break; case "sql": // Package is stored in MSDB. // Combine logical path and package name. if (integrationServices.ExistsOnSqlServer(packagePath, ".", String.Empty, String.Empty)) { myPackage = integrationServices.LoadFromSqlServer(packageName, "(local)", String.Empty, String.Empty, null); } else { throw new ApplicationException("Invalid package name or location: "+packagePath); } break; case "dts": // Package is managed by SSIS Package Store. // Default logical paths are File System and MSDB. if (integrationServices.ExistsOnDtsServer(packagePath, ".")) { myPackage = integrationServices.LoadFromDtsServer(packagePath, "localhost", null); } else { throw new ApplicationException("Invalid package name or location: "+packagePath); } break; default: throw new ApplicationException("Invalid sourceType argument: valid values are 'file', 'sql', and 'dts'."); }

return (Int32)myPackage.Execute();

}

Page 16: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

}

Testing the Web ServiceTesting the Web Service

To c re a t e a c o n s o l e a p p l i c a t i o n t o t e s t t h e W e b s e rv i c eTo c re a t e a c o n s o l e a p p l i c a t i o n t o t e s t t h e W e b s e rv i c e

Module LaunchSSISPackageTest

Sub Main()

Dim launchPackageService As New LaunchSSISPackageService.LaunchSSISPackageService Dim packageResult As Integer

Try packageResult = launchPackageService.LaunchPackage("sql", String.Empty, "SimpleTestPackage") Catch ex As Exception ' The type of exception returned by a Web service is: ' System.Web.Services.Protocols.SoapException Console.WriteLine("The following exception occurred: " & ex.Message) End Try

Console.WriteLine(CType(packageResult, PackageExecutionResult).ToString) Console.ReadKey()

End Sub

Private Enum PackageExecutionResult PackageSucceeded PackageFailed PackageCompleted PackageWasCancelled End Enum

End Module

The following sample console application uses the Web service to run a package. The LaunchPackage method ofthe Web service returns the result of package execution as an integer instead of a DTSExecResult value so thatclient computers do not require a reference to any Integration Services assemblies. The sample creates a privateenumeration whose values mirror the DTSExecResult values to report the results of execution.

1. In Visual Studio, add a new console application, using your preferred programming language, to the samesolution that contains the Web service project. The sample code uses the name LaunchSSISPackageTest forthe project.

2. Set the new console application as the startup project in the solution.

3. Add a Web reference for the Web service project. If necessary, adjust the variable declaration in the samplecode for the name that you assign to the Web service proxy object.

4. Paste the sample code for the Main routine and the private enumeration into the code. (The sample showsthe whole contents of the code window.)

5. Edit the line of code that calls the LaunchPackage method to provide a set of valid values for the inputarguments that point to an existing package. For example, if package1.dtsx is stored on the server in C:\MyPackages, pass "file" as the value of sourceType , "C:\My Packages" as the value of sourceLocation , and"package1" (without the extension) as the value of packageName .

Page 17: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

using System;

namespace LaunchSSISPackageSvcTestCS { class Program { static void Main(string[] args) { LaunchSSISPackageServiceCS.LaunchSSISPackageServiceCS launchPackageService = new LaunchSSISPackageServiceCS.LaunchSSISPackageServiceCS(); int packageResult = 0;

try { packageResult = launchPackageService.LaunchPackage("sql", String.Empty, "SimpleTestPackage"); } catch (Exception ex) { // The type of exception returned by a Web service is: // System.Web.Services.Protocols.SoapException Console.WriteLine("The following exception occurred: " + ex.Message); }

Console.WriteLine(((PackageExecutionResult)packageResult).ToString()); Console.ReadKey();

}

private enum PackageExecutionResult { PackageSucceeded, PackageFailed, PackageCompleted, PackageWasCancelled };

} }

External Resources

See Also

Video, How to: Automate SSIS Package Execution by Using the SQL Server Agent (SQL Server Video), ontechnet.microsoft.com

Understanding the Differences between Local and Remote ExecutionLoading and Running a Local Package ProgrammaticallyLoading the Output of a Local Package

Page 18: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

Loading the Output of a Local Package3/24/2017 • 9 min to read • Edit Online

NOTENOTE

Description

To load data package output into a client applicationTo load data package output into a client application

Client applications can read the output of Integration Services packages when the output is saved to SQL Serverdestinations by using ADO.NET, or when the output is saved to a flat file destination by using the classes in theSystem.IO namespace. However, a client application can also read the output of a package directly from memory,without the need for an intermediate step to persist the data. The key to this solution is theMicrosoft.SqlServer.Dts.DtsClient namespace, which contains specialized implementations of theIDbConnection, IDbCommand, and IDbDataParameter interfaces from the System.Data namespace. Theassembly Microsoft.SqlServer.Dts.DtsClient.dll is installed by default in %ProgramFiles%\Microsoft SQLServer\100\DTS\Binn.

The procedure described in this topic requires that the DelayValidation property of the Data Flow task and of any parentobjects be set to its default value of False.

This procedure demonstrates how to develop a client application in managed code that loads the output of apackage with a DataReader destination directly from memory. The steps summarized here are demonstrated inthe code sample that follows.

NOTENOTE

1. In the package, configure a DataReader destination to receive the output that you want to read into theclient application. Give the DataReader destination a descriptive name, since you will use this name later inyour client application. Make a note of the name of the DataReader destination.

2. In the development project, set a reference to the Microsoft.SqlServer.Dts.DtsClient namespace bylocating the assembly Microsoft.SqlServer.Dts.DtsClient.dll. By default, this assembly is installed inC:\Program Files\Microsoft SQL Server\100\DTS\Binn. Import the namespace into your code by usingthe C# Using or the Visual Basic Imports statement.

3. In your code, create an object of type DtsClient.DtsConnection with a connection string that contains thecommand-line parameters required by dtexec.exe to run the package. For more information, see dtexecUtility. Then open the connection with this connection string. You can also use the dtexecui utility to createthe required connection string visually.

The sample code demonstrates loading the package from the file system by using the /FILE <path and filename>

syntax. However you can also load the package from the MSDB database by using the /SQL <package name>

syntax, or from the Integration Services package store by using the /DTS \<folder name>\<package name> syntax.

4. Create an object of type DtsClient.DtsCommand that uses the previously created DtsConnection and setits CommandText property to the name of the DataReader destination in the package. Then call theExecuteReader method of the command object to load the package results into a new DataReader.

5. Optionally, you can indirectly parameterize the output of the package by using the collection ofDtsDataParameter objects on the DtsCommand object to pass values to variables defined in the package.

Page 19: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

Example

To create the test packageTo create the test package

command.Parameters.Add(new DtsDataParameter("MyVariable", 1));

IMPORTANTIMPORTANT

Within the package, you can use these variables as query parameters or in expressions to affect the resultsreturned to the DataReader destination. You must define these variables in the package in the DtsClientnamespace before you can use them with the DtsDataParameter object from a client application. (Youmay need to click the Choose Variable Columns toolbar button in the Variables window to display theNamespace column.) In your client code, when you add a DtsDataParameter to the Parameterscollection of the DtsCommand, omit the DtsClient namespace reference from the variable name. Forexample:

6. Call the Read method of the DataReader repeatedly as needed to loop through the rows of output data.Use the data, or save the data for later use, in the client application.

The Read method of this implementation of the DataReader returns true one more time after the last row of datahas been read. This makes it difficult to use the usual code that loops through the DataReader while Read returnstrue. If your code attempts to close the DataReader or the connection after reading the expected number of rows,without an additional, final call to the Read method, the code will raise an unhandled exception. However, if yourcode attempts to read data on this final iteration through a loop, when Read still returns true but the last row hasbeen passed, the code will raise an unhandled ApplicationException with the message, "The SSIS IDataReader ispast the end of the resultset." This behavior is different from that of other DataReader implementations. Therefore,when using a loop to read through the rows in the DataReader while Read returns true, you need to write code tocatch, test, and discard this anticipated ApplicationException on the last successful call to the Read method. Or, ifyou know in advance the number of rows expected, you can process the rows, and then call the Read method onemore time before closing the DataReader and the connection.

7. Call the Dispose method of the DtsCommand object. This is particularly important if you have used anyDtsDataParameter objects.

8. Close the DataReader and the connection objects.

The following example runs a package that calculates a single aggregate value and saves the value to aDataReader destination, and then reads this value from the DataReader and displays the value in a text box on aWindows Form.

The use of parameters is not required when loading the output of a package into a client application. If you do notwant to use a parameter, you can omit the use of the variable in the DtsClient namespace, and omit the code thatuses the DtsDataParameter object.

1. Create a new Integration Services package. The sample code uses "DtsClientWParamPkg.dtsx" as the nameof the package.

2. Add a variable of type String in the DtsClient namespace. The sample code use Country as the name of thevariable. (You may need to click the Choose Variable Columns toolbar button in the Variables window todisplay the Namespace column.)

3. Add an OLE DB connection manager that connects to the AdventureWorks2012 sample database.

4. Add a data flow task to the package and switch to the Data Flow design surface.

5. Add an OLE DB source to the data flow and configure it to use the OLE DB connection manager createdpreviously, and the following SQL command:

Page 20: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

To create the test applicationTo create the test application

Sample CodeSample Code

Imports System.Data Imports Microsoft.SqlServer.Dts.DtsClient

Public Class Form1

Private Sub btnRun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRun.Click

Dim dtexecArgs As String Dim dataReaderName As String Dim countryName As String

Dim dtsConnection As DtsConnection Dim dtsCommand As DtsCommand Dim dtsDataReader As IDataReader Dim dtsParameter As DtsDataParameter

Windows.Forms.Cursor.Current = Cursors.WaitCursor

dtexecArgs = "/FILE ""C:\...\DtsClientWParamPkg.dtsx""" dataReaderName = "DataReaderDest" countryName = "Canada"

dtsConnection = New DtsConnection()

SELECT * FROM Sales.vIndividualCustomer WHERE CountryRegionName = ?

6. Click Parameters and, in the Set Query Parameters dialog box, map the single input parameter in thequery, Parameter0, to the DtsClient::Country variable.

7. Add an Aggregate transformation to the data flow, and connect the output of the OLE DB source to thetransformation. Open the Aggregate Transformation Editor and configure it to peform a "Count all"operation on all input columns (*) and to output the aggregated value with the alias CustomerCount.

8. Add a DataReader destination to the data flow and connect the output of the Aggregate transformation tothe DataReader destination. The sample code uses "DataReaderDest" as the name of the DataReader. Selectthe single available input column, CustomerCount, for the destination.

9. Save the package. The test application created next will run the package and retrieve its output directly frommemory.

1. Create a new Windows Forms application.

2. Add a reference to the Microsoft.SqlServer.Dts.DtsClient namespace by browsing to the assembly of thesame name in %ProgramFiles%\Microsoft SQL Server\100\DTS\Binn.

3. Copy and paste the following sample code into the code module for the form.

4. Modify the value of the dtexecArgs variable as required so that it contains the command-line parametersrequired by dtexec.exe to run the package. The sample code loads the package from the file system.

5. Modify the value of the dataReaderName variable as required so that it contains the name of theDataReader destination in the package.

6. Put a button and a text box on the form. The sample code uses btnRun as the name of the button, andtxtResults as the name of the text box.

7. Run the application and click the button. After a brief pause while the package runs, you should see theaggregate value calculated by the package (the count of customers in Canada) displayed in the text box onthe form.

Page 21: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

dtsConnection = New DtsConnection() With dtsConnection .ConnectionString = dtexecArgs .Open() End With

dtsCommand = New DtsCommand(dtsConnection) dtsCommand.CommandText = dataReaderName

dtsParameter = New DtsDataParameter("Country", DbType.String) dtsParameter.Direction = ParameterDirection.Input dtsCommand.Parameters.Add(dtsParameter)

dtsParameter.Value = countryName

dtsDataReader = dtsCommand.ExecuteReader(CommandBehavior.Default)

With dtsDataReader .Read() txtResults.Text = .GetInt32(0).ToString("N0") End With

'After reaching the end of data rows, ' call the Read method one more time. Try dtsDataReader.Read() Catch ex As Exception MessageBox.Show("Exception on final call to Read method:" & ControlChars.CrLf & _ ex.Message & ControlChars.CrLf & _ ex.InnerException.Message, "Exception on final call to Read method", _ MessageBoxButtons.OK, MessageBoxIcon.Error) End Try

' The following method is a best practice, and is ' required when using DtsDataParameter objects. dtsCommand.Dispose()

Try dtsDataReader.Close() Catch ex As Exception MessageBox.Show("Exception closing DataReader:" & ControlChars.CrLf & _ ex.Message & ControlChars.CrLf & _ ex.InnerException.Message, "Exception closing DataReader", _ MessageBoxButtons.OK, MessageBoxIcon.Error) End Try

Try dtsConnection.Close() Catch ex As Exception MessageBox.Show("Exception closing connection:" & ControlChars.CrLf & _ ex.Message & ControlChars.CrLf & _ ex.InnerException.Message, "Exception closing connection", _ MessageBoxButtons.OK, MessageBoxIcon.Error) End Try

Windows.Forms.Cursor.Current = Cursors.Default

End Sub

End Class

using System; using System.Windows.Forms; using System.Data; using Microsoft.SqlServer.Dts.DtsClient;

namespace DtsClientWParamCS {

Page 22: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

{ public partial class Form1 : Form { public Form1() { InitializeComponent(); this.btnRun.Click += new System.EventHandler(this.btnRun_Click); }

private void btnRun_Click(object sender, EventArgs e) { string dtexecArgs; string dataReaderName; string countryName;

DtsConnection dtsConnection; DtsCommand dtsCommand; IDataReader dtsDataReader; DtsDataParameter dtsParameter;

Cursor.Current = Cursors.WaitCursor;

dtexecArgs = @"/FILE ""C:\...\DtsClientWParamPkg.dtsx"""; dataReaderName = "DataReaderDest"; countryName = "Canada";

dtsConnection = new DtsConnection(); { dtsConnection.ConnectionString = dtexecArgs; dtsConnection.Open(); }

dtsCommand = new DtsCommand(dtsConnection); dtsCommand.CommandText = dataReaderName;

dtsParameter = new DtsDataParameter("Country", DbType.String); dtsParameter.Direction = ParameterDirection.Input; dtsCommand.Parameters.Add(dtsParameter);

dtsParameter.Value = countryName;

dtsDataReader = dtsCommand.ExecuteReader(CommandBehavior.Default);

{ dtsDataReader.Read(); txtResults.Text = dtsDataReader.GetInt32(0).ToString("N0"); }

//After reaching the end of data rows, // call the Read method one more time. try { dtsDataReader.Read(); } catch (Exception ex) { MessageBox.Show( "Exception on final call to Read method:\n" + ex.Message + "\n" + ex.InnerException.Message, "Exception on final call to Read method", MessageBoxButtons.OK, MessageBoxIcon.Error); }

// The following method is a best practice, and is // required when using DtsDataParameter objects. dtsCommand.Dispose();

try { dtsDataReader.Close(); } catch (Exception ex)

Page 23: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

catch (Exception ex) { MessageBox.Show( "Exception closing DataReader:\n" + ex.Message + "\n" + ex.InnerException.Message, "Exception closing DataReader", MessageBoxButtons.OK, MessageBoxIcon.Error); }

try { dtsConnection.Close(); } catch (Exception ex) { MessageBox.Show( "Exception closing connection:\n" + ex.Message + "\n" + ex.InnerException.Message, "Exception closing connection", MessageBoxButtons.OK, MessageBoxIcon.Error); }

Cursor.Current = Cursors.Default;

} } }

See AlsoUnderstanding the Differences between Local and Remote ExecutionLoading and Running a Local Package ProgrammaticallyLoading and Running a Remote Package Programmatically

Page 24: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

Enumerating Available Packages Programmatically3/24/2017 • 2 min to read • Edit Online

Determining Whether a Package or Folder Exists

STORAGE LOCATION METHOD TO CALL

SSIS Package Store ExistsOnDtsServer

SQL Server ExistsOnSqlServer

STORAGE LOCATION METHOD TO CALL

SSIS Package Store FolderExistsOnDtsServer

SQL Server FolderExistsOnSqlServer

Enumerating Available Packages

STORAGE LOCATION METHOD TO CALL

SSIS Package Store GetDtsServerPackageInfos

SQL Server GetPackageInfos

Example (SSIS Package Store)Example (SSIS Package Store)

As you work programmatically with Integration Services packages, you may want to determine whether anindividual package or folder exists, or to enumerate the saved packages that are available to load and execute. TheApplication class of the Microsoft.SqlServer.Dts.Runtime namespace provides a variety of methods to satisfy theserequirements.

To determine programmatically whether a saved package exists, call one of the following methods beforeattempting to load and run it:

To determine programmatically whether a folder exists before attempting to list the packages stored in it, call oneof the following methods:

Back to top

To obtain a list of saved packages programmatically, call one of the following methods:

The following samples are console applications that demonstrate the use of these methods.

Use the GetDtsServerPackageInfos method to list packages stored in the SSIS Package Store. The default storagelocations that are managed by the SSIS Package store are File System and MSDB. You can create additional logicalfolders within these locations.

Page 25: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

Imports Microsoft.SqlServer.Dts.Runtime

Module Module1

Sub Main()

Dim sqlFolder As String Dim sqlServer As String

Dim ssisApplication As Application Dim sqlPackages As PackageInfos Dim sqlPackage As PackageInfo

sqlServer = "."

ssisApplication = New Application()

' Get packages stored in MSDB. sqlFolder = "MSDB" sqlPackages = ssisApplication.GetDtsServerPackageInfos(sqlFolder, sqlServer) If sqlPackages.Count > 0 Then Console.WriteLine("Packages stored in MSDB:") For Each sqlPackage In sqlPackages Console.WriteLine(sqlPackage.Name) Next Console.WriteLine() End If

' Get packages stored in the File System. sqlFolder = "File System" sqlPackages = ssisApplication.GetDtsServerPackageInfos(sqlFolder, sqlServer) If sqlPackages.Count > 0 Then Console.WriteLine("Packages stored in the File System:") For Each sqlPackage In sqlPackages Console.WriteLine(sqlPackage.Name) Next End If

Console.Read()

End Sub

End Module

Page 26: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

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

namespace EnumeratePackagesSSIS_CS { class Program { static void Main(string[] args) {

string sqlFolder; string sqlServer;

Application ssisApplication; PackageInfos sqlPackages;

sqlServer = ".";

ssisApplication = new Application();

// Get packages stored in MSDB. sqlFolder = "MSDB"; sqlPackages = ssisApplication.GetDtsServerPackageInfos(sqlFolder, sqlServer); if (sqlPackages.Count > 0) { Console.WriteLine("Packages stored in MSDB:"); foreach (PackageInfo sqlPackage in sqlPackages) { Console.WriteLine(sqlPackage.Name); } Console.WriteLine(); }

// Get packages stored in the File System. sqlFolder = "File System"; sqlPackages = ssisApplication.GetDtsServerPackageInfos(sqlFolder, sqlServer); if (sqlPackages.Count > 0) { Console.WriteLine("Packages stored in the File System:"); foreach (PackageInfo sqlPackage in sqlPackages) { Console.WriteLine(sqlPackage.Name); } }

Console.Read();

}

}

}

Example (SQL Server)Example (SQL Server)

Back to top

Use the GetPackageInfos method to list Integration Services packages that are stored in an instance of SQL Server.

Page 27: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

Imports Microsoft.SqlServer.Dts.Runtime

Module Module1

Sub Main()

Dim sqlFolder As String Dim sqlServer As String Dim sqlUser As String Dim sqlPassword As String

Dim ssisApplication As Application Dim sqlPackages As PackageInfos Dim sqlPackage As PackageInfo

sqlFolder = String.Empty sqlServer = "(local)" sqlUser = String.Empty sqlPassword = String.Empty

ssisApplication = New Application()

sqlPackages = ssisApplication.GetPackageInfos(sqlFolder, sqlServer, sqlUser, sqlPassword)

For Each sqlPackage In sqlPackages Console.WriteLine(sqlPackage.Name) Next

Console.Read()

End Sub

End Module

Page 28: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

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

namespace EnumeratePackagesSql_CS { class Program { static void Main(string[] args) {

string sqlFolder; string sqlServer; string sqlUser; string sqlPassword;

Application ssisApplication; PackageInfos sqlPackages;

sqlFolder = String.Empty; sqlServer = "(local)"; sqlUser = String.Empty; sqlPassword = String.Empty;

ssisApplication = new Application();

sqlPackages = ssisApplication.GetPackageInfos(sqlFolder, sqlServer, sqlUser, sqlPassword);

foreach (PackageInfo sqlPackage in sqlPackages) { Console.WriteLine(sqlPackage.Name); }

Console.Read();

} } }

See Also

Back to top

Package Management (SSIS Service)

Page 29: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

Managing Packages and Folders Programmatically3/24/2017 • 1 min to read • Edit Online

Determining Whether a Package or Folder Exists

STORAGE LOCATION METHOD TO CALL

SSIS Package Store ExistsOnDtsServer

SQL Server ExistsOnSqlServer

STORAGE LOCATION METHOD TO CALL

SSIS Package Store FolderExistsOnDtsServer

SQL Server FolderExistsOnSqlServer

Managing Packages and Folders

Removing a PackageRemoving a Package

STORAGE LOCATION METHOD TO CALL

SSIS Package Store RemoveFromDtsServer

SQL Server RemoveFromSqlServer

Creating a FolderCreating a Folder

As you work programmatically with Integration Services packages, you may want to determine whether anindividual package or folder exists, or to manage the folders in which packages are stored. The Application class ofthe Microsoft.SqlServer.Dts.Runtime namespace provides a variety of methods to satisfy these requirements.

To determine programmatically whether a saved package exists, call one of the following methods beforeattempting to load and run the package:

To determine programmatically whether a folder exists, call one of the following methods before attempting to listthe packages stored in the folder, :

Back to top

The Application class of the Microsoft.SqlServer.Dts.Runtime namespace provides additional methods formanaging packages and the folders in which they are stored.

To remove a saved package programmatically, call one of the following methods:

Back to top

To create a storage folder programmatically, call one of the following methods:

Page 30: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

STORAGE LOCATION METHOD TO CALL

SSIS Package Store CreateFolderOnDtsServer

SQL Server CreateFolderOnSqlServer

Removing a FolderRemoving a Folder

STORAGE LOCATION METHOD TO CALL

SSIS Package Store RemoveFolderFromDtsServer

SQL Server RemoveFolderFromSqlServer

Renaming a FolderRenaming a Folder

STORAGE LOCATION METHOD TO CALL

SSIS Package Store RenameFolderOnDtsServer

SQL Server RenameFolderOnSqlServer

See Also

Back to top

To remove a storage folder programmatically, call one of the following methods:

Back to top

To rename a storage folder programmatically, call one of the following methods:

Back to top

Package Management (SSIS Service)Enumerating Available Packages Programmatically

Page 31: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

Managing Running Packages Programmatically4/25/2017 • 1 min to read • Edit Online

IMPORTANTIMPORTANT

Determining Which Packages Are Currently Running

NOTENOTE

Working with Running Packages

Getting Information about a Running PackageGetting Information about a Running Package

Stopping a Running PackageStopping a Running Package

As you work programmatically with Integration Services packages, you may want to determine which packages arecurrently running. The Application class of the Microsoft.SqlServer.Dts.Runtime namespace provides methods andclasses to satisfy these requirements.

For more information about monitoring packages, see Package Management (SSIS Service).

All the methods discussed in this topic require a reference to the Microsoft.SqlServer.ManagedDTS assembly.After you add the reference in a new project, import the Microsoft.SqlServer.Dts.Runtime namespace with a usingor Imports statement.

The methods of the Application class for working with the SSIS Package Store support only ".", localhost, or the server namefor the local server. You cannot use "(local)".

To determine which packages are currently running on the specified server, call the GetRunningPackages method.This method returns a RunningPackages collection of RunningPackage objects.

Administrators see all packages that are currently executing on the computer; other users see only those packages that theyhave launched.

After you have determined which packages are currently running, you can retrieve information about the packagesand request that a package be stopped.

As you iterate through the RunningPackages collection, you can use the properties of the RunningPackage object tolocate a package or to obtain additional information about the packages that are running:

ExecutionDuration

ExecutionStartTime

InstanceID

PackageDescription

PackageID

PackageName

UserName

Page 32: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

See Also

You can call the Stop method of a RunningPackage object to request that the package be stopped. There may be adelay between the time that a stop request is issued and the time that the package actually stops.

Package Management (SSIS Service)Enumerating Available Packages Programmatically

Page 33: Table of Contents...You can also use the namespace to deploy and manage Integration Services projects on the Integration Services server. For an overview of the namespace and code

Managing Package Roles Programmatically (SSISService)4/25/2017 • 1 min to read • Edit Online

IMPORTANTIMPORTANT

Determining Which Roles Are Available

Determining Which Roles Are Assigned

See Also

As you work programmatically with Integration Services packages, you may want to determine which roles areavailable to apply to packages, or to determine or set the roles applied to an individual package. The Applicationclass of the Microsoft.SqlServer.Dts.Runtime namespace provides a variety of methods to satisfy theserequirements.

Roles apply only to packages stored in the SQL Server msdb database. For more information about package roles,see Integration Services Roles (SSIS Service).

All the methods discussed in this topic require a reference to the Microsoft.SqlServer.ManagedDTS assembly.After you add the reference in a new project, import the Microsoft.SqlServer.Dts.Runtime namespace by using ausing or Imports statement.

The methods of the Application class for working with the SSIS Package Store support only ".", localhost, or the server namefor the local server. You cannot use "(local)".

To determine which roles are available for the packages stored on a particular server, call the GetDtsServerRolesmethod of the Application class.

To determine which roles have already been assigned to a particular package, call the GetPackageRoles method. Toassign roles to a package, call the SetPackageRoles method.

Integration Services Roles (SSIS Service)