C# Script Task - MessageBox Variables

I dont know C#, so I thought I would start simple and try to do message box a variable. I am struggling even with that.
In VB.net I would print a value of the variable in a message box using the following syntax.
                Msgbox(dts.variables(“VariableName”).value.tostring)
In C#
                MessageBox.Show(Dts.Variables
At the point of selecting variables it is giving me this message.
                Error      1              Non-invocable member 'Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTAProxy.ScriptObjectModel.Variables' cannot be used like a method.         
I have following using statements defined. Do I need more?
                using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime.VSTAProxy;
using System.Windows.Forms;
using Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTAProxy;
I might be missing something. Can anyone help?
Thanks
Sutha

Why do I get the following exception?:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   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 Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()

Similar Messages

  • C# Script Task string variable replace wont replace

    The code below ought to replace "A" with "B" but it doesnt.
    Please tell me how to make this work. Thanks!

    Doug,
    it returns a new string (does not assign to the same)
    So you need fn  = fn.Replace("A", "B");
    Arthur
    MyBlog
    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

  • 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.

  • Variable of Type "Object" is getting Null in script task

    I have 3 components as below
    1.   Execute Sql Task ---> It will fetch The data from Database using ConnectionType "OLEDB" ("Full Result Set" its returning) and Store it in the Variable as below,
          "ConfigDetails"   "Scope --> Package"    "Type -  Object".
    2.  Script Task  (First) ---->   Here "ConfigDetails" Variable is part of "ReadOnlyVariables", So i am accessing this varaible and populating data from it in the Data Table object as below,
    OleDbDataAdapter configAdapter = new OleDbDataAdapter();
    DataTable dtConfigurationList = new DataTable();
    object config = Dts.Variables["ConfigDetails"].Value;
    configAdapter.Fill(dtConfigurationList, config);
      So here i am successfull in populating data in the data table .
    3. Script Task (Second)--> Same thig i am doing in second script task also as "First"
    Here "ConfigDetails" Variable is part of "ReadOnlyVariables", So i am accessing this varaible and populating data from it in the Data Table object as below,
    OleDbDataAdapter configAdapter = new OleDbDataAdapter();
    DataTable dtConfigurationList = new DataTable();
    object config = Dts.Variables["ConfigDetails"].Value;
    configAdapter.Fill(dtConfigurationList, config);
     So here it will execute successfully without any error. But no data is there in the data table .
    If i skip first script task, second script task is able to populate the data. But i am not righting any code to nullify the object and its part of "Read Only Varaibles."
      So please help me what i am doing wrong.
                configAdapter.Fill(dtConfigurationList, config);

    What do you pass to the config variable?
    Arthur My Blog

  • Pass variables to child via C# script task ?

    I don't want to use package configurations to pass variables from Parent to child package. I'd prefer to pass the variables to child, from a  C# script task in the parent package. Can this be done ? Here is the pseudocode for what I hope to do - 
    //code in script task of parent package
    Main(){
    Object parentObj = SSIS.ParentPackage.myObject;
    String parentStr =  SSIS.ParentPackage.myString;
    callChildPackage(parentObj, parentStr);

    You have four choices for this:
    Use Parent-Child variable configurations
    Place the value in a variable in the parent package, which can be referenced from the child package, when run with an Execute Package Task. (http://agilebi.com/jwelch/2009/10/03/passing-an-object-from-a-parent-package-to-a-child)
    Take over the execution of the child package entirely executing the package from inside your C# script task.
    Use something like the Task Factory Advanced Execute Package task. (Full Disclosure: I work for Pragmatic Works)
    Item 3 is probably closest to what you want. You'd need to use the Package.Execute method to run the child package yourself. The advantage of doing that is you can set child package variables explicitly before executing the package.
    John Welch | www.pragmaticworks.com | www.agilebi.com | ssisUnit.codeplex.com

  • Script task within child package - breakpoint wont hit, trying to find missing variable

    Im calling a child package and its failing on a script task with a message which indicates one of the variables cant be found
    The script threw an exception: The element cannot be found in a collection.
    So I remove the readonly/readwrite section, and place a breakpoint on the very first line of the script task. When I run the main package, by breakpoint on the child package script task isnt hit but I still get the error about the missing variable.
    How can I find out which variable its complaining about?

    You can raise an event in the script using FireInformation and pass into it the variable content as string
    examples:
    http://technet.microsoft.com/en-us/library/ms136054.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
    The variable content will put into the Output window (go to View menu to enable it).
    Arthur My Blog

  • Creating an empty file using variable in script task

    I created an empty file by writing a code in script task. how can i use a variable to do the same job.
    System.IO.File.Create(@"C:\OneEmptyTextFile.txt");

    Hi SyedF,
    Just as you said, we should refer to the code below to create an empty file in the specified path using System.IO.File.Create:
    System.IO.File.Create(Path)
    If we want to use a variable named FilePath to control the path of the created file, please refer to the following code:
    Dim Path As String
    Path = Dts.Variables("FilePath").Value
    System.IO.File.Create(Path)
    Reference:
    https://msdn.microsoft.com/en-IN/library/ms135941.aspx
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • Script task error during the creation of partition by reading a table and using AMO - SSAS 2012

    Hi,
    I need to create SSAS (tabular) and process partitions in an authomatic manner. Moreover, the partitioning is respect to a category, an year and a month.
    Category, year and month are resident on a table to read to create the SSAS partitions.
    So, in a SSIS pkg:
    a. I've created a data flow task to read the SQL Server table having category, year and month data,
    b. I've connected the output of the ole db source as the input for a recordset destination, associated to an object variable,
    c. I've used a for each loop container (ado enumerator) specifying the object variable and three variables, for category, year and month,
    d. inside the for each loop container I've created a script task using AMO (visual basic) to control for any existing partitions, if not presents to create the new ones and then to process them.
    For the first iteration, a new partition has been created and processed successfully, but then, for other category, year and month values the script task fails. I've controlled the code many times and I've tried to put returning messageboxes but I've found
    anything. The error is a generic one and no other info are returned.
    Well, any suggests to me in order to solve this issue, please?
    Many thanks

    Hi, thanks, I've solved adding to the code end the SSAS server connection termination.
    Bye

  • 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

  • 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 ...

  • 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

  • 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

Maybe you are looking for

  • Acrobat X Pro for Mac fails to scan double-sided

    Hello All, I am having trouble in scanning double-sided through Acrobat X Pro with a Canon MF4880dw installed on an iMac with Mountain Lion. Here is the procedure I follow: File > Create > PDF from scanner in the box "Sides", I select "Both Sides" an

  • How do you connect Jetpack to a Time Capsule

    How do I connect a Verizon Jetpack to a Time Capsule?  I currently use a Pepwave router to connect to my Jetpack via USB and to other networks via WAN over Wifi and create my own WiFi network.  Since I use the Jetpack more than WAN over WiFi, is ther

  • HTTP errors and/or access denied messages preventing me from downloading CS5.5

    How can I download my copy of CS5.5 Design Standard? I keep getting HTTP errors and/or access denied messages.

  • My iPhone 4S randomly shuts down.

    My iPhone 4S randomly shuts down, when plug it into charge. I restored, as a new iPhone and problem continues, what do I do?  iPhone is 4 months old, and has no damage.

  • Can music now be set to fit slideshow?

    OK - due to iMovie playing up, I was going to take a look at doing slideshows in iPhoto again. But with 05, the 'fit to music' thing didn't work once you export to QT - the music would run out before the end - usually by quite some way. Does anyone k