DateTime.Now.ToString() in Script Task

In Script task,
I am trrying to append timestamp to file Name. date format is passed through a variable in Cofig file. (dtFormat='ddMMyyyy_HHmmss').
But I get date in dd/MM/yyyy HH:mm:ss.
Filename+DateTime.now.toString(dtFormat)+fileExtension

Hi FlowerRain,
The issue may be caused by the factor that the package configurations was overwritten by the default package configurations. To narrow down the root cause, set the value of the dtFormat variable to ddMMyyyy_HHmmss, and run the package in BIDS/SSDT to see
if generates the right format.
If the string format displays as expected in BIDS/SSDT, the issue should be that the variable value passed from the XML configurations file was overwritten. Do you directly modify the original XML configurations file or create a new XML file for the package?
If you use SSIS 2008 R2 or older releases and specify a new XML configurations file for the package execution, rename or delete the original XML file and check the issue again. 
Besides, you can also use the /SET parameter in the DTExec utility command lines to specify the variable value. The syntax is as follows:
DTEXEC /F "C:\Temp\Package.dtsx" /CONF "C:\Temp\Package1.dtsConfig" /SET \Package.Variables[dtFormat].Value;yyyyMMdd_HHmmss
Regards,
Mike Yin
TechNet Community Support

Similar Messages

  • 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

  • Runtime error Exception has been thrown by the target of an invocation" from Script task

    I have a SSIS package with a script task, I get
    the following error when i try to run it in my local system. It works fine for my collegues as well as in production. However, I am not able to run it locally, to test. I keep a debug point in the main method, but it is never reached, I get the error before
    it goes to main method.
    I am using VS 2010, .Net framework 4.5.
    The script task does compile. I get the following messages SSIS package "..\Test.dtsx" starting. Error: 0x1 at Test: Exception has been thrown by the target of an invocation. Task failed: Test SSIS package "..\Test.dtsx" finished: Success.
    The program '[2552] DtsDebugHost.exe: DTS' has exited with code 0 (0x0).

    The following is the code:
    public void Main()
    try
     LogMessages("Update Bug package execution started at :: " + DateTime.Now.ToLongTimeString());
     LogMessages("Loading package configuration values to local variables.");
    strDBConn = Dts.Variables["User::DBConnection"] != null ? Dts.Variables["User::DBConnection"].Value.ToString() : string.Empty;
    strTPCUrl = Dts.Variables["User::TPCUrl"] != null ? Dts.Variables["User::TPCUrl"].Value.ToString() : string.Empty;
    TfsTeamProjectCollection objTPC = new TfsTeamProjectCollection(new Uri(strTPCUrl));
    WorkItemStore objWIS = new WorkItemStore(objTPC);
    WorkItemCollection objWIC = objWIS.Query("SELECT...");
    foreach (WorkItem wi in objWIC)
    catch(Exception ex)
    When I commented the code from TfsTeamProjectCollection objTPC = new TfsTeamProjectCollection(new Uri(strTPCUrl)); The script executes successfully. However, if i keep TfsTeamProjectCollection objTPC = new TfsTeamProjectCollection(new Uri(strTPCUrl));
    and comment the rest, i get the exception.
    I do have access to the URL

  • SSIS Package, Use Datepicker control in VB script task

    Dim dateTimePicker1 As New DateTimePicker()
    Controls.AddRange(New Control() {dateTimePicker1})
    MessageBox.Show(dateTimePicker1.Value.ToString())
    dateTimePicker1.Value = DateTime.Now.AddDays(1)
    MessageBox.Show(dateTimePicker1.Value.ToString())
    In an SSIS package, 2008r2....   I trying to add a messagebox to a script task that contains a datepicker control. 
    I will pass the date to a variable then stored procedure.  The code above almost works except I get "Name Controls not declared".  I am using
    System.Windows.Forms. 
    Anyone know how to correct?
    Thanks,
    MIke

    Nope
    You cant have forms etc added to script task inside SSIS and make it interactive
    If your intention is to pass a value from outside you need to make use of configurations or use command line arguments with utilities like dtexec.
    http://www.bidn.com/blogs/DevinKnight/ssis/1655/passing-values-into-an-ssis-package-at-runtime-from-outside-the-package
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Error While executing script task componnent

    Hi,
    I am using script task comp in  my package .script  written in script task comp
    ' Microsoft SQL Server Integration Services Script Task
    ' Write scripts using Microsoft Visual Basic
    ' The ScriptMain class is the entry point of the Script Task.
    Imports System
    Imports System.Data
    Imports System.Math
    Imports Microsoft.SqlServer.Dts.Runtime
    Imports System.IO
    Imports System.Collections
    Public Class clsCompareFileInfo
        Implements IComparer
        Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compare
            Dim File1 As FileInfo
            Dim File2 As FileInfo
            File1 = DirectCast(x, FileInfo)
            File2 = DirectCast(y, FileInfo)
            Compare = DateTime.Compare(File1.LastWriteTime, File2.LastWriteTime)
        End Function
    End Class
    <System.AddIn.AddIn("ScriptMain", Version:="1.0", Publisher:="", Description:="")> _
    <System.CLSCompliantAttribute(False)> _
    Partial Public Class ScriptMain
        Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
        Enum ScriptResults
            Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
            Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
        End Enum
        Public Sub Main()
            Dim dirinfo As DirectoryInfo
            Dim allFiles() As FileInfo
            dirinfo = New DirectoryInfo(Dts.Variables("gsLaddningsKatalogSokvag").Value.ToString)
            allFiles = dirinfo.GetFiles("*.txt")
            'Sortera filerna efter "senast ändrad" så den fil med äldst "ändrad datum" kommer att laddas först
            Array.Sort(allFiles, New clsCompareFileInfo)
            For Each fl As FileInfo In allFiles
                Dts.Variables("gsInFilNamnMedSokvag").Value = fl.FullName.ToString()
                Dts.Variables("gsInFilNamn").Value = Path.GetFileName(fl.FullName.ToString())
                Exit For
            Next
            Dts.TaskResult = ScriptResults.Success
        End Sub
    End Class
    Error which i ma getting while running..
    Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: The path is not of a legal form.
       at System.IO.Path.NormalizePathFast(String path, Boolean fullCheck)
       at System.IO.Path.NormalizePath(String path, Boolean fullCheck)
       at System.IO.Path.GetFullPathInternal(String path)
       at System.IO.DirectoryInfo..ctor(String path)
       at ST_338efd96a3e940b0b489d5b5000f3397.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()
    Please help.I am using sql server 2008R2 and visual studio 2008 BIDS.

    Hi,
    I am using script task comp in  my package .script  written in script task comp
    ' Microsoft SQL Server Integration Services Script Task
    ' Write scripts using Microsoft Visual Basic
    ' The ScriptMain class is the entry point of the Script Task.
    Imports System
    Imports System.Data
    Imports System.Math
    Imports Microsoft.SqlServer.Dts.Runtime
    Imports System.IO
    Imports System.Collections
    Public Class clsCompareFileInfo
        Implements IComparer
        Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compare
            Dim File1 As FileInfo
            Dim File2 As FileInfo
            File1 = DirectCast(x, FileInfo)
            File2 = DirectCast(y, FileInfo)
            Compare = DateTime.Compare(File1.LastWriteTime, File2.LastWriteTime)
        End Function
    End Class
    <System.AddIn.AddIn("ScriptMain", Version:="1.0", Publisher:="", Description:="")> _
    <System.CLSCompliantAttribute(False)> _
    Partial Public Class ScriptMain
        Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
        Enum ScriptResults
            Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
            Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
        End Enum
        Public Sub Main()
            Dim dirinfo As DirectoryInfo
            Dim allFiles() As FileInfo
            dirinfo = New DirectoryInfo(Dts.Variables("gsLaddningsKatalogSokvag").Value.ToString)
            allFiles = dirinfo.GetFiles("*.txt")
            'Sortera filerna efter "senast ändrad" så den fil med äldst "ändrad datum" kommer att laddas först
            Array.Sort(allFiles, New clsCompareFileInfo)
            For Each fl As FileInfo In allFiles
                Dts.Variables("gsInFilNamnMedSokvag").Value = fl.FullName.ToString()
                Dts.Variables("gsInFilNamn").Value = Path.GetFileName(fl.FullName.ToString())
                Exit For
            Next
            Dts.TaskResult = ScriptResults.Success
        End Sub
    End Class
    Error which i ma getting while running..
    Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. --->
    System.ArgumentException: The path is not of a legal form.
    Hi SR_MCTS, 
    The error message how the path is not of a legal form, please take a look at the highlight content in above message. Please try to use the following code:
    dirinfo = new DirectoryInfo(Dts.Variables["User::Local_Dir"].Value.ToString)
    Please ensure you have configure the vaild path for "Local_Dir" variable. For more information, you can take a look at the following thread:
    http://social.msdn.microsoft.com/forums/sqlserver/en-US/f073ecef-37ed-4a4c-bee6-d9ef66ff471d/filesystem-task-issue-ssis
    Regards,
    Elvis Long
    TechNet Community Support

  • 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

  • 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

  • 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

  • Parallel Script Tasks Using Same Connection Manager are Corrupted

    We're seeing a bizarre issues in our SSIS package.  We are using an HTTP connection manager in multiple script tasks running in parallel and the connections seem to be getting mismatched.  Here's the basic flow.
    We have 6 containers that run in parallel.  Each container does the exact same work (they are copy/pasted) except we change the value of a variable representing the report to generate that is scoped to each container.  The container runs a query
    (using a SQL connection manager defined in the package designer) and then uses a foreach container to enumerate the rows.  The variables inside the foreach container are scoped to it so we don't have a scoping issue.  Within the loop we write
    the variable values to a log table, use a script task to generate an SSRS report and then write all the data and the report to an external system.  Everything is working fine except for the generation of the report.
    Within the report script block we acquire a connection to a HTTP connection manager that is defined in the package (just like the SQL connection manager).  We then create a new HttpClientConnection with it and update the URL to include the necessary
    parameters that SSRS needs to generate the report.  We then download the results and return it back to the container.  Here's the basic code we use
    var httpConn = Dts.Connections["ReportServerUrl"];
    var clientConn = new HttpClientConnection(httpConn.AcquireConnection(null));
    var uri = new UriBuilder(clientConn.ServerURL) { Query = reportQueryInfo };
    clientConn.ServerURL = uri.Uri.ToString();
    clientConn.DownloadData();
    The issue we are seeing is that when 2 of the scripts run at the same time the ServerURLs are getting cross wired such that we see 2 of the same report being requested rather than 1 of each type that we had requested (based upon the SSRS execution logs). 
    It's almost like we are getting a shared HTTP client connection.  Provided the scripts don't run at the same time everything works correctly.  We are confident our variables are set correctly because we are storing them both before and after in external
    tables and they are always correct.  The URL calculation logic is also correct because this problem only occurs when 2 requests are sent in parallel.
    What am I missing here?
    Michael Taylor
    http://blogs.msmvps.com/p3net

    Thank you for the feedback.  Before I go to Connect I'd like to provide some more info that may provide a better idea of what the problem is.
    We broke things down trying to replicate the issue and it isn't a conn mgr problem after all I believe.  To clarify our package, we have 4 containers that execute the same logic (they were copy/pasted) except for the variable values that we set. The
    containers are not linked together so they run in parallel. Each container executes a query using the ADO.NET conn mgr.  A foreach loop captures the value for the current row and then calls SSRS using a script block, forwards the report onto an external
    resource and then updates a table indicating the row has been processed.  The only difference between them is the parameter we pass to the query and the value of the variables (that are scoped to the container or foreach loop).
    The problem we have found is that the very first time through the foreach loop ALL containers are using the same row (from the first container's query).  Second and subsequent rows are fine.  We initially thought the queries were fine because of
    our update at the end of the foreach loop but it is now clear that isn't the case.
    We saw this problem when we moved our package to production.  We went back to Dev and was able to replicate it as well.  It happens every time and it is always the same row when given the same input set.   We started eliminating containers
    and we found it only happens when you get to 3 containers or more.  2 containers had no problems.
    I'll try to replicate it on a simpler solution but any thoughts on whether there is a race condition or something in SSIS would be helpful.

  • Script task fails to send mail to GMAIL

    Hi   guys ,
       I am new here and i am glad i that i am here.  I am working in a company  as SQL Server developer(T-sql), i am learning SSIS because  i wanted to move to data warehousing.
    I not familiar and i don't know any thing about  C#,  but i am learning SSIS on my own.
    I tried to send mail to gmail  using script task , both sender and receiver with same mail ID using variables which i tried using tutorial i found from the below link.
    [quote]http://www.codeproject.com/Articles/85172/Send-Email-from-SSIS-with-option-to-indicate-Email[/quote]
    but finally when i execute the task , it returns failure message and email is not sent.
    [quote]SSIS package "Send mail using script task.dtsx" starting.
    Error: 0x8 at Script Task: The script returned a failure result.
    Task failed: Script Task
    SSIS package "Send mail using script task.dtsx" finished: Success.
    [/quote]
    Below message taken from progress tab
    [quote]Error: The script returned a failure result.[/quote]
    Can you all please help me in  finding where i am going wrong? please check below code which i have used in script task.
    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.Data;
    using Microsoft.SqlServer.Dts.Runtime;
    using System.Windows.Forms;
    using System.Text.RegularExpressions;
    using System.Net.Mail;
    namespace ST_9bc84810a62a401aa44ddd905bcd369d.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
    The execution engine calls this method when the task executes.
    To access the object model, use the Dts property. Connections, variables, events,
    and logging features are available as members of the Dts property as shown in the following examples.
    To reference a variable, call Dts.Variables["MyCaseSensitiveVariableName"].Value;
    To post a log entry, call Dts.Log("This is my log text", 999, null);
    To fire an event, call Dts.Events.FireInformation(99, "test", "hit the help message", "", 0, true);
    To use the connections collection use something like the following:
    ConnectionManager cm = Dts.Connections.Add("OLEDB");
    cm.ConnectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;";
    Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
    To open Help, press F1.
    public void Main()
    string sSubject = "Test Subject";
    string sBody = "Test Message";
    int iPriority = 2;
    if (SendMail(sSubject, sBody, iPriority))
    Dts.TaskResult = (int)ScriptResults.Success;
    else
    //Fails the Task
    Dts.TaskResult = (int)ScriptResults.Failure;
    public bool SendMail(string sSubject, string sMessage, int iPriority)
    try
    string sEmailServer = Dts.Variables["sEmailServer"].Value.ToString();
    string sEmailPort = Dts.Variables["sEmailPort"].Value.ToString();
    string sEmailUser = Dts.Variables["sEmailUser"].Value.ToString();
    string sEmailPassword = Dts.Variables["sEmailPassword"].Value.ToString();
    string sEmailSendTo = Dts.Variables["sEmailSendTo"].Value.ToString();
    string sEmailSendCC = Dts.Variables["sEmailSendCC"].Value.ToString();
    string sEmailSendFrom = Dts.Variables["sEmailSendFrom"].Value.ToString();
    string sEmailSendFromName = Dts.Variables["sEmailSendFromName"].Value.ToString();
    SmtpClient smtpClient = new SmtpClient();
    MailMessage message = new MailMessage();
    MailAddress fromAddress = new MailAddress(sEmailSendFrom, sEmailSendFromName);
    //You can have multiple emails separated by ;
    string[] sEmailTo = Regex.Split(sEmailSendTo, ";");
    string[] sEmailCC = Regex.Split(sEmailSendCC, ";");
    int sEmailServerSMTP = int.Parse(sEmailPort);
    smtpClient.Host = sEmailServer;
    smtpClient.Port = sEmailServerSMTP;
    System.Net.NetworkCredential myCredentials =
    new System.Net.NetworkCredential(sEmailUser, sEmailPassword);
    smtpClient.Credentials = myCredentials;
    message.From = fromAddress;
    if (sEmailTo != null)
    for (int i = 0; i < sEmailTo.Length; ++i)
    if (sEmailTo[i] != null && sEmailTo[i] != "")
    message.To.Add(sEmailTo[i]);
    if (sEmailCC != null)
    for (int i = 0; i < sEmailCC.Length; ++i)
    if (sEmailCC[i] != null && sEmailCC[i] != "")
    message.To.Add(sEmailCC[i]);
    switch (iPriority)
    case 1:
    message.Priority = MailPriority.High;
    break;
    case 3:
    message.Priority = MailPriority.Low;
    break;
    default:
    message.Priority = MailPriority.Normal;
    break;
    //You can enable this for Attachments.
    //SingleFile is a string variable for the file path.
    //foreach (string SingleFile in myFiles)
    // Attachment myAttachment = new Attachment(SingleFile);
    // message.Attachments.Add(myAttachment);
    message.Subject = sSubject;
    message.IsBodyHtml = true;
    message.Body = sMessage;
    smtpClient.Send(message);
    return true;
    catch (Exception ex)
    return false;
    Please help me resolve this guys ... THANKS IN ADVANCE

    Thank you very much for your reply @Elvis Long,
    Sorry for the late reply
    Actually, i am not trying or executing this task  from my office , but i am trying this at my home :( .
    sEmailPort has value 587 sEmailServer has smtp.gmail.com
    Can you please check whether this C# coding is correct or not ? because finally it gives error saying "Script
    Task: The script returned a failure result" 
    so can you please check this with your system and let me know what is wrong with this code
    Thanks in advance  

  • SSIS/Script Task/ VB 2008 Help Urgent...

    Hi Guys, 
    Simple Script Task, just rename Excel tab, here is my code...
    Imports System
    Imports System.Data
    Imports System.Math
    Imports Microsoft.SqlServer.Dts.Runtime
    Imports Microsoft.Office.Interop.Excel
    Imports System.IO
    Imports System.Text
    <System.AddIn.AddIn("ScriptMain", Version:="1.0", Publisher:="", Description:="")> _
    <System.CLSCompliantAttribute(False)> _
    Partial Public Class ScriptMain
    Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    Enum ScriptResults
    Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success
    Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
    End Enum
    Public Sub Main()
    Dts.VariableDispenser.LockForRead("User::FileName") ' File Name Variable
    Dim variablesList As Variables
    Dts.VariableDispenser.GetVariables(variablesList)
    'Dim SFileName As String
    'SFileName = variablesList("User::Filename").Value.ToString
    ' Dim vars As Variables 'New Added For Variable
    Dim oMissing As Object = System.Reflection.Missing.Value
    Dim xl As New Microsoft.Office.Interop.Excel.ApplicationClass()
    Dim xlBook As Microsoft.Office.Interop.Excel.Workbook
    Dim xlSheet As Microsoft.Office.Interop.Excel.Worksheet
    'Dts.VariableDispenser.LockForRead("Filename") 'New Added For Variable
    'Start For Variable
    'Dim File As String 'New Added For Variable
    'File = CType(vars("Filename").Value, String) 'New Added For Variable
    'MsgBox(Prompt:="Filename")
    'Dim laPath As String = "C:\Excel\ABC_dr_daily_lf_10-07-14.xls" 'My File Name
    Dim lapath As String = variablesList("User::FileName").Value.ToString 'New Added For Variable
    'MsgBox(Prompt:="Filename")
    xlBook = DirectCast(xl.Workbooks.Open(laPath, oMissing, oMissing, oMissing, oMissing, oMissing, _
    oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, _
    oMissing, oMissing, oMissing), Workbook)
    xlSheet = DirectCast(xlBook.Worksheets.Item(1), Worksheet)
    xlSheet.Name = "data"
    xlBook.Save()
    xl.Application.Workbooks.Close()
    Dts.TaskResult = ScriptResults.Success
    End Sub
    End Class
    Finally I intalled MS Excel 2007 on my Dev Server. Here is the error that I am receiving....
    Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidCastException: 
    Unable to cast COM object of type 'Microsoft.Office.Interop.Excel.ApplicationClass' to interface type 'Microsoft.Office.Interop.Excel._Application
    '. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208D5-0000-0000-C000-000000000046}'
    failed due to the following error: Library not registered. 
    Please help me, this is very urgent.
    Thank You.

    No I didn't upgrade my SQL Server. OMG this error making me ehhhhhh. 
    Here I solve my problem. 
    RUN>REGEDIT>  and look for "Office.Interop.Excel" and delete the old version. I am using Excel 2007, 14.0. 
    It solve my Problem. 
    Thanks All.

  • 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

  • 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()

  • SSIS : Read Rows from an Object variable in SSIS Script Task which is looped many times.

    Hello All,
    Here is what I am trying to do...
    1. I am having two rows, one column in an Object Variable. (vLoopCountObj).
    2. I am having 30 Rows, 2 Columns in my second Object  Variable (vTableRowsObj)
    3. I have a FOR EACH LOOP which will run for number of rows in vLoopCountObj i.e 2 times here.
    4. I have a Script Task inside the FOR EACH LOOP to display all the rows of vTableRowsObj.
    5. When I execute, 30 Rows gets displayed only once. It will not display when the loop goes for second iteration. Please help me to display for second time.
    6. I have used below code to display the rows whithin the script task which is in SSIS dataflow task.
    Imports System
    Imports System.Data
    Imports System.Math
    Imports Microsoft.SqlServer.Dts.Runtime
    Imports System.Xml
    Imports System.Collections
    Imports System.Data.OleDb
    Public Class ScriptMain
    Public Sub Main()
    Dim oleDA As New OleDbDataAdapter
    Dim dt As New DataTable
    Dim col As DataColumn
    Dim row As DataRow
    Dim sMsg As String
    oleDA.Fill(dt, Dts.Variables("vTableRowsObj").Value)
    MsgBox("Number of Rows " + dt.Rows.Count.ToString())
    For Each row In dt.Rows
    For Each col In dt.Columns
    sMsg = sMsg & col.ColumnName & ": " & row(col.Ordinal).ToString & vbCrLf
    Next
    MsgBox(sMsg)
    sMsg = ""
    Next
    Dts.TaskResult = Dts.Results.Success
    End Sub
    End Class

    Hi Raj,
    It is verrrry interesting issue. I can also confirm that it doesnt loop again. I've made a simple test and figured that in the second loop even you fill the Dataadapter, record count is zero. Which brings me up to the idea: Somehow, after you read the object
    variable resultset, you can not read it again in the for each loop.
    Strange, probably a bug or a technical issue that is beyond my existing knowledge.
    I can provide a workaround. You can also loop in script task for first variable. (Nested loops)
    Let other members to examine and comment on this.
    Regards
    Onur
    (For others who also wants to test, here is my scenario
    Execute SQL Task 1:
    Query: SELECT 1 as Cnt UNION ALL SELECT 2 as Cnt
    Resultset: Full Resultset
    ResultSet Tab: Name: 0, Variable Name: User::vLoopCountObj;
    Execute SQL Task 2:
    Query: SELECT 1 as ColA, 2 as ColB UNION ALL SELECT 3 as ColA, 4 as ColB UNION ALL SELECT 5 as ColA, 6 as ColB
    Resultset: Full Resultset
    ResultSet Tab: Name: 0, Variable Name: User::vTableRowsObj;
    For Each Loop Container:
    Collection: Enum: ForEach ADO Enum
    Source Object: User::vLoopCountObj
    Enum Mode: Rows n the first Table
    Script Task:
    ReadOnlyVariables: User::vTableRowsObj
    Script Source:
    Imports System
    Imports System.Data
    Imports System.Math
    Imports Microsoft.SqlServer.Dts.Runtime
    Imports System.Xml
    Imports System.Collections
    Imports System.Data.OleDb
    Public Class ScriptMain
    Public Sub Main()
    Dim oleDA As New OleDbDataAdapter
    Dim dt As New DataTable
    Dim col As DataColumn
    Dim row As DataRow
    Dim sMsg As String
    oleDA.Fill(dt, Dts.Variables("vTableRowsObj").Value)
    Dts.Events.FireInformation(-1, "START!!!!!!!!!!!!!!", "START LOOP", "", 0, True)
    Dts.Events.FireInformation(1, "RowCount: ", dt.Rows.Count.ToString(), "", 0, True)
    For Each row In dt.Rows
    For Each col In dt.Columns
    sMsg = sMsg & col.ColumnName & ": " & row(col.Ordinal).ToString & vbCrLf
    Next
    Dts.Events.FireInformation(1, "Msg: ", sMsg, "", 0, True)
    sMsg = ""
    Next
    Dts.TaskResult = ScriptResults.Success
    End Sub
    End Class
    BI and ERP Senior Consultant @ Nexum Bogazici
    If it is, Please dont forget to mark as answered or at least vote as helpful if the post helps you in any ways.

  • How to load data into table Using Script Task

    We have a directory/folder where we have a file. We need to insert the File Created Date , File Name , Extension into the database table of Sql server by using Script Task.
    So could you please suggest , how to frame the connection string , fetch the file details and insert the data into the database table using Script Task of SSIS 2008

    You can achieve it as follows using standard script task
    1. Add a ForEachLoop container to point to your directory to iterate though the files. Add a variable of type string inside loop to get file name of each file it iterates. Choose option Filename and extension. Add a variable to just store extension part
    (FileExtension), set EValuateAsExpression true for it and give expression as below
    SUBSTRING(@[User::FileName],FINDSTRING(@[User::FileName],".",1)+1,LEN(@[User::FileName]))
    2. Add a script task inside loop and pass filename variable as a read only variable to it. Crete a new variable to get creationdate and pass it as ReadWrite. Inside write code as below
    Public Sub Main()
    ' Add your code here
    Dim f As New System.IO.FileInfo(Dts.Variables("FileName").Value.ToString())
    Dts.Variables("FileCreatedDate").Value = f.CreationTime
    Dts.TaskResult = ScriptResults.Success
    End Sub
    3. Add a Exec SQL Task after Script task inside loop and give a query like below
    INSERT INTO TableName (FileName,CreatedDate,Extension)
    VALUES(?,?,?)
    and in parameter tab map the parameter placeholders 0,1 and 2 to @[User::FileName],@[User::FileCreatedDate] & @[User::FileExtension] variables
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

Maybe you are looking for

  • Can't play presentation with music

    Hi: I have Adobe Reader X (Spanish) and latest Flash Player installed. In Edit - Preferences - Multimedia of Adobe Reader X, I set as default player "Adobe Flash Player" since I don't have Windows Media Player or Quick Time installed in my computer.

  • Multi Mapping N:1 Mapping

    Hi ,   I want to test N:1 mapping at design time    Source MsgType 0 to unbound in Msg Mapping    Interface mapping Source MI 0 to Unbound    Target MsgType and MI are 1    To add more I am using pattren : Collect & Merge in BPM     in the Test tab o

  • Export songs in mp3 to sd card

    How can I export my Itunes (mac) library to an sd card in mp3 format? thank you

  • Problem with calendar colour categories in iOS 7

    We are running Exchange Server 2007 SP3 and Outlook 2007 SP3. I have an iPhone 5 running iOS 7.0.4 connected to my Exchange account. When I edit items in Outlook and change the colour category, the updated item appears on my phone. However if I make

  • The object contains an unrecognized argument: "JobId"

    Hi all, I'm trying to push configuration on two nodes using WMF 5.0 Preview February 2015 but it is failing to create job on one the second node. Would appreciate any advise on how to resolve this issue. Command: Start-DscConfiguration -Path C:\MOF\A