After I get the server jobs and I got each job steps I want to get the connection string related to each step as you could find it while opening SQL management studio in jobs like this:
is there is a suitable way to get the connection strings for each package by C# code?
ServerConnection conn = new ServerConnection("localhost");
//new SqlConnection("data source=localhost;initial catalog=CPEInventory_20101122;integrated security=True;"));
Server server = new Server(conn);
JobCollection jobs = server.JobServer.Jobs;
var stepInformationsDetailsList = new List<StepInformationsDetails>();
foreach (Job job in jobs)
{
foreach (JobStep jobstep in job.JobSteps)
{
stepInformationsDetailsList.Add(new StepInformationsDetails() {
ServerName = job.Parent.MsxServerName,
ReportName = job.Name,
StepName = jobstep.Name,
Command = jobstep.Command,
Schedual = jobstep.DatabaseName,
StepID = jobstep.ID
});
}
}
dataGridView1.DataSource = stepInformationsDetailsList;
That data will all be in your Command variable. When you override/add anything on the job step tabs, the net result is that the command line passed to dtexec has those values. The UI is simply slicing arguments out of the command column in the msdb.dbo.sysjobsteps table to link them to various tabs.
On your localhost, this query ought to return back the full command line.
SELECT
JS.command
FROM
dbo.sysjobs AS SJ
INNER JOIN dbo.sysjobsteps AS JS
ON JS.job_id = SJ.job_id
WHERE
sj.name = 'Concessions made by Simba Auto-Report';
Since you are not overriding the value of the Connection Manager 'Simba Replica...', it is not going to show up in the output of the command. If it was, you'd have a string like /SQL "\"\MyFolder\MyPackage\"" /SERVER "\"localhost\sql2008r2\"" /CONNECTION SYSDB;"\"Data Source=SQLDEV01\INT;Initial Catalog=SYSDB;Provider=SQLNCLI10.1;Integrated Security=SSPI;Auto Translate=False;\"" /CHECKPOINTING OFF /REPORTING E The /CONNECTION section would correlate to your 'Simba Replica...' value.
I suspect, but do not know, that the UI is examining the SSIS package via the API Microsoft.SqlServer.Dts.Runtime and identifying all the Connection Manager, via Connections property to build out that dialog.
Related
In package MainPackage.dtsx I have 10 connected Connection managers in that package. 9 are "OLE DB\Oracle Provider for OLE DB" and 1 is "OLE DB\SQL Server Native Client 11.0". In project, I have one C# Script, that create package NewPackageThatNotWillSaved.dtsx with dataFlow that take rows from table A, add column with datetime, copy to table B and count copied rows. And execute package NewPackageThatNotWillSaved.dtsx. In order for the package to be executed, I add 2 connection managers to the package(Source and Destination are connection managers from package MainPackage.dtsx by Dts.Connections) by connection string.
Here the problem. Connection string from SQL Server work fine, but connection string from Oracle throw error DTS_E_CAN NOT ACQUIRE CONNECTION FROM CONNECTION MANAGER every time, when I srcDesignTimeComponent.AcquireConnections(null); (IDTSDesigntimeComponent100 srcDesignTimeComponent). I can`t use password for oracle connection string because 9 different oracle servers have 9 different passwords and password in connection sting sounds bad.
Some C# code that I use:
// Create package
Application app = new Application();
Package package = new Package();
// Get connection manager
ConnectionManager sourceConnection = null;
ConnectionManager destinationConnection = null;
foreach (ConnectionManager conn in Dts.Connections)
{
if (conn.Name.Equals(sourceConnectionName))
{
sourceConnection = conn;
}
if (conn.Name.Equals(destinationConnectionName))
{
destinationConnection = conn;
}
}
// Create dataFlow
Executable e = package.Executables.Add("STOCK:PipelineTask");
TaskHost thMainPipe = e as TaskHost;
MainPipe dataFlowTask = thMainPipe.InnerObject as MainPipe;
thMainPipe.Name = dataFlowName;
// Add connection manager for OLE DB Source
ConnectionManager sourceConn = package.Connections.Add("OLEDB");
sourceConn.Name = sourceConnection.Name + "_src";
sourceConn.ConnectionString = sourceConnection.ConnectionString;
// Add OLE DB Source
IDTSComponentMetaData100 source = dataFlowTask.ComponentMetaDataCollection.New();
source.ComponentClassID = "DTSAdapter.OleDbSource";
source.ValidateExternalMetadata = true;
IDTSDesigntimeComponent100 srcDesignTimeComponent = source.Instantiate();
srcDesignTimeComponent.ProvideComponentProperties();
// Set connetcion manager for OLE DB Source
source.RuntimeConnectionCollection[0].ConnectionManager = DtsConvert.GetExtendedInterface(sourceConn); ;
source.RuntimeConnectionCollection[0].ConnectionManagerID = sourceConn.ID;
// Setting propreties
srcDesignTimeComponent.SetComponentProperty("AccessMode", 2);
srcDesignTimeComponent.SetComponentProperty("SqlCommand", sqlQuery);
srcDesignTimeComponent.AcquireConnections(null); // Throw ERROR -1071611876
srcDesignTimeComponent.ReinitializeMetaData();
srcDesignTimeComponent.ReleaseConnections();
Edit 1: Maybe exist better way to AcquireConnections from exist connected connection manager from MainPackage.dtsx?
I am having a C# API that takes an Excel sheet (filePath, sheetName) as an input and return the sheet content as the output in JSON form.
The API works fine when I try to test it on my machine that contains windows server 2016 installed on it. But it always fail when I try to send the file path and sheet name from the form.
This is my API Code...
public IHttpActionResult GetSheetData(string filePath, string sheetName)
{
try
{
var connectionString = $#"
Provider=Microsoft.ACE.OLEDB.12.0;
Data Source={filePath};
Extended Properties=""Excel 12.0 Xml;HDR=YES""";
using (var conn = new OleDbConnection(connectionString))
{
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandText = $#"SELECT * FROM [{sheetName}$]";
using (var DRow = cmd.ExecuteReader())
{
var query = DRow.Cast<DbDataRecord>().Select(row => new
{
name = row[0],
age = row[1],
email = row[2]
});
var JSON = JsonConvert.SerializeObject(query);
return Ok(JSON);
}
}
}
catch (Exception) { return Ok(HttpStatusCode.NotFound); };
}
The JSON result is returned perfectly when I test the API on the Server, But when I try to test it using this form..
It always returns 404 (Not Found).
This is my sample excel sheet data.
Any Ideas?!
I have found the solution to my Issue, and I wanted to share with you.
The Issue was all about the access rights of the IIS.
When I try to access a file on my local machine or in the clients machine, the IIS App Pool must have an access rights on that location.
So, I used the following steps.
Browse to the folder containing the file -to be read-
Right Click the folder and select 'Properties'
Under 'Security' Tab, select Edit.
In the 'Edit' Window select 'Add' -> 'Advanced' -> Find Now
Look up the result names while you find the user related to IIS -[IIS-IUsers]- in my case.
allow access controls to the folder -full access- or -Read and Write- etc...
I Hope this is helpful for you.
Thank you all.
I am having some issues with a class that I have created to perform different database commands.
1st) The program is local ran, and will only run locally. It will only ever connect to the database on the localhost.
Therefore I have a simple class setup, called databaseConnector that allows me to pass a string to it with the required Mysql query to perform the different functions.
For instance.
I use:
var db = new databaseConnector();
db.Update("UPDATE * WHERE.....");
However, it seems if I ever want to use a different query, or another query, it's not working and throwing errors.
For instance.
var db = new databaseConnector();
db.Update("UPDATE * WHERE...");
db.INSERT("INSERT INTO * WHERE.....");
Will give me an error on the insert execution. Any ideas why? I have resorted to creating it again. So I have to redo:
db = new databaseConnector();
to then use the Insert command.
Here is an example of my insert function.
public void Insert(string query)
{
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
Now that I think about it. Should I call my db.openConnection() before doing it. Since when I initialize it in the first var db = new databaseConnection(), it's opening? And then in each function it's closing it, but only checking if it's open, instead of attempting to open, doing query, then closing.
I am trying to build a .NET web application using SQL to query AS400 database. This is my first time encountering the AS400.
What do I have to install on my machine (or the AS400 server) in order to connect?
(IBM iSeries Access for Windows ??)
What are the components of the connection string?
Where can I find sample codes on building the Data Access Layer using SQL commands?
Thanks.
You need the AS400 .Net data provider. Check here:
https://www-01.ibm.com/support/docview.wss?uid=isg3T1027163
For connection string samples, check here:
https://www.connectionstrings.com/as-400/
Also, check out the redbook for code examples and getting started.
http://www.redbooks.ibm.com/redbooks/pdfs/sg246440.pdf
Following is what I did to resolve the issue.
Installed the IBM i Access for Windows. Not free
Referred the following dlls in the project
IBM.Data.DB2.iSeries.dll
Interop.cwbx.dll (If Data Queue used)
Interop.AD400.dll (If Data Queue used)
Data Access
using (iDB2Command command = new iDB2Command())
{
command.Connection = (iDB2Connection)_connection;
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue(Constants.ParamInterfaceTransactionNo, 1);
command.CommandText = dynamicInsertString;
command.ExecuteScalar();
}
Connection String
<add name="InterfaceConnection"
connectionString="Data Source=myserver.mycompany.com;User ID=idbname;Password=mypassxxx;
Default Collection=ASIPTA;Naming=System"/>
UPDATE
i Access for Windows on operating systems beyond Windows 8.1 may not be supported. Try the replacement product IBM i Access Client Solutions
IBM i Access Client Solutions
As mentioned in other answers, if you have the IBM i Access client already installed, you can use the IBM.Data.DB2.iSeries package.
If you don't have the IBM i Access software, you can leverage JTOpen and use the Java drivers. You'll need the nuget package JT400.78 which will pull in the IKVM Runtime.
In my case I needed to query a DB2 database on an AS400 and output a DataTable. I found several hints and small snippets of code but nothing comprehensive so I wanted to share what I was able to build up in case it helps someone else:
using com.ibm.as400.access;
using java.sql;
var sql = "SELECT * FROM FOO WITH UR";
DriverManager.registerDriver(new com.ibm.as400.access.AS400JDBCDriver());
Connection conn = DriverManager.getConnection(
"jdbc:as400:" + ServerName + ";prompt=false", UserName, Password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData md = rs.getMetaData();
int ct = md.getColumnCount();
DataTable dt = new DataTable();
for(int i=1; i<=ct; i++)
dt.Columns.Add(md.getColumnName(i));
while (rs.next())
{
var dr = dt.NewRow();
for (int i = 1; i <= ct; i++)
dr[i - 1] = rs.getObject(i);
dt.Rows.Add(dr);
}
rs.close();
The conversion from RecordSet to DataTable is a little clunky and gave me bad flashbacks to my VBScript days. Performance likely isn't blinding fast, but it works.
Extremely old question - but this is still relevant. I needed to query our AS/400 using .NET but none of the answers above worked and so I ended up creating my own method using OleDb:
public DataSet query_iseries(string datasource, string query, string[] parameterName, string[] parameterValue)
{
try
{
// Open a new stream connection to the iSeries
using (var iseries_connection = new OleDbConnection(datasource))
{
// Create a new command
OleDbCommand command = new OleDbCommand(query, iseries_connection);
// Bind parameters to command query
if (parameterName.Count() >= 1)
{
for (int i = 0; i < parameterName.Count(); i++)
{
command.Parameters.AddWithValue("#" + parameterName[i], parameterValue[i]);
}
}
// Open the connection
iseries_connection.Open();
// Create a DataSet to hold the data
DataSet iseries_data = new DataSet();
// Create a data adapter to hold results of the executed command
using (OleDbDataAdapter data_adapter = new OleDbDataAdapter(command))
{
// Fill the data set with the results of the data adapter
data_adapter.Fill(iseries_data);
}
return iseries_data;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
And you would use it like so:
DataSet results = query_iseries("YOUR DATA SOURCE", "YOUR SQL QUERY", new string[] { "param_one", "param_two" }, new string[] { "param_one_value", "param_two_value"});
It returns a DataSet of the results returned. If anyone needs/wants a method for inserting/updating values within the IBM AS/400, leave a comment and I'll share...
I'm using this code and work very good for me!
Try
Dim sqltxt As String = "SELECT * FROM mplib.pfcarfib where LOTEF=" & My.Settings.loteproceso
dt1 = New DataTable
Dim ConAS400 As New OleDb.OleDbConnection
ConAS400.ConnectionString = "Provider=IBMDA400;" & _
"Data Source=192.168.100.100;" & _
"User ID=" & My.Settings.usuario & ";" & _
"Password=" & My.Settings.contrasena
Dim CmdAS400 As New OleDb.OleDbCommand(sqltxt, ConAS400)
Dim sqlAS400 As New OleDb.OleDbDataAdapter
sqlAS400.SelectCommand = CmdAS400
ConAS400.Open()
sqlAS400.Fill(dt1)
grid_detalle.DataSource = dt1
grid_detalle.DataMember = dt1.TableName
Catch ex As Exception
DevExpress.XtraEditors.XtraMessageBox.Show("Comunicación Con El AS400 No Establecida, Notifique a Informatica..", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End Try
I recently found the ADO.Net driver available on NuGet. I have the iSeries client access installed on my PC, so I can't say if it works as a standalone, but it does connect. Theonly problem is I can't actually see any tables or procedures. I think there may be a schema or library or something I still haven't gotten down to. I will post if I find the answer. Meanwhile I can still get to the server and write most of my code with the NuGet adapter.
Check out http://asna.com/us/ as they have some development tools working with SQL and the AS400.
I think I have a straight forward question. I'm writing a system that allows users from company A to single sign on to the system and for this I go back to the central database of users at company A and validate the user credentials passed to me.
Currently my implementation involves building up my query using a stringbuilder and then passing the string as command text. My question is; is there a nicer way of doing this. below is my code;
public User LoginSSO(string UserName, Int32 sectorCode)
{
using (OdbcConnection con = new OdbcConnection(ConfigurationManager.ConnectionStrings["ComapnyA"].ConnectionString))
{
con.Open();
StringBuilder sb = new StringBuilder();
sb.AppendLine("Select mx.Id, mx.UserName, mx.firstname,mx.surname,mx.sectorCode,");
sb.AppendLine("mx.deleteFlag, dn.sectorGroupCode, dn.region, dn.district");
sb.AppendLine("from users mx");
sb.AppendLine("Inner Join sector dn on dn.sectorCode = mx.sectorCode");
sb.AppendLine("Where (mx.UserName = '{0}')");
string commandText = string.Format(sb.ToString(), UserName, sectorCode);
using (OdbcCommand comm = new OdbcCommand(commandText, con))
{
using (OdbcDataReader reader = comm.ExecuteReader())
{
if (reader.Read())
{
User user = new User();
user.Id = Convert.ToInt32(reader["Id"]);
user.Username = Convert.ToString(reader["UserName"]);
user.Firstname = Convert.ToString(reader["firstname"]);
user.Surname = Convert.ToString(reader["surname"]);
_dealerGroupCode = Convert.ToString(reader["sectorGroupCode"]);
_region = Convert.ToInt32(reader["region"]);
_district = Convert.ToInt32(reader["district"]);
_dealerCode = dealerCode;
_accessLevel = AccessLevel.Sector;
return user;
}
}
}
}
return null;
}
I don't like the fact that I am building up my sql which is ultimately a static script. Please note that I can't manipulate the remote server in any way or add any stored procedures to it. For the rest of the app I have been using LINQ but I'm assuming that isn't an option.
This is the most low-level way of querying a database with ADO.NET. Open connection, send command, read out results. You should however use parametrized queries instead of String.Format, since that will open up your program to SQL injection. Just consider what would happen if UserName has a ' character in it. The following would be much better:
string sql = #"Select mx.Id, mx.UserName, mx.firstname, mx.surname,
mx.sectorCode, mx.deleteFlag, dn.sectorGroupCode,
dn.region, dn.district
From users mx
Inner Join sector dn on dn.sectorCode = mx.sectorCode
Where (mx.UserName = ?)";
var command = new OleDbCommand(sql);
command.Parameters.AddWithValue(0, UserName);
If you want a higher level interface, look into DataSets/DataAdapters. They aren't as fancy as LINQ, but they'll give you an easy fill/update, and work with any database adapter. If you're using Visual Studio, you even get a visual designer that can generate Typed Datasets in drag-and-drop fashion that'll give you strong-typed accessors for all your data.
You might also want to look into the native MySql connector classes, instead of using ODBC.
You can use ‘sp_addlinkedserver’ system store procedure to link to the remote server server and then fire a query. following is the sample command.:
EXEC sp_addlinkedserver
#server = ‘SourceServer’
, #Srvproduct = ”
, #Provider = ‘SQLNCLI’
, #datasrc = ‘Remote SQL Server instance name’
I suggest you to please refer following link to know about how to run sql query on remote server http://ashishkhandelwal.arkutil.com/sql-server/sql-query-to-the-remote-sql-server/