Click here to Skip to main content
Click here to Skip to main content

Execute SQL Server 2005 Integration Services package from C#

By , 25 May 2006
 

Introduction

There are many ways to execute a SQL Server 2005 Integration Services (SSIS) package.  You can use the command line utility DTExec.exe or its window equivalent, DTExecUI.exe. A package can be executed within SQL Server Business Intelligence Studio (Visual Studio) or from a SQL Server Agent Job Step. A package can also be executed from .NET code!

Example SSIS Package

For the purposes of demonstration, I created a simple package that takes some data out of a SQL Server AdventureWorks database and dumps it into a flatfile. The package also has one variable.

Sample screenshot

Sample screenshot

In any kind of "real world" scenario, your package will usually be driven by a configuration file.  An SSIS configuration file is an XML file with a .dtsConfig extension that contains settings you can apply to a package (without actually changing or editing the package). In my example files, you can edit the configuration file with your SQL Server and flat file connection information and run the package. You'll never have to edit the actual package file. Here's a very good tutorial on configuration file syntax. Configurations can also be stored in a SQL Server table, but I won't cover that here.

Let's Start Coding...

You need to add a reference to Microsoft.SQLServer.ManagedDTS.dll. I believe that this DLL is only installed on a machine that has SQL Server components installed. 

Sample screenshot

The amount of code to execute a SSIS package is surprisingly small and concise. Notice that I added a using directive for the Microsoft.SqlServer.Dts.Runtime namespace.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SqlServer.Dts.Runtime;

namespace ExecuteSSIS
{
  class Program
  {
    static void Main(string[] args)
      {
        Application app = new Application();
        //
        // Load package from file system
        //
        Package package = app.LoadPackage("c:\\ExamplePackage.dtsx", null);
        package.ImportConfigurationFile("c:\\ExamplePackage.dtsConfig");
        Variables vars = package.Variables;
        vars["MyVariable"].Value = "value from c#";

        DTSExecResult result = package.Execute();

        Console.WriteLine("Package Execution results: {0}",result.ToString());

        //
        // Load package from SQL Server
        //
        Package package2 = app.LoadFromSqlServer(
            "ExamplePackage","server_name", "sa", "your_password", null);

        package2.ImportConfigurationFile("c:\\ExamplePackage.dtsConfig");
        Variables vars2 = package2.Variables;
        vars2["MyVariable"].Value = "value from c# again";

        DTSExecResult result2 = package2.Execute();

        Console.WriteLine("Package Execution results: {0}", 
             result2.ToString());
     }
  }
 }

First, you create an Application object, which provides access to the DTS (Integration Services) runtime.  Then you use the Application object to load a package from either the file system or from SQL Server, I've demonstrated both. Once you have the package loaded into a Package object, you call the ImportConfigurationFile() method to load and apply the configuration file to the package. The Package object also has a Variables collection that provides access to the package's variable. Finally, to actually execute a package, call the Execute() method.

Conclusion

This article was meant to quickly demonstrate how to load and execute a package. There is much, much more you can do with the managed DTS namespace. There are objects and additional namespaces that allow you to load and inspect packages or even create new packages from .NET code.

History

  • 25th May, 2006: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Jeff Modzel
Web Developer
United States United States
Technical Architect
Sungard HE

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
AnswerRe: Is there a way to catch errors in code, while package fails ?memberilievboyan15-Aug-08 3:38 
Try using something like this...
 
//code from example
...
Package package2 = app.LoadFromSqlServer(
"ExamplePackage","server_name", "sa", "your_password", null);
 
package2.ImportConfigurationFile("c:\\ExamplePackage.dtsConfig");
Variables vars2 = package2.Variables;
vars2["MyVariable"].Value = "value from c# again";
 
DTSExecResult result2 = package2.Execute();
if (result2 == DTSExecResult.Success || result2 == DTSExecResult.Completion)
{
//some Success message here
}
else if (result2 == DTSExecResult.Failure)
{
//some error message + handling here
}
else if (result2 == DTSExecResult.Canceled)
{
//some other message + handling here
}
 
It think it simple enough.
GeneralRe: Is there a way to catch errors in code, while package fails ?memberilievboyan15-Aug-08 3:43 
And also its a good itea to run the whole code in a try {} catch like :
 
try
{
// the code from the sample here
}
catch (Exception ex)
{
Console.WriteLine("Package Error: " + ex.Message);
}
 
For instance
Generala little problemmemberaliagayleon8-Aug-08 10:47 
this code is good, a dont have errors when a execute this program, but it´s dont trasfer data, the project build succeeded, the message in consola is failure.
please give a solution.
 
P.D. the package was save in the integration service
QuestionAnyone have the code to do this in VB?memberREBMCAD10-Jul-08 8:18 
I can run DTS packages from sql server 2000 from VB.net 2002, but I am having trouble running SSIS packages from vb.net 2005.
QuestionIt's very good!But how about the excel files?memberChaney.Wu12-Mar-08 0:25 
If my data source is excel,what can I do?How to give the path to the package?Who can help me,Thank you very much!
GeneralGood articlememberMuaddubby3-Mar-08 6:01 
Simple and to the point!
 
Thx.
 

Generalhelp needed in case of ssis package..membertasumisra11-Dec-07 1:02 
hi all i am working on execution SSIS pacakage from C# the following code i am using but not able to perform the execution
 
Application app = new Application();
Package package = app.LoadPackage("d:\\Main.dtsx", null);
package.ImportConfigurationFile("d:\\Main.dtsConfig");
try
{
DTSExecResult result1 = package.Execute();
}
 
but after completion of the execution it is not giving the desired result ... like result1 is saying failure..
 
can anybody help out me here..
 
Thanks in adavance..
 
vikas da

GeneralRe: help needed in case of ssis package..memberJames_Isisw15-Dec-07 21:56 
maybe your config file has something error?
 
and did you running the dtsx file successed in the vs2005?
 
try to test again pls
 
this is James.

thanks~
QuestionSSiS Problem Urgent!!memberPapai.T10-Oct-07 22:29 
Hi,
My Requirement is given below please solve my problem if u can:
Requirement is to create a table structure called customer books:
1.     Customer-Books has the following columns:
a.     BookName
b.     CustomerName
c.     Price
2.     Populate the table with random data.
3.     Create a BI Model using SQL Server 2005
4.     Choose an algorithm to process the BI Model.  
5.     Have a page with a Book text box and a Submit button.
6.     When the submit button is clicked – the page should display a message – people who bought this book also bought <names of other book>(intelligent search   page reflecting the taste of the reader,just like Amazon.com)
Please solve this problem for me.............regards

 
Thanx & Regards
GeneralRun SSIS package from C# using Windows authenticationmemberAlisterN5-Aug-07 15:38 
Hi...
 
I have found examples of how to run an SSIS package from C#, but they all use SQL Server Authentication. Is it possible to do this using Windows Authentication?
 
TIA
Alister
QuestionExecuting SSIS package always gets failurememberBrillientking3-Jul-07 19:31 
I have a ssis package that transfer data from a flat file to a database.
 
I tryied to executing ssis package in C#.
but the result is always failure and there are no data in database.
 
would you like to point the reason?
AnswerRe: Executing SSIS package always gets failuremembersaom6-Jul-07 11:15 
Yo tenia el mismo problema lo unico que pude hacer fue boton derecho en el paquete y que registre en Log Events y lo direccione a los eventos de Windows ahi se registra todo lo que paso y porque el error.
 
espero te sirva y si consigues otra forma avisame por favor.
 
Hola a todos

QuestionWhat if Configuration is type DTSConfigurationType.SqlServermemberJMB12289-May-07 11:07 
Your solution to Import a configuration file works great. Does anyone know if there is a way to import configuraitons that are of type DTSConfigurationType.SqlServer. My configurations are stored in SQL Server, but I cannot find a way to programmatically load them... Is there an equivalent of ImportConfigurationFile for SQLServer configurations...
 

QuestionError creating applicationmembercibercharlie9-May-07 4:44 
Hi

I am working in an application that should execute SSIS packages, and it works me well when I execute it in a pc with SQL Server installed, but when I run in another pc that doesn't have it, gives me error of COM when it tries to create the instance of the application. Is there a way of avoid this?

Regards
charlie
AnswerRe: Error creating applicationmemberjohn_17266-Aug-09 10:06 
Charlie, you need to run on a machine that has SQL Server installed because only these machines have the required Microsoft.SQLServer.ManagedDTS.dll installed on them.
QuestionWhat about calling a package from ASP.NETmemberFatihSahin19-Dec-06 13:27 
Hello,
 
Executing a package in runtime from .NET Code really helps a lot.
 
But, for example in situations when you want to call a long running package from an ASP.NET page
there is a major problem. You have to wait the package execution to complete for a page post-back!
 
Is there any way to handle this? I mean, you will start the package execution from a web page and forget about it. So the user will not have to wait for a post-back
 
Can we start a job from ASP.NET that executes that package in runtime? Would it be helpful?
 
Any ideas? Any help would be great?
 

 
Fatih Sahin
AnswerRe: What about calling a package from ASP.NETmemberchristhejackal12-Feb-07 5:28 
Build the code into a web service and then call it asynchronously from your ASP application:
 
http://msdn2.microsoft.com/en-us/library/aa480512.aspx
 
Regards,
 
Chris
GeneralRe: What about calling a package from ASP.NETmemberABlokha7718-May-07 1:56 
maybe it is good idea to start another thread and do not use web service?
GeneralOutstanding!memberWbehning6-Nov-06 12:44 
I developed a C# app, that is using Sql Express as a data store.
 
I spent considerable time creating a SSIS package, only to discover that it does not play well with SQL Express, which is one of the requirements for this particular package.
 
This solution works great, and I can incorporate it into the existing C# app and not have to worry about upgrade issues with SQL Express.

GeneralThanks.memberSlackshot16-Oct-06 5:54 
You saved me much headache. Had to incorporate some SSIS packages that a DBA made, into my app, that gathers information across our network. Now I don't have to run them myself. Just make a timer.. and wham.
GeneralThanksmemberFergal Boden7-Sep-06 0:07 
Your code saved me some valuable time - thanks.
General[OLE DB Destination [306]] Error: The AcquireConnection method call to the connection manager failed with error code 0xC0202009.memberBalayc29-Jul-06 1:11 
Can anyone tell why this error occuring.. Iam using SSIS package to dump data from Oracle db to SQL server db. I am getting both (oracle & SQL server) the sides connection string error
 
Thanks in advance
GeneralWrong referencesmembervavigli20-Jul-06 10:38 
To get code from the article running you need:
1) import assembly Microsoft.SqlServer.Dts.Runtime.Wrapper like:
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
2) create instance of specific Microsoft.SqlServer.Dts.Runtime.Wrapper application like:
Microsoft.SqlServer.Dts.Runtime.Wrapper.Application app = new Microsoft.SqlServer.Dts.Runtime.Wrapper.Application();
3) create instance of Package like:
Package package = (Package)app.LoadPackage(@"C:\PackageName.dtsx", true, null);
and so on
 
Val Glivinski
QuestionRun Time Error While Execute SSIS Package from C#(Windows Application)memberdeepumi5-Jun-06 15:31 
Hi
 
I am trying to Execute an SSIS Package from C# Dot Net.
 
Below the code i am using.
 
try
{
Application app = new Application();
Package package = app.LoadPackage("DTSPackage/WinServeMonitoring.dtsx", null);
DTSExecResult result = package.Execute();
label1.Text = "Package Execution " + result.ToString();
 

}
catch (Exception exp)
{
label1.Text = exp.Message.ToString();
}
 
I have added reffrence for DTS Run time (using Microsoft.SqlServer.Dts.Runtime;)
 
But I am getting an Error like this
 
Error 1 'Application' is an ambiguous reference between 'System.Windows.Forms.Application' and 'Microsoft.SqlServer.Dts.Runtime.Application' C:\Documents and Settings\vahqmd10\My Documents\Visual Studio 2005\Projects\WindowsApplication1\WindowsApplication1\Form1.cs 23 17 WindowsApplication1
 

Error 2 'Application' is an ambiguous reference between 'System.Windows.Forms.Application' and 'Microsoft.SqlServer.Dts.Runtime.Application' C:\Documents and Settings\vahqmd10\My Documents\Visual Studio 2005\Projects\WindowsApplication1\WindowsApplication1\Form1.cs 23 39 WindowsApplication1
 

Error 3 The type 'System.Windows.Forms.Application' has no constructors defined C:\Documents and Settings\vahqmd10\My Documents\Visual Studio 2005\Projects\WindowsApplication1\WindowsApplication1\Form1.cs 23 35 WindowsApplication1Can any one Help me !
 

 
Regards
 
Deepu M.I

AnswerRe: Run Time Error While Execute SSIS Package from C#(Windows Application)memberJeff Modzel6-Jun-06 3:58 
The problem is that Application exists as a valid class in multiple namespaces. You can do one of two things.
 
1) Explicitly define the class like:
 
Microsoft.SqlServer.Dts.Runtime.Application app = new Microsoft.SqlServer.Dts.Runtime.Application();
 
or 2) Create a namespace alias like:
 
using DTS = Microsoft.SqlServer.Dts.Runtime;
 
...
 
DTS.Application app = new DTS.Application();
GeneralPassing global variables back to C# from SSISmemberNigel-Findlater30-May-06 20:53 
Nice article,
 
Do you know how to pass paramters from an executed SSIS package directly back to C#?
 
The application I had in mind is to pass back a count of valid rows imported...
 
Nigel...
GeneralRe: Passing global variables back to C# from SSISmemberJeff Modzel31-May-06 2:43 
Nigel,
 
I have never needed to do that although I'm sure it's possible. I'll go check it out and let you know the results.
 
Jeff
AnswerRe: Passing global variables back to C# from SSISmemberJeff Modzel1-Jun-06 7:44 
Nigel,
 
Getting a SSIS variable value back to the calling C# program is pretty simple. All you need to do is check the variable collection after the package.Execute() method. For example, if you had a SSIS package variable called "RowCount", you might do something like:
 
DTSExecResult result = package.Execute();
Variables vars = package.Variables;
int rowcount = Convert.ToInt32(vars["RowCount"].Value);

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 25 May 2006
Article Copyright 2006 by Jeff Modzel
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid