Posts tonen met het label C#. Alle posts tonen
Posts tonen met het label C#. Alle posts tonen

maandag 17 januari 2011

SSIS : Adding a Derived Column to a SSIS package with C# (Part VI)

In this post i’ll describe the different aspects of developing SSIS components in C# and particularly the Derived Column component. Building packages in C# is a challenging job. Hopefully with help of this post you will be able to overcome most of the difficulties. I already published some posts about programming SSIS with C# (part I, part II, part III, part IV and part V). These were reasonable simple straight packages. In this post I’ll describe building a packages that is a bit more complicated.  In this post we will implement the derived column component in a data flow task. The derived column add or replaces columns in a dataflow task. 


There are certain parts of SSIS components to understand in order to build packages programmatically successful:
  • Type of component (source adapter, destination adapter, transformation adapter).
  • Design time/run time.
  • Virtual/non virtual.


Types of components
There are three types of components: the source adapter, transformation and the destination adapter.  The source adapter retrieves data from a external location and transforms this into a internal buffer format that the pipeline expects. The transformation component accepts buffers of data from the pipeline, does something with it and pushes the data further downstream. The destination adapter accepts buffers and writes this into a external location.

Design time/run time
The design time phase refers to the methods and interfaces that are called when the component is being used in a development sense. In other words, the code that is being run when the component is dragged onto the SSIS design surface, and when it’s being configured.. The run time functionality refers to the calls and interfaces that are being used when the component is actually being executed.

Below there are some typical Design time methods that I’ve been using in my SSIS code projects. 
  • ProvidecomponentProperties. This method is called when a component is first added to a dataflowtask and is used to initialize a component. Components should add their inputs, outputs and customproperties
  • SetComponentProperty. With the setcomponentproperty method it’s possible to set properties of a component
  • SetUsageType. This method deals with the columns on inputs into the component. You can use this to select a column and tells the component how you will treat each column.
  • MapInputColumn. These method is used to create a relationship between input column and MetaDatacolumn. An external metadata column is an offline representation of an output or input column and can be used to downstream components to create an input. I've used this in my destination adapter where a mapping is required.

Virtual/non virtual.
In the code below i'll be using the virtual and the non-virtual columns. As far as i understand now, the virtual columns are what a component could have  and the non virtual (normal) columns are the chosen columns of the component (from the virtualinputs).

The code
I’ve made one assumption in this code and that is I have the same name for the derived column and for the columnname in the database (DerivedColumn). This made it easy for mapping the columns in the destination. If you don’t have the same name then you have to build some custom code here.

Please note that the code is created based on SQL Server 2008 R2,

Add the following references to your project (Project->Add Reference):
  • Microsoft.SqlServer.DTSPipelineWrap.dll
  • Microsoft.SQLServer.DTSRuntimeWrap.dll
  • Microsoft.SQLServer.ManagedDTS.dll
  • Microsoft.SqlServer.PipelineHost.dll
Use this code on top of your script:

using DTS = Microsoft.SqlServer.Dts.Runtime;
using Microsoft.SqlServer.Dts.Pipeline;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
 

These are the steps that needs to be taken for succesfully generating a Derived Column component in a dataflow with C#:
  1. Create a application.
  2. Create a package.
  3. Add a connection for the source adapter to the package.
  4. Add a connection for the destination adapter to the package.
  5. Add a Dataflow task to the package.
  6. Add a source component to the dataflowtask.
  7. Connect the Source connection with the source component.
  8. Add a destination component to the dataflowtask.
  9. Connect the destination connection with the destination component.
  10. Add a Derived column component 
  11. Create the path between the Source and the Derived Column component.
  12. Create the path between the Derived Column and the Destination component.
  13. Add a column to the derived column component.
  14. Setting some properties for the derived column component.
  15. Map the fields in the destination component.
  16. Write the package to a file ( you can also write this to SQL Server).
  17. Dispose the objects. 

1. Create a application.
The first thing you have to create is a new object Application. With an application class it's possible to discover and access package objects. It can also access collections and properties that contain information about the system.  

                 // Create an application
            DTS.Application app = new DTS.Application();


2. Create a package.
After creating  the application object the next step is creating the package object. The package is a collection of other containers, connections, tasks, transformations, variables, configurations, and precedence constraints.

                 // Create a package
            DTS.Package pkg = new DTS.Package();
            //Setting some properties
            pkg.Name = @"MyProgrammedDataflowTaskWithDerivedColumn";


3. Add a connection for the source adapter to the package.
Data comes from a source and it will be pushed downstream to a destination. So a connection to the source is needed and is created with the connectionmanager class. The connectionmanager class provides the information that you must have to connect to a datasource.

            //Adding a connection to the database AdventureWorksLT2008R2
            DTS.ConnectionManager ConnMgrAdvent = pkg.Connections.Add("OLEDB");
            ConnMgrAdvent.ConnectionString = @"Provider=SQLOLEDB.1;" +
                "Integrated Security=SSPI;Initial Catalog=AdventureWorks2008R2;" +
                "Data Source=(local);";
            ConnMgrAdvent.Name = @"AdventureWorks2008R2";
            ConnMgrAdvent.Description = @"SSIS Connection Manager for OLEDB Source
            AdventureWorks2008R2";


4. Add a connection for the destination adapter to the package.
Logically, the destination adapter needs to be created too. This is described in my former post.

           //Adding a connection to the database Import_DB
            DTS.ConnectionManager ConnMgrImport_DB = pkg.Connections.Add("OLEDB");
            ConnMgrImport_DB.ConnectionString = @"Provider=SQLOLEDB.1;" +
                "Integrated Security=SSPI;Initial Catalog=Import_DB;" +
                "Data Source=(local);";
            ConnMgrImport_DB.Name = @"Import_DB";
            ConnMgrImport_DB.Description = @"SSIS Connection Manager for OLEDB Source
            ImportDB";


5. Add a Dataflow task to the package.
The derived column is part of the dataflow and therefore a dataflow task is needed. This is described in my former post.

           //Adding the dataflow task to the package
            DTS.Executable exe = pkg.Executables.Add("STOCK:PipelineTask");
            DTS.TaskHost TKHSQLHost = (DTS.TaskHost)exe;
            TKHSQLHost.Name = "This is a programmed DataFlowTask";
            MainPipe dataFlowTask = (MainPipe)TKHSQLHost.InnerObject;


6. Add a source component to the dataflowtask.
This is described in my former post.

            // Create the source component.
            IDTSComponentMetaData100 source =
                     dataFlowTask.ComponentMetaDataCollection.New();
            source.ComponentClassID = "DTSAdapter.OleDbSource";
            CManagedComponentWrapper srcDesignTime = source.Instantiate();
            srcDesignTime.ProvideComponentProperties();
        


7. Connect the Source connection with the source component.
This is described in my former post.

            // Assign the connection manager.
            if (source.RuntimeConnectionCollection.Count > 0)
            {
                source.RuntimeConnectionCollection[0].ConnectionManager =
                             DTS.DtsConvert.GetExtendedInterface(ConnMgrAdvent);
                source.RuntimeConnectionCollection[0].ConnectionManagerID = 
                             pkg.Connections["AdventureWorks2008R2"].ID;
             }

            // Set the custom properties of the source.
            srcDesignTime.SetComponentProperty("AccessMode", 0);
            srcDesignTime.SetComponentProperty("OpenRowset", "[Production].[Product]");

            // Connect to the data source, and then update the metadata for the source.
            srcDesignTime.AcquireConnections(null);
            srcDesignTime.ReinitializeMetaData();
            srcDesignTime.ReleaseConnections();


8. Add a destination component to the dataflowtask.
This is described in my former post.

             // Create the destination component.
            IDTSComponentMetaData100 destination =
                     dataFlowTask.ComponentMetaDataCollection.New();
            destination.ComponentClassID = "DTSAdapter.OleDbDestination";
            CManagedComponentWrapper destDesignTime = destination.Instantiate();
            destDesignTime.ProvideComponentProperties();


9. Connect the destination connection with the destination component.
This is described in my former post.

                    // Assign the connection manager.
            destination.RuntimeConnectionCollection[0].ConnectionManager =
                      DTS.DtsConvert.GetExtendedInterface(ConnMgrImport_DB);

            if (destination.RuntimeConnectionCollection.Count > 0)
            {
                destination.RuntimeConnectionCollection[0].ConnectionManager =
                           DTS.DtsConvert.GetExtendedInterface(ConnMgrImport_DB);
                destination.RuntimeConnectionCollection[0].ConnectionManagerID =
                           pkg.Connections["Import_DB"].ID;
            }

            // Set the custom properties of the destination
            destDesignTime.SetComponentProperty("AccessMode", 0);
            destDesignTime.SetComponentProperty("OpenRowset", "[dbo].
                            [ProductWithDerivedColumn]");

            // Connect to the data source, and then update the metadata for the source.
            destDesignTime.AcquireConnections(null);
            destDesignTime.ReinitializeMetaData();
            destDesignTime.ReleaseConnections();


10. Add a Derived column component.
This part is new regarding my former post. The code below adds the derived column component to the dataflow task.

           //Derived Column
            IDTSComponentMetaData100 derived =       
                               dataFlowTask.ComponentMetaDataCollection.New();
            derived.Name = "Derived Column Component";
            derived.ComponentClassID = "DTSTransform.DerivedColumn";
            CManagedComponentWrapper DesignDerivedColumns = derived.Instantiate();
            DesignDerivedColumns.ProvideComponentProperties();        //design time

            derived.InputCollection[0].ExternalMetadataColumnCollection.IsUsed = false;
            derived.InputCollection[0].HasSideEffects = false;

            //update the metadata for the derived columns
            DesignDerivedColumns.AcquireConnections(null);
            DesignDerivedColumns.ReinitializeMetaData();
            DesignDerivedColumns.ReleaseConnections();


11. Create the path between the Source and the Derived Column component.
With this code a connection (path) is created between the source component and the derived column component.

           //Create the path from source to derived columns
            IDTSPath100 SourceToDerivedPath = dataFlowTask.PathCollection.New();
            SourceToDerivedPath.AttachPathAndPropagateNotifications(source.OutputCollection[0],
                      derived.InputCollection[0]);


12. Create the path between the Derived Column and the Destination component.
With this code a connection (path) is created between the derived column component and the derived column component.

           //Create the path from derived to desitination
            IDTSPath100 DerivedToDestinationPath = dataFlowTask.PathCollection.New();
            DerivedToDestinationPath.AttachPathAndPropagateNotifications(
                     derived.OutputCollection[0],destination.InputCollection[0]);


13. Add a column to the derived column component.
This code is about adding a column to the derviced column component. I just entered 10 for simplicity but anything is possible, off course.

           IDTSOutputColumn100 myCol =
                      derived.OutputCollection[0].OutputColumnCollection.New();
            myCol.Name = "DerivedColumn";
            myCol.SetDataTypeProperties(
                       Microsoft.SqlServer.Dts.Runtime.Wrapper.DataType.DT_I4, 0, 0, 0, 0);
            myCol.ExternalMetadataColumnID = 0;
            myCol.ErrorRowDisposition = DTSRowDisposition.RD_FailComponent;
            myCol.TruncationRowDisposition = DTSRowDisposition.RD_FailComponent;

            IDTSCustomProperty100 myProp = myCol.CustomPropertyCollection.New();
            myProp.Name = "Expression";
            myProp.Value = "10";

            myProp = myCol.CustomPropertyCollection.New();
            myProp.Name = "FriendlyExpression";
            myProp.Value = "10";


14. Setting some properties for the derived column component.
Setting some properties for the derived column component.

            //Create the input columns for the transformation component
            IDTSInput100 input = derived.InputCollection[0];
            IDTSVirtualInput100 derivedInputVirtual = input.GetVirtualInput();
            input.ErrorRowDisposition = DTSRowDisposition.RD_NotUsed;
            input.ErrorOrTruncationOperation = "";
            DesignDerivedColumns.ReleaseConnections();


15.Map the fields in the destination component.
this code will map the columns in the mapping tab of the destination component. For simplicity i used the same name for the derived column and the database. Therefore it's not needed to manual mapping between the columns and the columns in the table.

            // Get the destination's default input and virtual input.
            IDTSInput100 destinationinput = destination.InputCollection[0];
            int destinationInputID = input.ID;

            IDTSVirtualInput100 vdestinationinput = destinationinput.GetVirtualInput();

            // Iterate through the virtual input column collection.
            foreach (IDTSVirtualInputColumn100 vColumn in
                                vdestinationinput.VirtualInputColumnCollection)
            {
                IDTSInputColumn100 vCol = destDesignTime.SetUsageType(destinationinput.ID,
                           vdestinationinput, vColumn.LineageID, DTSUsageType.UT_READWRITE);
                destDesignTime.MapInputColumn(destinationinput.ID, vCol.ID,
                              destinationinput.ExternalMetadataColumnCollection[vColumn.Name].ID);
            }


16. Write the package to a file ( you can also write this to SQL Server).
This is described in my former post.
          app.SaveToXml(String.Format(@"E:\\SSISProgram\\{0}.dtsx", pkg.Name), pkg, null);

17. Dispose the objects.
This is described in my former post.
.

          pkg.Dispose();

           app = null;
           source = null;
           destination = null;
           srcDesignTime = null;
           destDesignTime = null;

Conclusion
There is a lot of programming needed for implementing a derived column in a dataflow task. The lack of good documentation and tutorials for building packages in C# doesn't help a lot. So far i haven't found a good blog or site explaining this. By learning from snippets, MSDN and trying and trying it will succeed. The error codes (HRESULT) that are generated by the compiler are really terrible and gives very little debug information.

Greetz,

ps. the complete code:

                       // Create an application
            DTS.Application app = new DTS.Application();

            // Create a package
            DTS.Package pkg = new DTS.Package();

            //Setting some properties
            pkg.Name = @"MyProgrammedDataflowTaskWithDerivedColumn";

            //Adding a connection to the database AdventureWorksLT2008R2
            DTS.ConnectionManager ConnMgrAdvent = pkg.Connections.Add("OLEDB");
            ConnMgrAdvent.ConnectionString = @"Provider=SQLOLEDB.1;" +
                "Integrated Security=SSPI;Initial Catalog=AdventureWorks2008R2;" +
                "Data Source=(local);";
            ConnMgrAdvent.Name = @"AdventureWorks2008R2";
            ConnMgrAdvent.Description = @"SSIS Connection Manager for OLEDB Source AdventureWorks2008R2";

            //Adding a connection to the database Import_DB
            DTS.ConnectionManager ConnMgrImport_DB = pkg.Connections.Add("OLEDB");
            ConnMgrImport_DB.ConnectionString = @"Provider=SQLOLEDB.1;" +
                "Integrated Security=SSPI;Initial Catalog=Import_DB;" +
                "Data Source=(local);";
            ConnMgrImport_DB.Name = @"Import_DB";
            ConnMgrImport_DB.Description = @"SSIS Connection Manager for OLEDB Source ImportDB";

            //Adding the dataflow task to the package
            DTS.Executable exe = pkg.Executables.Add("STOCK:PipelineTask");
            DTS.TaskHost TKHSQLHost = (DTS.TaskHost)exe;
            TKHSQLHost.Name = "This is a programmed DataFlowTask";
            MainPipe dataFlowTask = (MainPipe)TKHSQLHost.InnerObject;

            // Create the source component.
            IDTSComponentMetaData100 source =  dataFlowTask.ComponentMetaDataCollection.New();
            source.ComponentClassID = "DTSAdapter.OleDbSource";
            CManagedComponentWrapper srcDesignTime = source.Instantiate();
            srcDesignTime.ProvideComponentProperties();

            // Assign the connection manager.
            if (source.RuntimeConnectionCollection.Count > 0)
            {
                source.RuntimeConnectionCollection[0].ConnectionManager = DTS.DtsConvert.GetExtendedInterface(ConnMgrAdvent);
                source.RuntimeConnectionCollection[0].ConnectionManagerID = pkg.Connections["AdventureWorks2008R2"].ID;
            }

            // Set the custom properties of the source.
            srcDesignTime.SetComponentProperty("AccessMode", 0);
            srcDesignTime.SetComponentProperty("OpenRowset", "[Production].[Product]");

            // Connect to the data source, and then update the metadata for the source.
            srcDesignTime.AcquireConnections(null);
            srcDesignTime.ReinitializeMetaData();
            srcDesignTime.ReleaseConnections();

            // Create the destination component.
            IDTSComponentMetaData100 destination = dataFlowTask.ComponentMetaDataCollection.New();
            destination.ComponentClassID = "DTSAdapter.OleDbDestination";
            CManagedComponentWrapper destDesignTime = destination.Instantiate();
            destDesignTime.ProvideComponentProperties();

            // Assign the connection manager.
            destination.RuntimeConnectionCollection[0].ConnectionManager = DTS.DtsConvert.GetExtendedInterface(ConnMgrImport_DB);

            if (destination.RuntimeConnectionCollection.Count > 0)
            {

                destination.RuntimeConnectionCollection[0].ConnectionManager = DTS.DtsConvert.GetExtendedInterface(ConnMgrImport_DB);
                destination.RuntimeConnectionCollection[0].ConnectionManagerID = pkg.Connections["Import_DB"].ID;

            }

            // Set the custom properties of the destination
            destDesignTime.SetComponentProperty("AccessMode", 0);
            destDesignTime.SetComponentProperty("OpenRowset", "[dbo].[ProductWithDerivedColumn]");

            // Connect to the data source, and then update the metadata for the source.
            destDesignTime.AcquireConnections(null);
            destDesignTime.ReinitializeMetaData();
            destDesignTime.ReleaseConnections();

            //Derived Column
            IDTSComponentMetaData100 derived = dataFlowTask.ComponentMetaDataCollection.New();
            derived.Name = "Derived Column Component";
            derived.ComponentClassID = "DTSTransform.DerivedColumn";
            CManagedComponentWrapper DesignDerivedColumns = derived.Instantiate();
            DesignDerivedColumns.ProvideComponentProperties();        //design time

            derived.InputCollection[0].ExternalMetadataColumnCollection.IsUsed = false;
            derived.InputCollection[0].HasSideEffects = false;

            //update the metadata for the derived columns
            DesignDerivedColumns.AcquireConnections(null);
            DesignDerivedColumns.ReinitializeMetaData();
            DesignDerivedColumns.ReleaseConnections();

            //Create the path from source to derived columns
            IDTSPath100 SourceToDerivedPath = dataFlowTask.PathCollection.New();
            SourceToDerivedPath.AttachPathAndPropagateNotifications(source.OutputCollection[0], derived.InputCollection[0]);

            //Create the path from derived to desitination
            IDTSPath100 DerivedToDestinationPath = dataFlowTask.PathCollection.New();
            DerivedToDestinationPath.AttachPathAndPropagateNotifications(derived.OutputCollection[0], destination.InputCollection[0]);

            //derived.OutputCollection[0].TruncationRowDisposition = DTSRowDisposition.RD_NotUsed;
            //derived.OutputCollection[0].ErrorRowDisposition = DTSRowDisposition.RD_NotUsed;

            IDTSOutputColumn100 myCol = derived.OutputCollection[0].OutputColumnCollection.New();
            myCol.Name = "DerivedColumn";
            myCol.SetDataTypeProperties(Microsoft.SqlServer.Dts.Runtime.Wrapper.DataType.DT_I4, 0, 0, 0, 0);
            myCol.ExternalMetadataColumnID = 0;
            myCol.ErrorRowDisposition = DTSRowDisposition.RD_FailComponent;
            myCol.TruncationRowDisposition = DTSRowDisposition.RD_FailComponent;

            IDTSCustomProperty100 myProp = myCol.CustomPropertyCollection.New();
            myProp.Name = "Expression";
            myProp.Value = "10";

            myProp = myCol.CustomPropertyCollection.New();
            myProp.Name = "FriendlyExpression";
            myProp.Value = "10";

            //Get the output collection
            //IDTSOutput100 outputd = derived.OutputCollection[0];

            //Create the input columns for the transformation component
            IDTSInput100 input = derived.InputCollection[0];
            IDTSVirtualInput100 derivedInputVirtual = input.GetVirtualInput();
            input.ErrorRowDisposition = DTSRowDisposition.RD_NotUsed;
            input.ErrorOrTruncationOperation = "";
            DesignDerivedColumns.ReleaseConnections();

            // Get the destination's default input and virtual input.
            IDTSInput100 destinationinput = destination.InputCollection[0];
            int destinationInputID = input.ID;

            IDTSVirtualInput100 vdestinationinput = destinationinput.GetVirtualInput();

            // Iterate through the virtual input column collection.
            foreach (IDTSVirtualInputColumn100 vColumn in vdestinationinput.VirtualInputColumnCollection)
            {
                IDTSInputColumn100 vCol = destDesignTime.SetUsageType(destinationinput.ID, vdestinationinput, vColumn.LineageID, DTSUsageType.UT_READWRITE);
                destDesignTime.MapInputColumn(destinationinput.ID, vCol.ID, destinationinput.ExternalMetadataColumnCollection[vColumn.Name].ID);
            }

            // Verify that the columns have been added to the input.
            foreach (IDTSInputColumn100 inputColumn in destination.InputCollection[0].InputColumnCollection)
                Console.WriteLine(inputColumn.Name);
            Console.Read();

            app.SaveToXml(String.Format(@"E:\\SSISProgram\\{0}.dtsx", pkg.Name), pkg, null);

            Console.WriteLine("Package  {0} created", pkg.Name);

            pkg.Dispose();

            app = null;
            source = null;
            destination = null;
            srcDesignTime = null;
            destDesignTime = null;


woensdag 5 januari 2011

SSIS : Adding a Dataflow Task to a SSIS package with C# (Part V)

Hi,

This is the fifth post (part I, part II, part III, part IV) about programming SSIS components in C#. In this post i will explain the Data Flow Task. There's very little information available on this subject on the internet. The information that i used for this blog can be found on MSDN and a post on forums of Microsoft(Jessica Elise).

During my research of certain classes, methods and properties of the dataflow task and the dataflowcomponents i came along very interestings sites:
  • I also found some code on BlackDuckKoders.com. 
  • Another interesting blog i found on MSDN is from mmasson. 
  • On the SSISBI.com blog of Duane Douglas there is quite some information available on programming SSIS packages.
  • On SQL Lion i found a example of coding a Lookup transformation. May be there is more information available.
  • Thinker wrote two articles on his blog and an interesting one is about programming the merge join.

This is SSIS package that is generated by the code in this blog:


The OleDB source component will read data from a AdventureWorks2008R2 database with the Data Access mode "Table or View".  I tried the SQL command but i didn't get it properly work (yet). So the data is read from a Production.product table and written in a dbo.Product in a Import_DB database. Below you can see the two editor windows of the generated code.


Okay, what are the steps that needs to be taken when you program a dataflow task in C#. There are 13 steps:
  1. Create a application.
  2. Create a project.
  3. Add a connection for the source adapter to the package.
  4. Add a connection for the destination adapter to the package.
  5. Add a Dataflow task to the package.
  6. Create a source component to the dataflowtask.
  7. Connect the Source connection with the source component.
  8. Create a destination component to the dataflowtask.
  9. Connect the destination connection with the destination component.
  10. Create the path between the Source and the desination component.
  11. Map the fields from the source with the desination.
  12. Write the package to a file ( you can also write this to SQL Server).
  13. Dispose the objects.

In contrast with my former post about programming SSIS packages with C# there are quite a few steps needed before creating a succesful dataflow task in a package. Lets explain the steps in more detail.

Please note that this is created with SQL Server 2008 R2 and that i used an alias for Microsoft.SqlServer.Dts.Runtime

Use this code on top of your script:

using DTS = Microsoft.SqlServer.Dts.Runtime;
using Microsoft.SqlServer.Dts.Pipeline;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;


1. Create a application.
The first thing you have to create is instantiate a new object Application. With an application class it's possible to discover an access package objects. It can also access collections and properties that contain information about the system.

            // Create an application
        DTS.Application app = new DTS.Application(); 


2. Create a project.
After creating  the application object the next step is creating the package object. The package is a collection of other containers, connections, tasks, transformations, variables, configurations, and precedence constraints.

            // Create a package
       DTS.Package pkg = new DTS.Package();

       //Setting some properties
       pkg.Name = @"MyProgrammedDataflowTask";


3. Add a connection for the source adapter to the package.
Data comes from a sources and i transferred to a destination. So a connection to the source is needed and is created with the connectionmanager class. The connectionmanager class provides the information that you must have to connect to a datasource.

           //Adding a connection to the database AdventureWorksLT2008R2
       DTS.ConnectionManager ConnMgrAdvent = pkg.Connections.Add("OLEDB");
       ConnMgrAdvent.ConnectionString = @"Provider=SQLOLEDB.1;" +
                "Integrated Security=SSPI;Initial Catalog=AdventureWorks2008R2;" +
                "Data Source=(local);";
       ConnMgrAdvent.Name = @"AdventureWorks2008R2";
       ConnMgrAdvent.Description = @"SSIS Connection Manager for OLEDB Source
                AdventureWorks2008R2";


4. Add a connection for the destination adapter to the package.
Logically, the destination adapter needs to be created too.

            //Adding a connection to the database Import_DB
        DTS.ConnectionManager ConnMgrImport_DB = pkg.Connections.Add("OLEDB");
        ConnMgrImport_DB.ConnectionString = @"Provider=SQLOLEDB.1;" +
                "Integrated Security=SSPI;Initial Catalog=Import_DB;" +
                "Data Source=(local);";
        ConnMgrImport_DB.Name = @"Import_DB";
        ConnMgrImport_DB.Description = @"SSIS Connection Manager for OLEDB Source
              ImportDB";


5. Add a Dataflow task to the package.
Now it's time to add the dataflow task to the package. This is done by using the Executable class and the executables class. By using the add method of the Executables class it's possible to add a executable (ForEachLoop, Forloop, Package, Sequence and TaskHost). Taskhost is the interesting class in this post. I haven't found an official list on MSDN (?) of the so called STOCK components (maybe here) but i've found a list on SQLIS.com for  2008 (bit strange that SQLIS talks about "DTSAdapter.OleDbSource.2" and my code "DTSAdapter.OleDbSource" (?)).

            //Adding the dataflow task to the package
        DTS.Executable exe = pkg.Executables.Add("STOCK:PipelineTask");
        DTS.TaskHost TKHSQLHost = (DTS.TaskHost)exe;
        TKHSQLHost.Name = "This is a programmed DataFlowTask";
        MainPipe dataFlowTask = (MainPipe)TKHSQLHost.InnerObject;


6. Create a source component to the dataflowtask.
The next thing is building a source component in the dataflowtask. IDTSComponentMetaData100 is an interface and i haven't found any (interesting) information about this on MSDN and google. The CManagedComponentWrapper Interface configures the properties and column collections of a component. The ProvideComponentProperties() is called when a component is first added to the dataflow task to initialize the ComponentMetaData of the component.
 
            // Create the source component.
        IDTSComponentMetaData100 source =  
                        dataFlowTask.ComponentMetaDataCollection.New();
        source.ComponentClassID = "DTSAdapter.OleDbSource";
        CManagedComponentWrapper srcDesignTime = source.Instantiate();
        srcDesignTime.ProvideComponentProperties();


7. Connect the Source connection with the source component.
The next step is connecting the source connection with the  source component. The RuntimeConnectionCollection contains the objects defined by the component. I haven't founf very little information about the GetExtendedInterface. With the SetComponentProperty it's possible to set properties to a IDTSCustomProperty100. AcquireConnections is called during both component design and execution. Components that connect to external data sources should establish their connections during this method. ReinitializeMetaData repairs any errors identified during validation that cause the component to return VS_NEEDSNEWMETADATA at design time. I'm not sure but sometimes when i edit SSIS packages a red error appears and when i open and close the component the error disappears. Perhaps the ReinitializeMetaData is called? The ReleaseConnections method
frees the connections established during AcquireConnections. This can be called at design time and run time.

            // Assign the connection manager.
       if (source.RuntimeConnectionCollection.Count > 0)
       {
          source.RuntimeConnectionCollection[0].ConnectionManager =
                             DTS.DtsConvert.GetExtendedInterface(ConnMgrAdvent);
          source.RuntimeConnectionCollection[0].ConnectionManagerID =
                             pkg.Connections["AdventureWorks2008R2"].ID;
       }
       // Set the custom properties of the source.
       srcDesignTime.SetComponentProperty("AccessMode", 0);
       srcDesignTime.SetComponentProperty("OpenRowset", "[Production].[Product]");

       // Connect to the data source, and then update the metadata for the source.
       srcDesignTime.AcquireConnections(null);
       srcDesignTime.ReinitializeMetaData();
       srcDesignTime.ReleaseConnections();


8. Create a destination component to the dataflowtask.
See 6.

             // Create the destination component.
        IDTSComponentMetaData100 destination =
                   dataFlowTask.ComponentMetaDataCollection.New();
        destination.ComponentClassID = "DTSAdapter.OleDbDestination";
        CManagedComponentWrapper destDesignTime = destination.Instantiate();
        destDesignTime.ProvideComponentProperties();


9. Connect the destination connection with the destination component.
See 7.

          // Create the destination component.
       IDTSComponentMetaData100 destination =
                      dataFlowTask.ComponentMetaDataCollection.New();
       destination.ComponentClassID = "DTSAdapter.OleDbDestination";
       CManagedComponentWrapper destDesignTime = destination.Instantiate();
       destDesignTime.ProvideComponentProperties();

       // Set the custom properties of the destination
       destDesignTime.SetComponentProperty("AccessMode", 0);
       destDesignTime.SetComponentProperty("OpenRowset", "[dbo].[Product]");

       // Connect to the data source, and then update the metadata for the source.
       destDesignTime.AcquireConnections(null);
       destDesignTime.ReinitializeMetaData();
       destDesignTime.ReleaseConnections();



10. Create the path between the source and the desination component.
Okay, now we have created a source component and a destination component. Now it's time to connect the components with each other. First we need to define a path interface. Path objects are created to establish the flow of data between the IDTSOutput100 of an upstream component and the IDTSInput100 of another component. A path contains a single output object represented as the StartPoint, and a single input, which is the EndPoint of the path. A path between two components is established in a two-step process. First, create the path by calling New on the path collection of the IDTSComponentMetaData100 object. Second, establish the path by calling AttachPathAndPropagateNotifications on the path itself. This method establishes the path and notifies the affected components of its existence.

             // Create the path.
        IDTSPath100 path = dataFlowTask.PathCollection.New();
        path.AttachPathAndPropagateNotifications(source.OutputCollection[0],
                                destination.InputCollection[0]);


11. Map the fields from the source with the desination.
The next step is mapping the fields from the source component with destination component.
IDTSInput100 contains the collection of columns that represents the data provided to a component in the form of PipelineBuffer objects at run time. A connection between an IDTSInput100 and an IDTSOutput100 is established through the IDTSPath100 object. IDTSVirtualInput100
represents the columns available to a component from the upstream component. The virtual columns are selected for a component by calling the SetUsageType method of the CManagedComponentWrapperClass.

        // Get the destination's default input and virtual input.
         IDTSInput100 input = destination.InputCollection[0];
         int destinationInputID = input.ID;

         IDTSVirtualInput100 vInput = input.GetVirtualInput();

         // Iterate through the virtual input column collection.
         foreach (IDTSVirtualInputColumn100 vColumn in vInput.VirtualInputColumnCollection)
         {
            IDTSInputColumn100 vCol = destDesignTime.SetUsageType(input.ID, vInput,
                            vColumn.LineageID, DTSUsageType.UT_READWRITE);
            destDesignTime.MapInputColumn(input.ID, vCol.ID,
                            input.ExternalMetadataColumnCollection[vColumn.Name].ID);
         }



12. Write the package to a file ( you can also write this to SQL Server).
The next step is writing the columns to the output window (offcourse this optional) and writing the SSIS package to the file system with SaveToXml.

       // Verify that the columns have been added to the input. 
       foreach (IDTSInputColumn100 inputColumn in    
               destination.InputCollection[0].InputColumnCollection)
           Console.WriteLine(inputColumn.Name);
       Console.Read();

       app.SaveToXml(String.Format(@"E:\\SSISProgram\\{0}.dtsx", pkg.Name), pkg, null);

       Console.WriteLine("Package  {0} created", pkg.Name);


13. Dispose the objects.
Cleaning up the objects and finishing the code.

           pkg.Dispose();
       app = null;
       source = null;
       destination = null;
       srcDesignTime = null;
       destDesignTime = null;



Conclusion
Well, this is quite a job to get this working. There is very litle information and explanations available about programming SSIS packages and especially the dataflow task. 

Greetz,

Hennie


ps. the complete code:



// Create an application
DTS.Application app = new DTS.Application();

// Create a package
DTS.Package pkg = new DTS.Package();

//Setting some properties
pkg.Name = @"MyProgrammedDataflowTask";

//Adding a connection to the database AdventureWorksLT2008R2
DTS.ConnectionManager ConnMgrAdvent = pkg.Connections.Add("OLEDB");
ConnMgrAdvent.ConnectionString = @"Provider=SQLOLEDB.1;" +
    "Integrated Security=SSPI;Initial Catalog=AdventureWorks2008R2;" +
    "Data Source=(local);";
ConnMgrAdvent.Name = @"AdventureWorks2008R2";
ConnMgrAdvent.Description = @"SSIS Connection Manager for OLEDB Source AdventureWorks2008R2";

//Adding a connection to the database Import_DB
DTS.ConnectionManager ConnMgrImport_DB = pkg.Connections.Add("OLEDB");
ConnMgrImport_DB.ConnectionString = @"Provider=SQLOLEDB.1;" +
    "Integrated Security=SSPI;Initial Catalog=Import_DB;" +
    "Data Source=(local);";
ConnMgrImport_DB.Name = @"Import_DB";
ConnMgrImport_DB.Description = @"SSIS Connection Manager for OLEDB Source ImportDB";


//Adding the dataflow task to the package
DTS.Executable exe = pkg.Executables.Add("STOCK:PipelineTask");
DTS.TaskHost TKHSQLHost = (DTS.TaskHost)exe;
TKHSQLHost.Name = "This is a programmed DataFlowTask";
MainPipe dataFlowTask = (MainPipe)TKHSQLHost.InnerObject;

// Create the source component.
IDTSComponentMetaData100 source =
    dataFlowTask.ComponentMetaDataCollection.New();
source.ComponentClassID = "DTSAdapter.OleDbSource";
CManagedComponentWrapper srcDesignTime = source.Instantiate();
srcDesignTime.ProvideComponentProperties();

// Assign the connection manager.
if (source.RuntimeConnectionCollection.Count > 0)
{

    source.RuntimeConnectionCollection[0].ConnectionManager = DTS.DtsConvert.GetExtendedInterface(ConnMgrAdvent);
    source.RuntimeConnectionCollection[0].ConnectionManagerID = pkg.Connections["AdventureWorks2008R2"].ID;

}

// Set the custom properties of the source.
//srcDesignTime.SetComponentProperty("AccessMode", 2);
//srcDesignTime.SetComponentProperty("SqlCommand", "Production.Product");
srcDesignTime.SetComponentProperty("AccessMode", 0);
srcDesignTime.SetComponentProperty("OpenRowset", "[Production].[Product]");

// Connect to the data source, and then update the metadata for the source.
srcDesignTime.AcquireConnections(null);
srcDesignTime.ReinitializeMetaData();
srcDesignTime.ReleaseConnections();

// Create the destination component.
IDTSComponentMetaData100 destination = dataFlowTask.ComponentMetaDataCollection.New();
destination.ComponentClassID = "DTSAdapter.OleDbDestination";
CManagedComponentWrapper destDesignTime = destination.Instantiate();
destDesignTime.ProvideComponentProperties();

// Assign the connection manager.
destination.RuntimeConnectionCollection[0].ConnectionManager = DTS.DtsConvert.GetExtendedInterface(ConnMgrImport_DB);

if (destination.RuntimeConnectionCollection.Count > 0)
{

    destination.RuntimeConnectionCollection[0].ConnectionManager = DTS.DtsConvert.GetExtendedInterface(ConnMgrImport_DB);
    destination.RuntimeConnectionCollection[0].ConnectionManagerID = pkg.Connections["Import_DB"].ID;

}

// Set the custom properties of the destination
destDesignTime.SetComponentProperty("AccessMode", 0);
destDesignTime.SetComponentProperty("OpenRowset", "[dbo].[Product]");

// Connect to the data source, and then update the metadata for the source.
destDesignTime.AcquireConnections(null);
destDesignTime.ReinitializeMetaData();
destDesignTime.ReleaseConnections();


// Create the path.
IDTSPath100 path = dataFlowTask.PathCollection.New();
path.AttachPathAndPropagateNotifications(source.OutputCollection[0], destination.InputCollection[0]);

          

// Get the destination's default input and virtual input.
IDTSInput100 input = destination.InputCollection[0];
int destinationInputID = input.ID;

IDTSVirtualInput100 vInput = input.GetVirtualInput();

// Iterate through the virtual input column collection.
foreach (IDTSVirtualInputColumn100 vColumn in vInput.VirtualInputColumnCollection)
{
    IDTSInputColumn100 vCol = destDesignTime.SetUsageType(input.ID, vInput, vColumn.LineageID, DTSUsageType.UT_READWRITE);
    destDesignTime.MapInputColumn(input.ID, vCol.ID, input.ExternalMetadataColumnCollection[vColumn.Name].ID);
}

// Verify that the columns have been added to the input.
foreach (IDTSInputColumn100 inputColumn in destination.InputCollection[0].InputColumnCollection)
    Console.WriteLine(inputColumn.Name);
Console.Read();

app.SaveToXml(String.Format(@"E:\\SSISProgram\\{0}.dtsx", pkg.Name), pkg, null);

Console.WriteLine("Package  {0} created", pkg.Name);

pkg.Dispose();

app = null;
source = null;
destination = null;
srcDesignTime = null;
destDesignTime = null;

maandag 3 januari 2011

SSIS : Adding a Execute SQL task to SSIS package with C# (Part IV)

This post is the fourth post in a serie (Part I, Part II and Part III) about generating SSIS packages with C#. This post is about generating a SSIS package with a Execute SQL Task. In one of my former posts i already showed how to use early binding constructs. Prerequisite for this is referencing the Microsoft.SqlServer.SQLTask and using this in your C# program. Below is an example a simple C# program with a Execute SQL Task programmed. Don't forget adding this on top of script: using DTS = Microsoft.SqlServer.Dts.Runtime; (i created a Forms application and therefore the application object is referenced twice).

// Create an application
DTS.Application app = new DTS.Application();

// Create a package
DTS.Package pkg = new DTS.Package();

//Setting some properties
pkg.Name = @"MyProgrammedSQLTaskPAckage";

//Adding a connection to the package
DTS.ConnectionManager ConnMgr = pkg.Connections.Add("OLEDB");
ConnMgr.ConnectionString = @"Provider=SQLOLEDB.1;" +
"Integrated Security=SSPI;Initial Catalog=AdventureWorksLT2008R2;" +
"Data Source=(local);";
ConnMgr.Name = @"AdventureWorksLT2008R2";
ConnMgr.Description = @"SSIS Connection Manager for OLEDB Source AdventureWorksLT2008R2";

//adding a "Execute SQL task" to the package
DTS.Executable ExeForSQLTask = pkg.Executables.Add("STOCK:SQLTask");
DTS.TaskHost TKHSQLHost = (DTS.TaskHost)ExeForSQLTask;

TKHSQLHost.Name = "This is a programmed SQL Task";

ExecuteSQLTask MySQLTask = (ExecuteSQLTask)TKHSQLHost.InnerObject;

MySQLTask.Connection = "AdventureWorksLT2008R2";
MySQLTask.SqlStatementSource = "SELECT id FROM sysobjects WHERE name = 'sysrowsets'";
MySQLTask.SqlStatementSourceType = SqlStatementSourceType.DirectInput;
MySQLTask.BypassPrepare = false;

app.SaveToXml(String.Format(@"E:\\SSISProgram\\{0}.dtsx", pkg.Name), pkg, null);

Console.WriteLine("Package {0} created", pkg.Name);

pkg.Dispose(); 



In SSIS the following windows are the result of executing this C# script:


Hennie

vrijdag 31 december 2010

SSIS : ExecuteSQLTask and C# troubles (Part III)

This is the third post (Part I, Part II) in about programming SSIS with C#. It was been a while that i pulled out my hair. Yesterday and today were one of those days. The following post will show you why. I was trying to generate a Execute SQL Task in SSIS from C# and i couldn’t get it work right. The code shown below was the starting point:

DTS.Executable ExeForSQLTask = pkg.Executables.Add("STOCK:SQLTask");
DTS.TaskHost TKHSQLHost = (DTS.TaskHost) ExeForSQLTask;

TKHSQLHost.Name = "This is a programmed SQL Task";

ExecuteSQLTask MySQLTask = (ExecuteSQLTask)TKHSQLHost.InnerObject;


The last step is optional (i call this design time validation) . This uses the ExecuteSQLStep object for adopting the properties and methods of the Execute SQL task. It’s also possible to do something like this:

taskHost.Properties["SqlStatementSource"].SetValue(taskHost, "SELECT * FROM sysobjects");  
 
This is what i would define as "runtime validation" of the properties. So the runtime validation method was my plan B but i didn’t want to give up that soon. I finally managed to get some answers.

First, Someone at the MSDN SSIS forum came up with the idea that i had to add a reference to the right dll for the ExecuteSQLTask. So i did.


Also i had to add the following using command. "using Microsoft.SqlServer.Dts.Tasks.ExecuteSQLTask;" Still i wasn't finished.After this correction the following error occured:

Unable to cast COM object of type 'System.__ComObject' to class type 'Microsoft.SqlServer.Dts.Tasks.ExecuteSQLTask.ExecuteSQLTask'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.

Finally James Beresford on MSDN forums came up with the answer i was looking for. I was using the ‘wrong’ .NET framework (4 instead of 3.5)! So i changed the .NET framework to 3.5 and it worked great! There were some warnings about System.Csharp reference. I removed it (fingers crossed) and the warnings disappeared. 

Hennie

woensdag 29 december 2010

SSIS : Adding a connectionmanager in C# (Part II)

In my former post about generating a package with C#, i discovered the various properties of a simple SSIS package. In this post i’ll add a connection to a package with C#. The following code is needed for this (don't forget adding this on top of script: using DTS = Microsoft.SqlServer.Dts.Runtime;):

// Create an application
DTS.Application app = new DTS.Application();

// Create a package
DTS.Package pkg = new DTS.Package();

//Setting some properties
pkg.Name = "MyProgrammedSQLTaskPAckage";
         
//Adding a connection to the package
DTS.ConnectionManager ConnMgr = pkg.Connections.Add("OLEDB");
ConnMgr.ConnectionString = "Provider=SQLOLEDB.1;" +
    "Integrated Security=SSPI;Initial Catalog=AdventureWorksLT2008R2;" +
    "Data Source=(local);";
ConnMgr.Name = "AdventureWorksLT2008R2";
ConnMgr.Description = "SSIS Connection Manager for OLEDB Source AdventureWorksLT2008R2";

app.SaveToXml(String.Format(@"E:\\SSISProgram\\{0}.dtsx", pkg.Name), pkg, null);
Console.WriteLine("Package  {0} created", pkg.Name);
pkg.Dispose(); 


When i compare the XML schema of the generated SSIS package with the generated SSIS package itself, the following relations can be drawn.


Greetz,
Hennie

maandag 27 december 2010

SSIS : Create a simple SSIS package in C# (Part I)


In this post an example on how to build a SSIS with a piece of C# code.For building SSIS packages in C# you need to install visual studio 2010 for C# and add the following references to your project (Project->Add Reference):
  • Microsoft.SqlServer.DTSPipelineWrap.dll
  • Microsoft.SQLServer.DTSRuntimeWrap.dll
  • Microsoft.SQLServer.ManagedDTS.dll
  • Microsoft.SqlServer.PipelineHost.dll

Now it’s time to write our first C# program generating a SSIS package. In this C# program only the general properties are programmed. The following (simple) properties of SSIS packages can be programmed:
  • VersionComments (“Some Version comments”)
  • CreatorName(“Hennie de Nooijer”)
  • CreatorComputerName(“HenniePC”)
  • CreationDate("01/01/2011")
  • PackageType(DTS.DTSPackageType.DTSDesigner100)
  • ProtectionLevel(DTSProtectionLevel.DontSaveSensitive)
  • MaxConcurrentExecutables(5)
  • PackagePriorityClass(DTSPriorityClass.AboveNormal)
  • VersionMajor(2)
  • VersionMinor(3)
  • VersionBuild(7)
  • VersionGUID(Readonly)
  • EnableConfigurations(false)
  • CheckpointFileName(<packagename>.chkpnt)
  • SaveCheckpoints(true)
  • CheckpointUsage(DTSCheckpointUsage.Always)
  • SuppressConfigurationWarnings(false
  • LastModifiedProductVersion(“”)
  • ForceExecValue(false)
  • ExecValue(“Test”)
  • ForceExecutionResult(DTSForcedExecResult.Completion)
  • Disabled(false)
  • FailPackageOnFailure(“false”)
  • FailParentOnFailure(“true”)
  • MaxErrorCount(2)
  • ISOLevel(“IsolationLevel.Snapshot”)
  • LocaleID(“8201”). English jamaica
  • TransactionOption(“DTS.DTSTransactionOption.Supported”)
  • DelayValidation(“true”)
  • LoggingMode(“DTS.DTSLoggingMode.Disabled”)
  • FilterKind. Has something to do with logging
  • EventFilter. Has something to do with logging.
  • ObjectName("MyProgrammedSSISPackage"). = Name
  • DTSID. UnclearDescription(“This is created with SSIS API”)
  • CreationName (Readonly).
  • DisableEventHandlers (true)
Off course there is more to set but that will shown in future posts on my blogs.  Here is the snippet from my C# code:

// Create an application
DTS.Application app = new DTS.Application();
// Create a package
DTS.Package pkg = new DTS.Package();
//Setting some properties
pkg.VersionComments = "Some Version comments";
pkg.CreatorName = "Hennie de Nooijer";
pkg.CreatorComputerName = "HenniePC";
pkg.CreationDate = DateTime.Parse("01/01/2011");
pkg.PackageType = DTS.DTSPackageType.DTSDesigner100;
pkg.ProtectionLevel = DTS.DTSProtectionLevel.DontSaveSensitive;
pkg.MaxConcurrentExecutables = 5;
pkg.PackagePriorityClass = DTS.DTSPriorityClass.AboveNormal;
pkg.VersionMajor = 2;
pkg.VersionMinor = 3;
pkg.VersionBuild = 7;
//pkg.VersionGUID (is readonly)
pkg.EnableConfigurations = false;
pkg.CheckpointFileName = String.Format(@"E:\\SSISProgram\\{0}.chkpnt", pkg.Name);
pkg.SaveCheckpoints = true;
pkg.CheckpointUsage = DTS.DTSCheckpointUsage.Always;
pkg.SuppressConfigurationWarnings = false;
pkg.ForceExecutionResult = DTS.DTSForcedExecResult.Completion;
pkg.ForceExecutionValue = false;        // without d
pkg.ForcedExecutionValue = "Test";      // with d
pkg.Disable = false;
pkg.FailPackageOnFailure = false;
pkg.FailParentOnFailure = true;
pkg.MaximumErrorCount = 2;
pkg.IsolationLevel = IsolationLevel.Snapshot;
pkg.LocaleID = 8201; //English.Jamaica
pkg.TransactionOption = DTS.DTSTransactionOption.Supported;
pkg.DelayValidation = true;
pkg.LoggingMode = DTS.DTSLoggingMode.Disabled;
pkg.Name = "MyProgrammedSSISPackage";
pkg.Description = "This is created with SSIS API";
pkg.DisableEventHandlers = true;
app.SaveToXml(String.Format(@"E:\\SSISProgram\\{0}.dtsx", pkg.Name), pkg, null);
Console.WriteLine("Package  {0} created", pkg.Name);
pkg.Dispose();

This will create a SSIS package in the SSISprogram folder. When you open this SSIS package the following XML is shown. On the right i’ve shown the properties as available in the generated SSIS package. I’ve drawn red lines to show the relations.


 There are some properties that can't be set with the SSIS API (as far as i know now):
  • PackageFormatVersion.
  • PackageType.
  • VersionGUID.
  • CreationName.

The one i'm unsure about is (These seems properties for the logging. I'll write about them in the future):
  • Loggingmode
  • Filterkind
  • EventFilter

ForceExecutionValueType is set automatically by API.


OffLine mode is greyed out in the properties window.

UpdateObjects is a property that will be removed in a futureversion of SSIS. This is what i found on MSDN : This member will be removed in a future version of MicrosoftSQL Server. Avoid using this member in new development work, and plan to modify applications that currently use this member.
Whether i  set this property or not it will  not be shown in the XML schema of the SSIS package.


Gr,
Hennie