Script Task order by FileName
I have following code in my script task to get all the files in directory.
String[] sourceFiles =
Directory.GetFiles(Dts.Variables["User::FilePath"].Value.ToString(),
"*.TIF");
I have files in directory as 1.TIF, 10. TIF, 3.TIF.
I would like to process my files in following order 1.TIF, 3.TIF, 10.TIF.
How do i sort it by FileName ascending.
any help much appreciated.
If the numeric sorting is necessary then still the same function applies, but you need to extract the numerical portion of the elements of the file names array (the 3,1...), place 'em into a new numeric array and sort it, and then when you operate on the
elements for processing append the extension (given it is the same for all files, otherwise it becomes tricky).
Arthur
MyBlog
Twitter
Similar Messages
-
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 thanksHi, thanks, I've solved adding to the code end the SSAS server connection termination.
Bye -
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. -
Iterating inside a script task - SSIS 2012
Hi,
in order to create SSAS partitions I need to read a SQL Server table where I've year and month value.
So I think to iterate for each row inside the data set returned by the read operation and for each year and month value to create a SSAS partition.
Is it better to read the SQL Server table outside the script task? How can I iterate for each row in the dataset inside the script component?
Any suggests to me, please?
ThanksI've done similar requirement as below
1. Create a object type variable
2. Use Execute sql task to populate the recordset with partition information from the query. Use resultset option as Full resultset and map to object variable with index 0 in resultset tab
3. Use a For Each Loop with ADO enumerator and map to object variable. Then have variables inside to get individual field values
4. Add script task inside loop and pass the variables inside and use it to build your script task for partition processing. If you want you can also use analysis services DDL task for this too.
Also see these for more info
http://aniruddhathengadi.blogspot.in/2012/07/automate-creation-of-cube-partitions.html
http://dataqueen.unlimitedviz.com/2014/05/how-to-automate-ssas-cube-partitioning-in-ssis/
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
How to 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 2008You 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 -
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 ??
ThanksI 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 ... -
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 -
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)+fileExtensionHi 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 -
Passing parameters with spaces to SCCM Run PowerShell Script task
I am working on an OS deployment task sequence in SCCM 2012 R2 with several Run PowerShell Script tasks. Most of them run fine, but I am having trouble with the one I need to pass parameters to.
The parameters I need to pass are:
-ComputerOU "ou=All Workstations,dc=contoso,dc=com" -GroupDN "cn=Group1,ou=All Groups,dc=contoso,dc=com"
I have that line (with actual DNs) entered in Parameters of the task.
But when the script runs on the target machine, the values of the parameters in the script are truncated at the spaces. $ComputerOU is set to "ou=All" and $GroupDN is set to "cn=Group1,ou=all"
What syntax should I be using the Parameters field of the Task in order to properly pass PowerShell parameter string values that include spaces?
Tim Curwick
MadWithPowerShell.comThank you, TC, but I am not calling the parameters from within PowerShell.
The parameters are in the settings of a task sequence task to be used by the task to launch a script. The syntax I am using would be correct for use within PowerShell or from a command line or batch script, but SCCM appears to be doing some parsing
before or while it is passing them to the script, possibly dropping the quotes which causes mishandling of the spaces in the string values.
Historically, it is always challenging to give one application parameters to pass to another application, and the required syntax can get quite tricky when the two application handle quotes or spaces differently, or when the parent application wants to parse
something intended to be passed on as is to the child application.
I'm sure someone has already figured out what the syntax needs to be for doing this with an SCCM 'Run PowerShell Script" task, it's just one of those issues that is hard to Google effectively.
Any other ideas?
Tim Curwick
MadWithPowerShell.com -
Convert ActiveX DTS script task to SSIS Script task - Please help
Hello,
I Have a ActiveX script that was used in a DTS package but I'm currently trying to convert all my DTS packages to SSIS.The script is tasked to run the package on a daily basis. Everything works fine except the ActiveX script. It gives an error on my DTSGlobalVariables.parent,
I looked up this error and changed it to "DTS.Variables("User::VariableName").Value", in
the SSIS script task (in VB) but now I'm getting error:
Microsoft.SqlServer.Dts.Runtime.DtsRuntimeException: The element cannot be found in a collection.
---> System.Runtime.InteropServices.COMException (0xC0010009): The element cannot be found in a collection.
bij Microsoft.SqlServer.Dts.Runtime.Wrapper.IDTSVariables100.get_Item(Object Index)
bij Microsoft.SqlServer.Dts.Runtime.Variables.get_Item(Object index)
--- Einde van intern uitzonderingsstackpad ---
bij Microsoft.SqlServer.Dts.Runtime.Variables.get_Item(Object index)
bij ST_f32fc12b60f34bebbbdfc0c5e5b40a96.vbproj.ScriptMain.Main()
--- Einde van intern uitzonderingsstackpad ---
bij System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
bij System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
bij System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
bij System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
bij System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
bij System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, CultureInfo culture)
I have tried to convert this ActiveX script into a SSIS script task in VB but I know hardly any VB... So I'm wondering what the best course of action for me is, should I try to convert it into the script task like I am trying now, if so, how do I make it
work?
Any help would be really really welcome.
This is the original ActiveX script that needs to be converted:
' Visual Basic ActiveX Script
Function Main()
Dim sEnvironm
Dim sServer
Dim sSourceFile
Dim sSourcePath
Dim sBackupPath
Dim sErrorPath
Dim sFileName
Dim sUDLPath
' Set vars
' First 2 are depending on the server and db
' FILL IN THE RIGHT VALUES
sEnvironm = "MON_Datamart"
sServer = "BrechtProesmans"
' --- DO NOT CHANGE ANYTHING BELOW THIS LINE ---
sSourceFile = "C:\Program Files\Microsoft SQL Server\MON_Datamart\SourceFiles\tbl_L00T1.txt"
sSourcePath = "C:\Program Files\Microsoft SQL Server\MON_Datamart\SourceFiles\"
sBackupPath = "C:\Program Files\Microsoft SQL Server\MON_Datamart\BackupFiles\"
sErrorPath = "C:\Program Files\Microsoft SQL Server\MON_Datamart\ErrorFiles\"
sFileName = "tbl_L00T1.txt"
sUDLPath = "C:\Program Files\Microsoft SQL Server\MON_Datamart\MON_Datamart.udl"
' Initial
FoundError = False
' Get a handle to the Package object.
Set oPackage = DTSGlobalVariables.Parent
' Update DTSConnections
Set oConnection = oPackage.Connections("tbl_L00T1.txt")
oConnection.DataSource = sSourceFile
Set oConnection = oPackage.Connections("Datamart")
oConnection.UDLPath = sUDLPath
Set oConnection = oPackage.Connections("Truncate")
oConnection.UDLPath = sUDLPath
' Update DTSTasks
Set oTask = oPackage.Tasks("DTSTask_DTSDataPumpTask_1").CustomTask
oTask.SourceObjectName = sSourceFile
oTask.DestinationObjectName = sEnvironm & ".dbo.stg_tbl_L00T1"
' Set Global vars
DTSGlobalVariables("SourcePath").Value = sSourceFile
DTSGlobalVariables("BackupPath").Value = sBackupPath
DTSGlobalVariables("ErrorPath").Value = sErrorPath
DTSGlobalVariables("FileName").Value = sFileName
' Clean up.
Set oTask = Nothing
Set oConnection = Nothing
Set oPackage = Nothing
Main = DTSTaskExecResult_Success
End FunctionSet a breakpoint and tell us on what line it dies, at the same time, you can inspect the variable values in the Auto window (if there are) as it merely perhaps is an issue with values not being passed in.
Arthur
MyBlog
Twitter -
Problem with Script Task formatting excel
Hi Experts,
I am creating a package and using Script task to format one excel dimension file, now the problem is if I execute the package from BIDS designer with static values then the package executes fine with excel file formatted perfectly fine but if I execute same package in BPC via Data manager with values used from variables it gives error on script task message:
"Description = System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException (0x800A03EC): Microsoft Office Excel cannot access the file 'E:\PC_MS\Data\Webfolders\CDNPLAN\AdminApp\Stage\Employee.xls'. There are several possible reasons:
u2022 The file name or path does not exist.
u2022 The file is being used by another program.
u2022 The workbook you are trying to save has the same name as a currently open workbook.
at Microsoft.VisualBasic.CompilerServices.LateBinding.LateGet(Object o, Type objType, String name, Object[] args, String[] paramnames, Boolean[] CopyBack)
at Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateGet(Object Instance, Type Type, String MemberName, Object[] Arguments, String[] ArgumentNames, Type[] TypeArguments, Boolean[] CopyBack)
at ScriptTask_2921447fa19c44dfae73d5370828ba94.vbproj.ScriptMain.Main()
Now to crosscheck I commented the dynamic variables from the code and used same static values with Data manager as they are in BIDS but it didn't help, please find the code below and help me in solving this problem or just give me some clue to come out if this:
Thanks & Regards,
Rohit
Code
Public Sub Main()
' Add your code here
'Dim FileName As String = Dts.Variables("MYWEBFOLDERS").Value & Dts.Variables("MYAPPSET").Value & "\AdminApp\Stage\" & Dts.Variables("MYDIMNAME").Value & ".xls" This I commented as it was using dynamic variables
Dim FileName As String = "E:\PC_MS\Data\Webfolders\CDNPLAN\AdminApp\Stage\Employee.xls"
Dim WB As Object ' Workbook
Dim WS As Object 'Worksheet
Dim W As Object 'Window
Dim XL As Object 'Application
XL = CreateObject("Excel.Application")
XL.DisplayAlerts = False
' Open the workbook
WB = XL.Workbooks.Open(FileName)
' WB = GetObject(FileName)
' XL = WB.Parent
' XL.DisplayAlerts = False
WS = WB.Worksheets(1)
W = WB.Windows(WB.Name)
' Change the name of the worksheet to MEMBERS
WS.Name = "MEMBERS"
' Set up the split and freeze the panes
W.SplitRow = 1
W.SplitColumn = 1
W.Split = True
W.FreezePanes = True
' Make it visible
W.Visible = True
' Replace *ID column header with ID
Dim Row1 As Object
Row1 = WS.UsedRange.Rows("1:1")
Dim I As Integer
For I = 1 To Row1.Columns.Count
If Row1.Cells(I, 1).Value = "*ID" Then
Row1.Cells(I, 1).value = "ID"
Exit For
End If
Next
' Paste Values
WS.UsedRange.NumberFormat = "@"
WS.UsedRange.Value = WS.UsedRange.Value
' Change the font of everything to Arial,9
With WS.Cells.Font
.Name = "Arial"
.Size = 9
End With
' Format the top row to be bold and orange
With WS.Rows("1:1")
.Font.Bold = True
.Interior.ColorIndex = 44 'orange
End With
' Auto-fit all the columns
WS.Cells.EntireColumn.AutoFit()
' Convert to Excel format
Const xlNormal = -4143
WB.Parent.DisplayAlerts = False
WB.SaveAs(FileName:=FileName, FileFormat:=xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False, CreateBackup:=False)
' Close and save changes
WS = Nothing
WB.Close()
W = Nothing
' Quit Excel
XL.Quit()
XL = Nothing
Dts.TaskResult = ScriptResults.Success
End SubHi,
If you do not define GLOBAL VARIABLE in your BPC package and BIDS, why don't you try to have it? you should specify the webfolder and file name in advanced script, then you also need to create global variable as text type in BIDS.
I saw many cases BPC does not pass the dynamic variable to BIDS, therefore I changed the type of variable as the Global variable and it works for me.
Regards,
YH Seo -
Error While executing a SSIS package which contains a script task through SQL Server Agent job
Hi,
I have a SQL Server 2012 SSIS package with a script task along with other tasks [data flow, execute sql tasks ]. When I manually executed the job through BIDS, its completed successfully.
Then I have automated the execution of the package through SQL Server Agent Job. But when I executed the package through SQL Agent job, it runs successfully for all the tasks except script task. When it comes to execute the Script Task, it is getting failed
with the below error message.
"Error: 2012-08-29 12:45:14.67
Code: 0x00000001
Source: Script Task
Description: Exception has been thrown by the target of an invocation.
End Error
DTExec: The package execution returned DTSER_FAILURE (1).
Started: 12:45:10 PM
Finished: 12:45:14 PM
Elapsed: 4.353 seconds
I have installed the SSIS on the 64-bit environment and SSIS service is running. Also I tried to run the job through 32 bit [job option] but I am getting the above error in all cases.
Any help will be greatly appreaciated !
Thanks,
Navin
- naveen.reddyHi Arthur,
My script task access the excel files in a network share, refresh them all and save them. When I execute the ETL manually or thru DTEXEC, it is executing successfully. I am facing the issue when I am executing thru SQL Agent Job only. Logging also showing
the same error.
"Error: 2012-08-23 12:45:14.67
Code: 0x00000001
Source: Script Task
Description: Exception has been thrown by the target of an invocation.
End Error
DTExec: The package execution returned DTSER_FAILURE (1).
Started: 12:45:10 PM
Finished: 12:45:14 PM
Elapsed: 4.353 seconds
- naveen.reddy -
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 ADVANCEThank 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 -
Getting error message when i am trying to update the excel file using script task in ssis package
Hi Guys,
I am getting error message when I am trying to update the excel. Please find the error messages as below
Error at Update File [Update File]: Failed to compiled scripts contained in the package. Open the package in SSIS Designer and resolve the compilation errors.
Error at Update File [Update File]: BC30002 - Type 'Microsoft.Office.Interop.Excel.Application' is not defined., ScriptMain.vb, 32, 32
Error at Update File [Update File]: BC30002 - Type 'Microsoft.Office.Interop.Excel.Workbook' is not defined., ScriptMain.vb, 33, 25
Error at Update File [Update File]: The binary code for the script is not found. Please open the script in the designer by clicking Edit Script button and make sure it builds successfully.
Warning at Update File [Update File]: Found SQL Server Integration Services 2008 Script Task "ST_050fcae972904039b4f0fe59b7528ece" that requires migration!
and the code that I am using is
Dell - Internal Use - Confidential
' 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 Microsoft.Office.Interop.Excel
<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.TaskResult = ScriptResults.Success
'Dim proc As System.Diagnostics.Process
'kill all instances of excel
'For Each proc In System.Diagnostics.Process.GetProcessesByName("EXCEL")
' proc.Kill()
'Next
Dim excelnacomm As
New Microsoft.Office.Interop.Excel.Application
Dim wbnacomm As Microsoft.Office.Interop.Excel.Workbook
wbnacomm = excelnacomm.Workbooks.Open("http://test.xlsx")(renamed
the excel)
wbnacomm.RefreshAll()
wbnacomm.Save()
wbnacomm.Close()
excelnacomm.Quit()
Runtime.InteropServices.Marshal.ReleaseComObject(excelnacomm)
End Sub
End
Class
Please let me know what could be the reason
Smash126Download:
Microsoft Office 2010: Primary Interop Assemblies Redistributable
How to: Add or Remove References By Using the Add Reference Dialog Box / How to:
Add and Remove References in Visual Studio (C#)
Olaf Helper
[ Blog] [ Xing] [ MVP] -
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
-
CUP Issue: Unable to see the expired roles
Hi All, I am experiencing a problem which is explained below: A ticket was raised in CUP for deleting role(s) in backend system which are expired. When I accessed this ticket to do the needful, I am surprised to see that the Expired roles are not vis
-
HT4236 Hello. I need to know how to sync pictures from my PC to my Iphone 3gs?
I just recently bought a iphone 3gs updated with 5.0 and I want to transfer pictures from my computer to the iphone. how do i do that using a PC? I also would like to know how to transfer text messages from my old 3g to this 3gs. Can anyone guide me
-
Windows 7 Areo/Aqua Snap won't snap Reader X
Hi, I just downloaded Adobe Reader X and the Windows 7 snap functionality won't work with it. It works for all other applications so I think it's an issue with the Reader. Am I missing something? I don't think it should matter, but I'm using AquaSna
-
Editable ALVs vs Table Controls
Hi... Can somebody give me the advantages and disadvantages of using editable ALV's (ALV grid) over table controls? I've got a requirement from my client side wherein I have to replace all table controls with editable ALV's and prior to that, I've t
-
Need document for User profile.
Hi, Can you please let me know where i will get the complete document for User profile. Thanks Utsav