SSIS 2012 Script Task to Get File Properties

Hello,
I researched on how to grab a file properties such as file size, file modified date, etc and I came across the following
link:
I followed exact steps and when I went to execute the package, I got the following error:
Below is the code:
// C# code
// Fill SSIS variables with file properties
using System;
using System.Data;
using System.IO; // Added to get file properties
using System.Security.Principal; // Added to get file owner
using System.Security.AccessControl; // Added to get file owner
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
namespace ST_cb8dd466d98149fcb2e3852ead6b6a09.csproj
[System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
#region VSTA generated code
enum ScriptResults
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
#endregion
public void Main()
// Lock SSIS variables
Dts.VariableDispenser.LockForRead("User::FilePath");
Dts.VariableDispenser.LockForWrite("User::FileAttributes");
Dts.VariableDispenser.LockForWrite("User::FileCreationDate");
Dts.VariableDispenser.LockForWrite("User::FileExists");
Dts.VariableDispenser.LockForWrite("User::FileInUse");
Dts.VariableDispenser.LockForWrite("User::FileIsReadOnly");
Dts.VariableDispenser.LockForWrite("User::FileLastAccessedDate");
Dts.VariableDispenser.LockForWrite("User::FileLastModifiedDate");
Dts.VariableDispenser.LockForWrite("User::FileOwner");
Dts.VariableDispenser.LockForWrite("User::FileSize");
// Create a variables 'container' to store variables
Variables vars = null;
// Add variables from the VariableDispenser to the variables 'container'
Dts.VariableDispenser.GetVariables(ref vars);
// Variable for file information
FileInfo fileInfo;
// Fill fileInfo variable with file information
fileInfo = new FileInfo(vars["User::FilePath"].Value.ToString());
// Check if file exists
vars["User::FileExists"].Value = fileInfo.Exists;
// Get the rest of the file properties if the file exists
if (fileInfo.Exists)
// Get file creation date
vars["User::FileCreationDate"].Value = fileInfo.CreationTime;
// Get last modified date
vars["User::FileLastModifiedDate"].Value = fileInfo.LastWriteTime;
// Get last accessed date
vars["User::FileLastAccessedDate"].Value = fileInfo.LastAccessTime;
// Get size of the file in bytes
vars["User::FileSize"].Value = fileInfo.Length;
// Get file attributes
vars["User::FileAttributes"].Value = fileInfo.Attributes.ToString();
vars["User::FileIsReadOnly"].Value = fileInfo.IsReadOnly;
// Check if the file isn't locked by an other process
try
// Try to open the file. If it succeeds, set variable to false and close stream
FileStream fs = new FileStream(vars["User::FilePath"].Value.ToString(), FileMode.Open);
vars["User::FileInUse"].Value = false;
fs.Close();
catch (Exception ex)
// If opening fails, it's probably locked by an other process
vars["User::FileInUse"].Value = true;
// Log actual error to SSIS to be sure
Dts.Events.FireWarning(0, "Get File Properties", ex.Message, string.Empty, 0);
// Get the Windows domain user name of the file owner
FileSecurity fileSecurity = fileInfo.GetAccessControl();
IdentityReference identityReference = fileSecurity.GetOwner(typeof(NTAccount));
vars["User::FileOwner"].Value = identityReference.Value;
// Release the locks
vars.Unlock();
Dts.TaskResult = (int)ScriptResults.Success;
Eventually I am looking to just grab the Modified Date from the Windows Explorer folder and insert into table. Any suggestions? Thank you in advance!
Sanjeev
Sanjeev Jha

Hi SSISJoost,
I am so glad you responded to this thread. You are absolutely right. I copied the entire code including the project name (guid) and that solved the error problem.
Now, what did you do to get the message box? I added the watch and I could see the values but how do I get these values in a table? If I remember correctly, in your blog, you mentioned something about using derived columns. I am familiar with Derived Columns
but how do I do that? I appreciate your response.
Thank you.
Sanjeev
Sanjeev Jha
I used a second script task to show all variable values. It has a
MessageBox in it and between all
variables I added a
newline to make it more readable...
But with an Execute SQL Task and parameters you can also put these values in a Table... or you can read the file in a Data Flow Task and add those variables (as metadata) to each record with a Derived Column
Please mark the post as answered if it answers your question | My SSIS Blog:
http://microsoft-ssis.blogspot.com |
Twitter

Similar Messages

  • SSIS 2012 Script Task Debugging not working (VSTA Popup but no script displayed in IDE)

    Hi,
    I am trying to debug 2012 SSIS Package but for some reason its not working. Basically when I run package (64bit mode) it pop up Script IDE but never brings up Script (see below). Usually when debugging of script starts it should break execution at the code.
    Anybody experienced this issue with SSIS 2012 ?
    Thanks,
    Nayan
    Visit My Blog (Home of BI Articles) 

    Hi,
    I am trying to debug 2012 SSIS Package but for some reason its not working. Basically when I run package (64bit mode) it pop up Script IDE but never brings up Script (see below). Usually when debugging of script starts it should break execution at the code.
    Anyone has clue whats going on here?
    Thanks,
    Nayan
    My Blog |
    Convert DTS to SSIS |
    Document SSIS |
    SSIS Tasks |
    Real-time SSIS Monitoring

  • Error in script task "The name 'file' does not exist in the current context"

    I am new to the c# scripting and SSIS come from PHP and Foxpro.
    I am using SSIS with a script task and I am getting am errror "The name 'file' does not exist in the current context" in the following code in the picture below: (See
    Why does the object named "file" go away after the first refrence to it?? How do I make it avaliable for the whole script??
         public void Main()
            String cFileInfo = null;
            DateTime dFTPFileDateTime;
       bool fireAgain = true;
                List<IRemoteFileInfo> fileList = (List<IRemoteFileInfo>)Dts.Variables["SFTPResult"].Value;
                foreach (IRemoteFileInfo file in fileList)
                    cFileInfo = file.Name + "|" +file.ModifiedTime +"|"+ file.Size;
                Dts.Events.FireInformation(1, "Name ", cFileInfo, "", 0, ref fireAgain);
                dFTPFileDateTime =
    file.ModifiedTime;
    << This is where the error is occuring. 
                Dts.TaskResult = (int)ScriptResults.Success;

    I think you forgot { and } after the loop... Or is that deliberately?
    Please mark the post as answered if it answers your question | My SSIS Blog:
    http://microsoft-ssis.blogspot.com |
    Twitter

  • Service to ssis to script task invocation errors

    Hi.  We run 2012 std and were under the impression that if we gac'd our .dll which is called by our pkg's script task, that plumbing a c# .net service to the pkg wouldn't fail in the pkg script taks with the generic "
    Exception has been thrown by the target of an invocation" error.
    The service calls the pkg.  The script task references the strongly named .dll which is gac'd.
    I'm getting the impression that having the script task do anything other than dts namespace related and c# generic commands will fail with that error.  Not just calls to our method.  As an experiment I threw a generic script task into the pkg prior
    to the first script task and tested with and without just a message box command in that script task prior to Dts.TaskResult being set .   I'm not sure if that was a good way to prove my suspicions or not but my c# knowledge is limited.
    I'll go thru the exercise of uninstalling , removing refs, un gac ing, rebuilding .dll, re gac ing, adding refs back, etc etc but have a bad feeling that my results will be the same.  My peers believe that a call to a gac'd .dll from a script task (all
    initiated by a .net service) should work and not get this .net "state" exception where I believe .net is trying to save us from ourselves when it detects an attempt to execute things in an "external" run/name space.. 
    I have verified that my params are being passed correctly to the pkg from the service and mapping to the proper variables.   Those params are used in the .dll call and there were no problems running the pkg stand alone and executing the same script
    task and gac'd .dll with the default variables values. 

    it looks like using this Parse method also works in the "sql environment" when the pkg is run standalone.  I mean without a .net service calling it.
    I looked at the documentation on this method and don't see anything about it being especially useful when switching between environs (sql vs .net).  So it isn't clear to me why MS made both the explicit cast (eg int) and Parse (eg int.Parse) available
    to its customers and allowed (int) to act on ssis var objects like int.Parse when running pkgs standalone.  But not when a service calls the pkg.  And especially in light of the fact that it is c# that is used to code script tasks.
    But I'm happy to have gotten past this and now need to make sure the same approach will be useful when setting one ssis var = to another.

  • SQL 2008 R2 - SSIS C# Script Task - Not Setting Variable

    OK... I am stumped.  I am trying to set the variable "User::TicketDB_Get_SQL" from a Script Task since it is dynamic... and well it isn't working :(
    I can see I am supposed to be setting the value, but when I do breaks and watch that variable the new value is not being set.  Here is my C# code... Can someone look and see what the heck I might be doing wrong:
    Microsoft SQL Server Integration Services Script Task
    Write scripts using Microsoft Visual C# 2008.
    The ScriptMain is the entry point class of the script.
    using System;
    using System.IO;
    using System.Data;
    using Microsoft.SqlServer.Dts.Runtime;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    using System.Text.RegularExpressions;
    namespace ST_3542610d50a64788be84926d15e07f7b.csproj
    [System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]
    public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    #region VSTA generated code
    enum ScriptResults
    Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
    Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
    #endregion
    public void Main()
    //MessageBox.Show("Start VB");
    //MessageBox.Show("Make ADO Connection");
    SqlConnection sqlConn = new SqlConnection();
    sqlConn = (SqlConnection)(Dts.Connections["ADO-DW-SSIS_Processing"].AcquireConnection(Dts.Transaction) as SqlConnection);
    SqlConnection sqlTicketDBRowsConn = new SqlConnection();
    sqlTicketDBRowsConn = (SqlConnection)(Dts.Connections["ADO-DW-SSIS_Processing"].AcquireConnection(Dts.Transaction) as SqlConnection);
    //MessageBox.Show("Connected to ADO");
    String newSelectSQL = null;
    //bool fireAgain = false;
    Variables vars = null;
    try
    Dts.VariableDispenser.LockForRead("User::Data_Warehouse_Max_Modified_Date");
    Dts.VariableDispenser.LockForRead("User::Data_Warehouse_Prod_Table");
    Dts.VariableDispenser.LockForRead("User::Modified_Date_Field");
    Dts.VariableDispenser.LockForRead("User::TicketDB_Schema");
    Dts.VariableDispenser.LockForRead("User::Table_Name");
    Dts.VariableDispenser.LockForRead("User::Unique_ID_Field");
    Dts.VariableDispenser.LockForRead("User::Data_Warehouse_Process_Table_Name");
    Dts.VariableDispenser.LockForRead("User::Data_Warehouse_DB_Name");
    Dts.VariableDispenser.LockForWrite("User::TicketDB_Get_SQL");
    Dts.VariableDispenser.LockForWrite("User::Reprocess_Records");
    Dts.VariableDispenser.GetVariables(ref vars);
    //Dts.VariableDispenser.GetVariables(ref glvars);
    String maxModDate = vars["User::Data_Warehouse_Max_Modified_Date"].Value.ToString();
    String prodtable = vars["User::Data_Warehouse_Prod_Table"].Value.ToString();
    String modField = vars["User::Modified_Date_Field"].Value.ToString();
    String TicketDBSchema = vars["User::TicketDB_Schema"].Value.ToString();
    String tablename = vars["User::Table_Name"].Value.ToString();
    String uniqIDField = vars["User::Unique_ID_Field"].Value.ToString();
    String procTable = vars["User::Data_Warehouse_Process_Table_Name"].Value.ToString();
    String custName = vars["User::Data_Warehouse_DB_Name"].Value.ToString();
    String Reprocess = "F";
    String ReprocessDate = "0";
    String ReprocessPrime = null;
    String ReprocessVal = null;
    Int16 count = 0;
    #region Get List of Rows for TicketDB Query
    String TicketDBRows = null;
    String sqlTicketDBRowsQuery = "SELECT [TicketDB_Column_Name] " +
    "FROM " + procTable + " " +
    "WHERE " +
    "[Import_Data_Warehouse] = 1 " +
    "AND " +
    "[TicketDB_Table_Name] = '" + tablename + "' " +
    "ORDER BY [TicketDB_Column_Name]";
    SqlCommand sqlTicketDBRowsCmd = new SqlCommand(sqlTicketDBRowsQuery, sqlTicketDBRowsConn);
    SqlDataReader sqlTicketDBRowsReader = sqlTicketDBRowsCmd.ExecuteReader();
    Int16 TicketDBrowcount = 0;
    while (sqlTicketDBRowsReader.Read())
    if (TicketDBrowcount > 0)
    TicketDBRows += ", ";
    TicketDBRows += " " + sqlTicketDBRowsReader.GetString(0) + " ";
    TicketDBrowcount++;
    #endregion
    String Pattern = @"(\D)\s-\s(\d+)(\s-\s(.*)\s-\s(.*))?";
    String ReProcessFile = null;
    if (prodtable.Equals("Template")) {
    ReProcessFile = "E:\\Templates\\Configs\\" + prodtable + "-Reprocess.txt";
    else
    ReProcessFile = "E:\\SSIS_Configs\\" + custName + "\\" + prodtable + "-Reprocess.txt";
    #region Process Re-Process File
    if (File.Exists(ReProcessFile))
    //MessageBox.Show("File is found");
    using (StreamReader sr = new StreamReader(ReProcessFile))
    //MessageBox.Show("File has been opened");
    string line;
    while ((line = sr.ReadLine()) != null)
    //MessageBox.Show("Found a Line: " + line);
    Regex rgx = new Regex(Pattern, RegexOptions.IgnoreCase);
    MatchCollection matches = rgx.Matches(line);
    foreach (Match match in matches)
    GroupCollection groups = match.Groups;
    Reprocess = groups[1].Value;
    ReprocessDate = groups[2].Value;
    ReprocessPrime = groups[4].Value;
    ReprocessVal = groups[5].Value;
    //MessageBox.Show("Variables Set." + Environment.NewLine +
    // "Reprocess: " + Reprocess + Environment.NewLine +
    // "Reprocess Date: " + ReprocessDate + Environment.NewLine +
    // "Reprocess Primary Field: " + ReprocessPrime + Environment.NewLine +
    // "Reprocess Value Field: " + ReprocessVal);
    //MessageBox.Show("End Processing File");
    #endregion
    #region Re-Proccess Rows
    if (Reprocess.Equals("T"))
    if (String.IsNullOrEmpty(ReprocessPrime) && String.IsNullOrEmpty(ReprocessVal))
    else
    //MessageBox.Show("Finished Getting Read Only Variables");
    string sqlQuery = "SELECT TOP (1000) " + uniqIDField + " " +
    "FROM " + prodtable + " " +
    "WHERE " +
    "[" + ReprocessVal + "] IS NULL " +
    "AND " +
    "[" + ReprocessPrime + "] IS NOT NULL " +
    "ORDER BY [" + modField + "]";
    //MessageBox.Show("sqlQuery: " + sqlQuery);
    SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
    SqlDataReader sqlReader = sqlCmd.ExecuteReader();
    newSelectSQL = "SELECT " + TicketDBRows + " FROM " + TicketDBSchema + "." + tablename + " WHERE "; // + modField + " > '" + maxModDate + "' ";
    while (sqlReader.Read())
    if (count == 0)
    newSelectSQL += " CASE_ID IN (";
    if (count > 0)
    newSelectSQL += ", ";
    newSelectSQL += "'" + sqlReader.GetString(0) + "'";
    count++;
    newSelectSQL += ") OR " + modField + " > '" + maxModDate + "' ORDER BY " + modField + " ASC";
    //sqlConn.Close();
    if (count == 0)
    //MessageBox.Show("Reprocess: " + Reprocess + Environment.NewLine + "Start Date: " + ReprocessDate);
    newSelectSQL = "SELECT " + TicketDBRows + " FROM " + TicketDBSchema + "." + tablename + " " + "WHERE " + modField + " >= '" + ReprocessDate + "' ";
    newSelectSQL += "ORDER BY " + modField + " ASC";
    vars["User::Reprocess_Records"].Value = newSelectSQL.ToString();
    //Dts.Variables["User::Reprocess_Records"].Value = "T";
    else
    //MessageBox.Show("NO Reprocess: " + Reprocess + Environment.NewLine + "Max Date: " + maxModDate);
    newSelectSQL = "SELECT " + TicketDBRows + " FROM " + TicketDBSchema + "." + tablename + " " + "WHERE " + modField + " > '" + maxModDate + "' ";
    newSelectSQL += "ORDER BY " + modField + " ASC";
    #endregion
    else
    //MessageBox.Show("NO Reprocess: " + Reprocess + Environment.NewLine + "Max Date: " + maxModDate);
    newSelectSQL = "SELECT " + TicketDBRows + " FROM " + TicketDBSchema + "." + tablename + " " + "WHERE " + modField + " > '" + maxModDate + "' ";
    newSelectSQL += "ORDER BY " + modField + " ASC";
    //MessageBox.Show("Maybe New SQL: " + newSelectSQL.ToString());
    //Variables vars = null;
    MessageBox.Show("Got Variable now lets set it to: " + newSelectSQL.ToString());
    // Now you can use the variables
    vars["User::TicketDB_Get_SQL"].Value = newSelectSQL.ToString();
    MessageBox.Show("New SQL: " + vars["User::TicketDB_Get_SQL"].Value.ToString());
    //vars.Unlock();
    catch (Exception ex)
    //MessageBox.Show("Error :(");
    // Throw an exception or add some logging
    //this.Dts.Events.FireInformation(1, "Something Went Wrong", newSelectSQL.ToString(), "", 0, ref fireAgain);
    throw ex;
    //Dts.TaskResult = (int)ScriptResults.Failure;
    finally
    //MessageBox.Show("Trying to UNLock Variable");
    // Release the locks (even if your script task fails)
    vars.Unlock();
    //Dts.Variables["User::TicketDB_Get_SQL"].Value = newSelectSQL;
    //MessageBox.Show("New SQL: " + Dts.Variables["User::TicketDB_Get_SQL"].Value);
    Dts.TaskResult = (int)ScriptResults.Success;
    So that is my code... when I run it, line # 217 shows what the new Variable should be... However when I hit line # 220 it isn't set and if I let it continue I am watching the variables and it isn't getting set.  I am confused... anyone??
    Billy S.

    Hi Billy S,
    Thank you for sharing your solutions and experience here. It will be very beneficial for other community members who have similar questions.
    Thanks,
    Eileen
    TechNet Subscriber Support
    If you are
    TechNet Subscription user and have any feedback on our support quality, please send your feedback
    here

  • SSIS 2005 Script task to process XMLA

    Hi,
    I am looking for a script (in script task SSIS 2005) to execute the XMLA command.This needs to be done through script only as my Analysis DDL task is having issue with connection.Please let me know,if any one can help me on this.
    Thanks,
    Ramesh

    Not sure whats the issue with your connection but we usually make use of dynamic XMLA scripts generated using script task and pass them onto Analysis services ddl task to create partitions. Similarly we use analysis services processing task to process the
    created partitions. If you can give more details on issue we may be able to help you out.
    Alternatively, if you want a solution using only script task have a look at the below
    http://bishtabhinav.wordpress.com/2012/06/01/cube-processing-using-ssis/
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • How to migrate to SSIS 2012 from Integration Services dtsx file?

    I am struck at migrating the dtsx file to SSIS 2012. How to migrate that dtsx file to SSIS 2012.I made it to migrate from SQL2000 to SQL 2005 dtsx. Now I want to migrate or upgrade it to SSIS 2012.How to achieve it.Help me please. 
    sammy

    Hi sammy,
    Based on your description, you want to upgrade SQL Server 2005 packages to SQL Server 2012. If there are some individual packages, I suggest that we can directly add the SQL Server 2005 package to an existing project in SQL Server Data Tools (SSDT). For
    more details, please see:
    Right click on the SSIS Packages folder in the Integration Services Project in SSDT and Select Add Existing Package from the context menu.
    In the Add Copy of Existing Package dialog box select Package location as File System from the dropdown.
    Click on the ellipsis button next to the Package path textbox.
    Locate the SSIS package (.dtsx file) which you want to add from the file system.
    Click OK in the Add Copy of Existing Package dialog box to finish adding and upgrading the package.
    If those packages are located in a project, we can open a SQL Server 2005 Integration Services (SSIS) project file in SSDT, and then use the SSIS Package Upgrade Wizard to upgrade multiple packages in the project.
    If there are any questions, please feel free to ask.
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • CDC SSIS 2012 ,CDC TASK,CDC Source,CDC Splitter

    Hi,
    I tried CDC in SSIS 2012 yesterday I was unable to run the hole process sucessfully
    http://www.mattmasson.com/index.php/2011/12/cdc-in-ssis-for-sql-server-2012-2/?utm_source=rss&utm_medium=rss&utm_campaign=cdc-in-ssis-for-sql-server-2012-2--------------------------------------------------------------------------------
    did any one tried this process
    Sri.Tummala

    sorry my sql server agent is turned off i have to turn it on
    after turning it on i trie dto run the package it gave following errors in data flow
    [CDC Source [2]] Error: "Value ILUPDATE/CE/0x00078CD5000023D20001/IR/0x00078CD5000023590002//TS/2012-05-24T14:12:15.0476569/ of CDC state User::CDC_State is not well structured. Structure must be - logicalName(required)/[CS/<cs-lsn>/](optional)[CE/<ce-lsn>/](optional)[IR<ir-start>/<ir-end>/](optional)/[TS/timestamp/](optional)[ER/<error-message>/](optional).".
    [CDC Source [2]] Error: System.Exception: Value ILUPDATE/CE/0x00078CD5000023D20001/IR/0x00078CD5000023590002//TS/2012-05-24T14:12:15.0476569/ of CDC state User::CDC_State is not well structured. Structure must be - logicalName(required)/[CS/<cs-lsn>/](optional)[CE/<ce-lsn>/](optional)[IR<ir-start>/<ir-end>/](optional)/[TS/timestamp/](optional)[ER/<error-message>/](optional).
       at Attunity.SqlServer.CDCSrc.CdcSourceComponent.PrimeOutput(Int32 outputs, Int32[] outputIDs, PipelineBuffer[] buffers)
       at Microsoft.SqlServer.Dts.Pipeline.ManagedComponentHost.HostPrimeOutput(IDTSManagedComponentWrapper100 wrapper, Int32 outputs, Int32[] outputIDs, IDTSBuffer100[] buffers, IntPtr ppBufferWirePacket)
    [SSIS.Pipeline] Error: SSIS Error Code DTS_E_PRIMEOUTPUTFAILED.  The PrimeOutput method on CDC Source returned error code 0x80131500.  The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure
    code is defined by the component, but the error is fatal and the pipeline stopped executing.  There may be error messages posted before this with more information about the failure.
    Sri.Tummala

  • Major Bug in SSIS 2012 Script Component - Potentially

    I think there is a major issue with the Script Component in SSIS when running SSDT on Windows 8.1. I have a Script Component that functions as a data source. The script compiles successfully. However, when returning back to the Data Flow Task, I still get the
    following error which I'd get when an error exists in the Script.
    Validation error. Data Flow Task Script Component [2]: The binary code for the script is not found. Please open the script in the designer by clicking Edit Script button and make sure it builds successfully.
    The script compiles successfully so this is frustrating. This is incorrect and I believe it's an issue with SSDT/SSIS when run on Windows 8.1. I've applied SQL Server 2012 SP1 with CU7 and the error still exists. Can someone else confirm this as
    a bug? 
    &lt;a href=&quot;http://martinsbiblog.spaces.live.com&quot; target=&quot;_blank&quot;&gt;http://martinmason.wordpress.com&lt;/a&gt;

    I'm simply doing the following: 
    Add a Data Flow Task.
    Add a Script Component. Configure as a Source.
    Double click on the Script Component.
    Click on the Edit Script button.
    Compile the script. Compiles successfully.
    Close the VSTAProject editor.
    Close the Script Component properties page.
    When returning to the Data Flow, the "Binary code for the script is not found" error is return
    Running as an Administrator did not solve the problem. Again, this is only an issue with SSIS on Windows 8.1 so if you're not running on Windows 8.1, do not bother replying. I've applied SP1 and CU7 and the problem was not resolved.
    Really regretting upgrading to Windows 8.1.
    &lt;a href=&quot;http://martinsbiblog.spaces.live.com&quot; target=&quot;_blank&quot;&gt;http://martinmason.wordpress.com&lt;/a&gt;

  • Is it a bug - SSIS 2012 ReadOnlyVariables in Script Task doesn't work

    It's very weird when I use the ReadOnlyVariables in SSIS 2012 Script Task, it doesn't work at all!!! And I never notice this change before, but everything in 2008 R2 is fine! Is it a bug in SSIS 2012 ?
    All the variables I set them to "ReadOnlyVariables"
    In scripts - I assigned some values from system variables.
    String PackageName = Dts.Variables["System::PackageName"].Value.ToString();
    DateTime CurrentDate = (DateTime)Dts.Variables["System::StartTime"].Value;
    // User Defined Variables
    Dts.Variables["User::PV_CURRENT_DATE"].Value = CurrentDate;
    Dts.Variables["User::PV_YEAR"].Value = CurrentDate.Year;
    Dts.Variables["User::PV_MONTH"].Value = CurrentDate.Month;
    Dts.Variables["User::PV_DAY"].Value = CurrentDate.Day;
    Dts.Variables["User::PV_PACKAGE_NAME"].Value = PackageName;
    Execute the package, it works !
    The only thing I can make it as SSIS 2008 R2 does is to change the ReadOnly for each variables.
    Then you will get the error.
    Why do we need this feature here but not to use the ReadOnlyVariables in script task ?
    Please vote if it's helpful and mark it as an answer!

    I can reproduce it as well. Feels like a bug...
    Locking the variable for read in code has the same effect:
    public void Main()
    // Lock variable for read
    Dts.VariableDispenser.LockForRead("User::myStringVariable");
    // Create a variables 'container' to store variables
    Variables vars = null;
    // Add variable from the VariableDispenser to the variables 'container'
    Dts.VariableDispenser.GetVariables(ref vars);
    // Now try giving it a new name
    vars["User::myStringVariable"].Value = "new value";
    // Release the locks
    vars.Unlock();
    Dts.TaskResult = (int)ScriptResults.Success;
    For reference:
    https://connect.microsoft.com/SQLServer/Feedback/Details/991697
    Please mark the post as answered if it answers your question | My SSIS Blog:
    http://microsoft-ssis.blogspot.com |
    Twitter

  • SSIS 2008 – Read roughly 50 CSV files from a folder, create SQL table from them dynamically, and dump data.

    Hello everyone,
    I’ve been assigned one requirement wherein I would like to read around 50 CSV files from a specified folder.
    In step 1 I would like to create schema for this files, meaning take the CSV file one by one and create SQL table for it, if it does not exist at destination.
    In step 2 I would like to append the data of these 50 CSV files into respective table.
    In step 3 I would like to purge data older than a given date.
    Please note, the data in these CSV files would be very bulky, I would like to know the best way to insert bulky data into SQL table.
    Also, in some of the CSV files, there will be 4 rows at the top of the file which have the header details/header rows.
    According to my knowledge I would be asked to implement this on SSIS 2008 but I’m not 100% sure for it.
    So, please feel free to provide multiple approaches if we can achieve these requirements elegantly in newer versions like SSIS 2012.
    Any help would be much appreciated.
    Thanks,
    Ankit
    Thanks, <b>Ankit Shah</b> <hr> Inkey Solutions, India. <hr> Microsoft Certified Business Management Solutions Professionals <hr> http://ankit.inkeysolutions.com

    Hello Harry and Aamir,
    Thank you for the responses.
    @Aamir, thank you for sharing the link, yes I'm going to use Script task to read header columns of CSV files, preparing one SSIS variable which will be having SQL script to create the required table with if exists condition inside script task itself.
    I will be having "Execute SQL task" following the script task. And this will create the actual table for a CSV.
    Both these components will be inside a for each loop container and execute all 50 CSV files one by one.
    Some points to be clarified,
    1. In the bunch of these 50 CSV files there will be some exception for which we first need to purge the tables and then insert the data. Meaning for 2 files out of 50, we need to first clean the tables and then perform data insert, while for the rest 48
    files, they should be appended on daily basis.
    Can you please advise what is the best way to achieve this requirement? Where should we configure such exceptional cases for the package?
    2. For some of the CSV files we would be having more than one file with the same name. Like out of 50 the 2nd file is divided into 10 different CSV files. so in total we're having 60 files wherein the 10 out of 60 have repeated file names. How can we manage
    this criteria within the same loop, do we need to do one more for each looping inside the parent one, what is the best way to achieve this requirement?
    3. There will be another package, which will be used to purge data for the SQL tables. Meaning unlike the above package, this package will not run on daily basis. At some point we would like these 50 tables to be purged with older than criteria, say remove
    data older than 1st Jan 2015. what is the best way to achieve this requirement?
    Please know, I'm very new in SSIS world and would like to develop these packages for client using best package development practices.
    Any help would be greatly appreciated.
    Thanks, <b>Ankit Shah</b> <hr> Inkey Solutions, India. <hr> Microsoft Certified Business Management Solutions Professionals <hr> http://ankit.inkeysolutions.com
    1. In the bunch of these 50 CSV files there will be some exception for which we first need to purge the tables and then insert the data. Meaning for 2 files out of 50, we need to first clean the tables and then perform
    data insert, while for the rest 48 files, they should be appended on daily basis.
    Can you please advise what is the best way to achieve this requirement? Where should we configure such exceptional cases for the package?
    How can you identify these files? Is it based on file name or are there some info in the file which indicates
    that it required a purge? If yes you can pick this information during file name or file data parsing step and set a boolean variable. Then in control flow have a conditional precedence constraint which will check the boolean variable and if set it will execute
    a execte sql task to do the purge (you can use TRUNCATE TABLE or DELETE FROM TableName statements)
    2. For some of the CSV files we would be having more than one file with the same name. Like out of 50 the 2nd file is divided into 10 different CSV files. so in total we're having 60 files wherein the 10 out of 60 have
    repeated file names. How can we manage this criteria within the same loop, do we need to do one more for each looping inside the parent one, what is the best way to achieve this requirement?
    The best way to achieve this is to append a sequential value to filename (may be timestamp) and then process
    them in sequence. This can be done prior to main loop so that you can use same loop to process these duplicate filenames also. The best thing would be to use file creation date attribute value so that it gets processed in the right sequence. You can use a
    script task to get this for each file as below
    http://microsoft-ssis.blogspot.com/2011/03/get-file-properties-with-ssis.html
    3. There will be another package, which will be used to purge data for the SQL tables. Meaning unlike the above package, this package will not run on daily basis. At some point we would like these 50 tables to be purged
    with older than criteria, say remove data older than 1st Jan 2015. what is the best way to achieve this requirement?
    You can use a SQL script for this. Just call a sql procedure
    with a single parameter called @Date and then write logic like below
    CREATE PROC PurgeTableData
    @CutOffDate datetime
    AS
    DELETE FROM Table1 WHERE DateField < @CutOffDate;
    DELETE FROM Table2 WHERE DateField < @CutOffDate;
    DELETE FROM Table3 WHERE DateField < @CutOffDate;
    GO
    @CutOffDate which denote date from which older data have to be purged
    You can then schedule this SP in a sql agent job to get executed based on your required frequency
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • How can apply configure file in ssis by using script task ?

    I had  two config file in ssis
     1. config file as per QA
    2. config file as per Production
     I think apply dynamically by using script task for above file (acc to server)
    How can I apply in script task for config file path in C# script
    any one provide Helpful code ??
    Thanks

    I applied script Task  with below code :
    public void Main()
    //User::Config,User::Config_Pd,User::Config_QA
    Application App = new Application();
    Package Pack = new Package();
    DTSExecResult pkgResults;
    string strPackageName;
    string filename = "";
    string configvalue;
    configvalue = Dts.Variables["Config"].Value.ToString();
    strPackageName = Directory.GetCurrentDirectory().ToString() + "\\Excel Reports from Remittance advice\\Child.dtsx";
    try
    Pack = App.LoadPackage(strPackageName, null);
    if (Pack != null)
    if (configvalue == "DEV")
    filename = Dts.Variables["Config_QA"].Value.ToString();
    else if (configvalue == "PROD")
    filename = Dts.Variables["Config_Pd"].Value.ToString();
    else
    Dts.TaskResult = (int)ScriptResults.Failure;
    System.Windows.Forms.MessageBox.Show("Unable to bind the XML Configurations");
    return;
    } System.Windows.Forms.MessageBox.Show("Config:"+filename);
    Pack.ImportConfigurationFile(@filename);
    Pack.EnableConfigurations = true;
    Pack.Configurations.Add();
    App.SaveToXml(strPackageName, Pack, null)
    pkgResults = Pack.Execute(); //Pack.Execute();
    System.Windows.Forms.MessageBox.Show("Results:" + pkgResults.ToString());
    Dts.TaskResult = (int)ScriptResults.Success;
    But ouput in ssis showing as
    But some thing missed in code  plz help me ...

  • Script Task Builds Successfully But Still Has Compile Error (SQL 2012)

    This is repost in a way but the problem has not gone away and I really need to find a solution.
    I have some script from SSIS 2008 that uses the ReportExecution2005
    web service to execute SSRS reports and save the results to Excel. There were some initial problems with confusion between Web Service Reference (legacy?) and Service Reference (WCF) but I think that I have that sorted out
    now.
    The remaining problem is that, while the VB script (which I have pasted in from a working SSIS 2008 Script Task) builds/complies without error, I get a compile error when I close the Script Task and it has the dreaded "Red X" in the Control
    Flow. If I attempt to run the package I get a message box saying that there is a compile error.
    How can I identify the problem and fix the error? The script itself has no errors in SSIS 2008.
    R Campbell

    This is the code by the way (see below) as pasted into the Main sub.
    I have added
    http://localhost/reportserver/reportexecution2005.asmx as a Web Service
    Reference (under the  "Advanced" button) not just a Service Reference (WCF).
    I can build the code without error but I get an error, saying that there is compile error, when I close the Script Task.
    ReportExecutionService definitely shows up in Object Explorer, not the
    WCF "equivalent" of ReportExecutionServiceSoapClient.
    I have always had the impression, that when you close a Script Task, a compiler kicks in to auto-generate some internal script. Could it be (as seems likely) that this compiler is picking up errors that "Build" doesn't (when the script is open)?
    I think that there was once an explicit Compile rather than just Build option in the Script editing environment but I can't find it in SQL 2012 Database Tools (nee BIDS).
    Dim objRSExec As New localhost.ReportExecutionService
    Dim objParam0 As New localhost.ParameterValue
    Dim objParam1 As New localhost.ParameterValue
    Dim objParam2 As New localhost.ParameterValu
    Dim objParam3 As New localhost.ParameterValue
    Dim objParam4 As New localhost.ParameterValue
    Dim objParam5 As New localhost.ParameterValue
    Dim objParam6 As New localhost.ParameterValue
    Dim objParams() As localhost.ParameterValue
    Dim objResult() As Byte
    Dim objStream As FileStream
    Dim FileType As String
    Dim FileExtension As String
    Dim FilePath As String
    Dim NumberOfParameters As Integer
    Dim ReportName As String
    Dim TaskSuccess As Boolean = True
    FileType = Dts.Variables("FileType").Value.ToString()
    FileExtension = Dts.Variables("FileExtension").Value.ToString()
    FilePath = Dts.Variables("FilePathNameExt").Value.ToString()
    ReportName = Dts.Variables("ReportPathName").Value.ToString()
    NumberOfParameters = CInt(Dts.Variables("NumberOfParameters").Value) - 1
    ReDim objParams(NumberOfParameters)
    If NumberOfParameters >= 0 Then
    objParam0.Name = Dts.Variables("P0Name").Value.ToString()
    objParam0.Value = Dts.Variables("P0Value").Value.ToString()
    objParams(0) = objParam0
    End If
    If NumberOfParameters >= 1 Then
    objParam1.Name = Dts.Variables("P1Name").Value.ToString()
    objParam1.Value = Dts.Variables("P1Value").Value.ToString()
    objParams(1) = objParam1
    End If
    If NumberOfParameters >= 2 Then
    objParam2.Name = Dts.Variables("P2Name").Value.ToString()
    objParam2.Value = Dts.Variables("P2Value").Value.ToString()
    objParams(2) = objParam2
    End If
    If NumberOfParameters >= 3 Then
    objParam3.Name = Dts.Variables("P3Name").Value.ToString()
    objParam3.Value = Dts.Variables("P3Value").Value.ToString()
    objParams(3) = objParam3
    End If
    If NumberOfParameters >= 4 Then
    objParam4.Name = Dts.Variables("P4Name").Value.ToString()
    objParam4.Value = Dts.Variables("P4Value").Value.ToString()
    objParams(4) = objParam4
    End If
    If NumberOfParameters >= 5 Then
    objParam5.Name = Dts.Variables("P5Name").Value.ToString()
    objParam5.Value = Dts.Variables("P5Value").Value.ToString()
    objParams(5) = objParam5
    End If
    If NumberOfParameters >= 6 Then
    objParam6.Name = Dts.Variables("P6Name").Value.ToString()
    objParam6.Value = Dts.Variables("P6Value").Value.ToString()
    objParams(6) = objParam6
    End If
    Try
    With objRSExec
    .Credentials = System.Net.CredentialCache.DefaultNetworkCredentials
    .Url = "http://localhost/reportserver/reportexecution2005.asmx"
    .LoadReport(ReportName, Nothing)
    .SetExecutionParameters(objParams, "en-us")
    objResult = .Render(FileType, Nothing, FileExtension, Nothing, Nothing, Nothing, Nothing)
    End With
    objStream = File.Create(FilePath, objResult.Length)
    With objStream
    .Write(objResult, 0, objResult.Length)
    .Close()
    End With
    Catch e As Exception
    Dts.Log("ERROR - RSExec - " & e.Message.ToString(), 100, Nothing)
    TaskSuccess = False
    End Try
    If TaskSuccess Then
    Dts.TaskResult = ScriptResults.Success
    Else
    Dts.TaskResult = ScriptResults.Failure
    End If
    R Campbell

  • Error while sending mail using script task in ssis 2008

    Hi,
        i am trying to send mail using ssis 2008 script task.for my requirement i am not able to use send mail task.
    code i have used is
    declared read only variables system::packagename
     Dim PACKAGE As String
            PACKAGE = Dts.Variables("System::PackageName").Value.ToString()
            Dim myHtmlMessage As MailMessage
            Dim mySmtpClient As SmtpClient
            myHtmlMessage = New MailMessage("[email protected]", "[email protected]", "PACKAGE STATUS", PACKAGE + "WAS FAILED")
         mySmtpClient = New SmtpClient("smtp.gmail.com")
            mySmtpClient.Credentials = New NetworkCredential("[email protected]", "mypassword")
            mySmtpClient.EnableSsl = True
            mySmtpClient.Port = 587
            mySmtpClient.Send(myHtmlMessage)
    error i am getting is
    Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1
    Authentication Required. Learn more at
       at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
       at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, String from)
       at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
       at System.Net.Mail.SmtpClient.Send(MailMessage message)
       at ST_c121e07caaa94c21bb1355d4f753112f.vbproj.ScriptMain.Main()
       --- End of inner exception stack trace ---
       at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
       at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
       at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
       at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, CultureInfo culture)
       at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()
    can any one tell me where i am going wrong

    also getting error as follows
    Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1
    Authentication Required. Learn more at
       at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
       at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, String from)
       at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
       at System.Net.Mail.SmtpClient.Send(MailMessage message)
       at ST_c121e07caaa94c21bb1355d4f753112f.vbproj.ScriptMain.Main()
       --- End of inner exception stack trace ---
       at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
       at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
       at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
       at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, CultureInfo culture)
       at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()

  • Package Configuration Files Not loading SSIS 2012

    I've migrated an SSIS 2008 project to SSIS 2012 that uses xml configuration files. When I execute the first package through the IDE, the values in the config file are not populating variables as they did in SSIS 2008. I've enabled Package Configurations
    and added the config files and not sure what I could be doing wrong. Could anyone offer any suggestions.
    Thanks

    Someone else migrated it for me before I had vs2012 installed. So I decided I would try migrating it myself. Now the config files are loading. When I migrated it there was an option for ignore config files that was checked. I unchecked it. Could that have
    been the problem?
    I just have one more issue now...Whenever I open the solution, it loads the config files, but two passwords are encrypted. For some reason it tries to login to the database when I load the package. This didn't occur in SSIS 2008. Do you know of any way to
    disable this? I get about 2 failures before I'm locked out of the db.
    Thanks

Maybe you are looking for