Running SSIS Packages Programmatically, Part 2: Running

Resources:

Now that we’ve got our package loaded, executing it is pretty straightforward, although there is a more parameterized way to do it:

//using Microsoft.SqlServer.Dts.Runtime;
Package pkg;
DTSExecResult pkgResults;
pkgResults = pkg.Execute();

The DTSExecResult enumerable captures a simple Success/Failure/Canceled status (technically, Completion – Success or Failure – is an enum value, but you won’t see it).

And that’s it!

Let’s put it all together:

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

namespace SSIS2012.PackageRuntime
{
    public class PackageExecution
    {
        public void ExecutePackage(
            string destinationDB,
            string destinationServer,
            string pkgFolder,
            string pkgName
            )
        {
            //run SSIS package:
            string pkgLocation = pkgFolder + pkgName + @".dtsx";
            Application app = new Application();
            Package pkg;
            DTSExecResult pkgResults;

            MyEventListener eventListener = new MyEventListener();
            pkg = app.LoadPackage(pkgLocation, eventListener);
            pkgResults = pkg.Execute();

            switch (pkgResults)
            {
                case DTSExecResult.Success:
                    //do something here:
                    break;
                case DTSExecResult.Failure:
                    //do something here:
                    break;
                case DTSExecResult.Canceled:
                    //do something here:
                    break;
                case DTSExecResult.Completion:
                    //do something here:
                    break;
                default:
                    break;
            }
        }
    }

    class MyEventListener : DefaultEvents
    {
        public DtsObject ErrorSource;
        public string ErrorSubcomponent;
        public string ErrorDescription;
        public int ErrorCode;

        public override bool OnError(
            DtsObject source,
            int errorCode,
            string subComponent,
            string description,
            string helpFile,
            int helpContext,
            string idofInterfaceWithError)
        {
            ErrorSource = source;
            ErrorSubcomponent = subComponent;
            ErrorDescription = description;
            ErrorCode = errorCode;

            //Console.WriteLine("Error in {0}/{1} : {2}", source, subComponent, description);
            return false;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *