How do I prompt for input from an SSIS package? - sql

I want to be able to have a sql query in my DTSX package and I want to be able to have some sort of prompt to update the value of a null column. See what I have below:
UPDATE SF1411
SET [QuoteNumber] = '123456'
, [ItemNumber] = '123654-100'
, [DeleteItem] = 'NO'
WHERE [QuoteNumber] = '0'
I want to be able to be prompted for the QuoteNumber and ItemNumber, then have the script update as needed. Is this possible and if so how can I do it?

This can be acheived as below: This will be in your intial script component.
System.Windows.Forms.Form frm = new Form();
TextBox txt = new TextBox();
Button inputset = new Button();
public void Main()
{
inputset.Text = "Set Variable Value";
inputset.Width = 200;
inputset.Height = 100;
inputset.Click += new EventHandler(inputset_Click);
txt.Name = "Input";
frm.Controls.Add(txt);
frm.Controls.Add(inputset);
frm.ShowDialog();
MessageBox.Show(Dts.Variables["Value1"].Value.ToString());
Dts.TaskResult = (int)ScriptResults.Success;
}
void inputset_Click(object sender, EventArgs e)
{
Dts.Variables["Value1"].Value = Convert.ToInt32(txt.Text);
frm.Close();
}
This should be the initial component in your package to set the variable value or construct you SQL Command.

In general, an SSIS package is not used interactively. Your cleanest solution is a custom solution that gets the input from the user, and then launches the SSIS package.
A simpler alternative is using Package Configurations. You can store the user input in an external location (XML file, SQL Server database, and others) and the SSIS package will load the value at run time.

Related

execute ssis package in MVC

Afternoon,
Is it possible to execute a SSIS package using MVC? What I am creating is a web application and it would have a button, once clicked the SSIS package runs.
The SSIS project is already set up and deployed on the MSSQL server.
SQL Server 2012+ offers a fantastic mechanism for managing packages and their execution via the Integration Services catalog, SSISDB.
The following code provides an example of running the package (Package2.dtsx) from the MyProjectName SSIS project living under the Demo folder with an IntensityLevel package parameter turned up to 11.
DECLARE #execution_id bigint;
EXEC SSISDB.catalog.create_execution
#package_name = N'Package2.dtsx'
, #execution_id = #execution_id OUTPUT
, #folder_name = N'Demo'
, #project_name = N'MyProjectName'
, #use32bitruntime = False
, #reference_id = NULL;
DECLARE #var0 int = 11;
EXEC SSISDB.catalog.set_execution_parameter_value
#execution_id
, #object_type = 30
, #parameter_name = N'IntensityLevel'
, #parameter_value = #var0;
DECLARE #var1 smallint = 1;
EXEC SSISDB.catalog.set_execution_parameter_value
#execution_id
, #object_type = 50
, #parameter_name = N'LOGGING_LEVEL'
, #parameter_value = #var1;
EXEC SSISDB.catalog.start_execution
#execution_id;
The easy way to get a sample of how the above SQL should be built out is to open SQL Server Management Studio (SSMS) and configure a run of the SSIS package. Navigate to the Integration Services Catalog and find the package you want to run. Right click and select Execute...
The Configuration menu opens up and find the parameter(s) you want to specify. Provide a sample value but DO NOT CLICK OK. Instead, click that Script button and specify script to new window (or clipboard)
Now you have the exact commands that SSMS would have issued to run your package. Take that code, use your parameterization method of choice for having your MVC program stubbing in the correct runtime value for your parameter and then wrap all of that TSQL up in a simple database call (ole, ado, odbc it won't matter)
You could just create a stored procedure which you can call from your MVC app with SQLClient or so..
In this stored procedure you can then launch the SSIS package.(see below link for more detailed description on how to do this)
https://www.mssqltips.com/sqlservertip/2992/how-to-execute-an-integration-services-ssis-package-from-a-sql-server-stored-procedure/
I created a stored procedure which runs the SSIS package. Within MVC it calls the stored procedure -
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index()
{
//code that updates DB
#region Run Stored Procedure
//connect to the SQL server
var connection = new SqlConnection(_configuration.GetConnectionString("DatabaseConnection"));
//command that runs procedure on the SQL server
var command = new SqlCommand("RebuildSelection", connection)
{
CommandType = CommandType.StoredProcedure,
CommandText = "RebuildSelection"
};
//get text from stored procedure to show success/error messages
SqlParameter text = new SqlParameter("#Text", SqlDbType.NVarChar, 1000)
{
//output as its displayed to the user
Direction = ParameterDirection.Output
};
//add the params
command.Parameters.Add(text);
connection.Open();
//run query
command.ExecuteNonQuery();
//used to return success/error messages to user
ViewData["Message"] = text.Value;
connection.Close();
#endregion
return View();
}
This link was a big help for creating the procedure.
This one helped in returning message to the user.
C# can be used to execute a package deployed to SSISDB as follows. The initial connection created in the SqlConnection object will be the server where the package is deployed to. In the example below, the ObjectType of 30 is used for a package parameter. This can be changed to 20 for a parameter at the project level.
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.IntegrationServices;
using System.Collections.ObjectModel;
string folder = "Folder of Package";
string project = "Project Of Package";
string packageName = "PackageName.dtsx";
string packageParameter = "ParameterValue";
// server where package is deployed
SqlConnection connString = new SqlConnection(#"Data Source=ServerWherePackageDeployed;Initial Catalog=SSISDB;Integrated Security=SSPI;");
IntegrationServices ssisConnString = new IntegrationServices(connString);
//create PackageInfo object for package to execute
Microsoft.SqlServer.Management.IntegrationServices.PackageInfo package = ssisConnString.Catalogs["SSISDB"].Folders[folder].Projects[project].Packages[packageName];
Collection <Microsoft.SqlServer.Management.IntegrationServices.PackageInfo.ExecutionValueParameterSet> parameterList = new Collection<Microsoft.SqlServer.Management.IntegrationServices.PackageInfo.ExecutionValueParameterSet>();
//set logging level to basic
parameterList.Add(new Microsoft.SqlServer.Management.IntegrationServices.PackageInfo.ExecutionValueParameterSet { ObjectType = 50, ParameterName = "LOGGING_LEVEL", ParameterValue = 1 });
parameterList.Add(new Microsoft.SqlServer.Management.IntegrationServices.PackageInfo.ExecutionValueParameterSet { ObjectType = 30, ParameterName = "ParameterName", ParameterValue = packageParameter });
package.Execute(false, null, parameterList);

Setting openFileDialog to variable string

I am trying to create a small GUI that will rename a file (eventually a batch of files). I am using C++ and Windows user (Visual Studio Community 2015).
I have a btnSelectFiles button with which I want to open a file selection GUI.
I am trying to use openFileDialog but am struggling to set the file name to a string variable.
The code I am using:
public:
void btnSelectFiles_Click(Object^ /*sender*/, System::EventArgs^ /*e*/)
{
IO::Stream^ myStream;
OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;
openFileDialog1->InitialDirectory = "c:\\";
openFileDialog1->Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1->FilterIndex = 2;
openFileDialog1->RestoreDirectory = true;
if (openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK)
{
if ((myStream = openFileDialog1->OpenFile()) != nullptr)
{
// Insert code to read the stream here.
myStream->Close();
}
}
/*String test = openFileDialog1;*/
}
One of my many tries was to use:
String test = openFileDialog1
I also tried:
String test = openFileDialog1.FileName
But received an expression must have class type error.
Please can someone help me solve this and thus help my understanding on the matter. The book I have picked up does not cover this and I have struggled to find help online.
Since you are using c++/CLI ( rather than C++ ) you must write
String^ test = new String( openFileDialog1.FileName );

SSIS - how to access system variables in Script Task

Can anyone please advice how to access/read system variables in Script Component (e.g I want to package name from this variable System::PackageName in Script Component)
In the Script Task Editor, provide the variable names you want to access (for example System::PackageName) in the ReadOnlyVariables field.
From the script, in the C# example, use this:
public void Main()
{
bool fireAgain = true;
// Read the variable
String PackageName = (String)Dts.Variables["System::PackageName"].Value;
// Post the value to progress results
Dts.Events.FireInformation(3, "Package name:", PackageName, "", 0, ref fireAgain);
Dts.TaskResult = (int)ScriptResults.Success;
}
The results:

SSIS ScriptTask change Value property of Variable

I try to simply change value of SSIS variable doing this code in ScriptTask:
string path = Dts.Connections["BazyPobrane"].ConnectionString.ToString();
string[] nameZIParray = Directory.GetFiles(path, "*.ZIP");
string[] nameRARarray = Directory.GetFiles(path, "*.RAR");
foreach (string nameZIP in nameZIParray) //search new ZIP
{
if (File.GetCreationTime(nameZIP) > DateTime.Now.AddDays(-1))
{
Dts.Variables["User::NazwaPliku"].Value = Path.GetFileName(nameZIP);
}
}
foreach (string nameRAR in nameRARarray) //search new RAR
{
if (File.GetCreationTime(nameRAR) > DateTime.Now.AddDays(-1))
{
Dts.Variables["User::NazwaPliku"].Value = Path.GetFileName(nameRAR);
}
}
Dts.TaskResult = (int)ScriptResults.Success;
After executing ScriptTask it simply don't change the variable Value. Debug mode seems fine. Maybe i miss some component settings?
Thx!
Some things to check:
Are you sure the variable isn't changing? If you put a subsequent script task with a MessageBox in place, does it show the correct value?
I don't think you need the variable type, i.e. remove "user::"
Make sure the variable is in the ReadWriteVariables property, as suggested by #OcasoP
What's the scope of the variable? Make sure you don't have two copies at different scopes, or that at least the one you do have is visible from the scope of the script
You could try locking the variable before writing to it (which should be equivalent to (3) above)
Code example for the last point:
IDTSVariables100 variables = null;
this.VariableDispenser.LockOneForWrite("NazwaPliku",ref variables);
variables[0].Value = myValue;
variables.Unlock();
debug your script task adding MsgBox(variable_name) and see its value through the execution.
Best debugging option :)

Related on Custom Timer Job in sharepoint 2010

How to create a custom job to export an Excel file in a list which has only 2 columns(Title,Description) in a sharepoint 2010?i want the coding part of this question?
Reading Data from Excel and writing into a sharepoint list,this has to be done through custom job coding
Thanks in Advance...
Naresh
Use OpenXMLSDK - a free download that needs to be installed on the server.
[...]
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
public class OffBookAssetLibraryEventReceiver : SPItemEventReceiver
{
public override void ItemUpdated(SPItemEventProperties properties)
{
// This if statement is to work around the sharepoint issue of this event firing twice.
if (properties.AfterProperties["vti_sourcecontrolcheckedoutby"] == null && properties.BeforeProperties["vti_sourcecontrolcheckedoutby"] != null)
{
byte[] workSheetByteArray = properties.ListItem.File.OpenBinary();
Stream stream = new MemoryStream(workSheetByteArray);
Package spreadsheetPackage = Package.Open(stream, FileMode.Open, FileAccess.ReadWrite);
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(spreadsheetPackage);
SharedStringTablePart shareStringTablePart = spreadsheetDocument.WorkbookPart.SharedStringTablePart;
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.Sheets;
try
{
foreach (Sheet sheet in sheets)
{
var worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(sheet.Id.Value);
IEnumerable<Row> rows = worksheetPart.Worksheet.GetFirstChild<SheetData>().Elements<Row>();
if (rows.Count() > 0)
{
int rowNumber = 0;
foreach (Row row in rows)
{
IEnumerable<Cell> cells = row.Elements<Cell>();
Cell title = null;
Cell description = null;
title = cells.ToArray()[0];
description = cells.ToArray()[1];
// This is the code used to extract cells from excel that are NOT inline (Inline cells are decimal and dates - although dates are stored as int)
int index = int.Parse(title.CellValue.Text);
string titleString = spreadsheetDocument.WorkbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(index).InnerText;
index = int.Parse(description.CellValue.Text);
string descriptionString = spreadsheetDocument.WorkbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(index).InnerText;
//Insert into your sharepoint list here!
}
}
}
}
}
}
}
I recommend putting this code into an event receiver on the document library (as seen above).
Have you looked at Excel REader for .NET
http://exceldatareader.codeplex.com/
Open the Excel File
Take a look at the Excel Services for SharePoint 2010. There is a walkthrough explaining the required steps to open an excel file.
SharePoint Custom Timer Job
To create a custom SharePoint timer job, you have to create a class that inherits from SPJobDefinition. A complete tutorial can be found in this blog post: Creating Custom Timer Job in SharePoint 2010.