SSIS C# Script Task Error - c#

All, I'm using SQL 2014 and Visual Studio 2013.
I have a script task that is not firing. It's being read, but not working. This task creates tables and inserts data into them. I need to do this with a script task as there are 100's of TSV files and the fields may change month to month and it's a pain maintaining individual nodes for each table.
If you look at the code snippet, the message boxes (1) do fire, but the script errors right after - I believe at (2):
The error message is:
I think this error refers to variables that are not accessible in the task or are misspelled, etc. I've checked these Ad nauseam - don't think that's it.
Any help is greatly appreciated. Thank you.

The problem in your code is that you are creating an ADO.NET (C# standard) connection in your script code, but the base of this - DBconn connection manager - is an OLEDB connection manager. These two connections could not be casted into one another.
Suggestions:
If possible, create DBconn connection manager as an ADO.NET. Then your code should work.
In case you have to keep DBconn as an OLEDB connection manager, you have to create a SqlConnection connection in script task based on DBconn. I have done that building connection string for ADO.NET from OLEDB conn string and creating a new SqlConnection with that connection string.
Below is a code sample for function generating Connection String.
using RuntimeWrapper = Microsoft.SqlServer.Dts.Runtime.Wrapper;
using System.Data.OleDb;
using System.Data.SqlClient;
using Microsoft.SqlServer.Dts.Runtime;
static string Get_ManagedConnString(string Src_Name, ConnectionManager CM)
{
if (CM.CreationName != "OLEDB")
throw new Exception(string.Format("Cannot get Conn String from non-OLEDB Conn manager {0}", CM.Name));
RuntimeWrapper.IDTSConnectionManagerDatabaseParameters100 cmParams_Src = CM.InnerObject as RuntimeWrapper.IDTSConnectionManagerDatabaseParameters100;
OleDbConnection oledbConn_Src = cmParams_Src.GetConnectionForSchema() as OleDbConnection;
OleDbConnectionStringBuilder oledbCSBuilder_Src = new OleDbConnectionStringBuilder(oledbConn_Src.ConnectionString);
SqlConnectionStringBuilder sqlCSBuilder_Src = new SqlConnectionStringBuilder();
sqlCSBuilder_Src.DataSource = oledbCSBuilder_Src["Data Source"].ToString();
sqlCSBuilder_Src.InitialCatalog = oledbCSBuilder_Src["Initial Catalog"].ToString();
if (oledbCSBuilder_Src["integrated security"].ToString() == "SSPI")
{
sqlCSBuilder_Src.IntegratedSecurity = true;
}
else
{
sqlCSBuilder_Src.UserID = oledbCSBuilder_Src["User ID"].ToString();
sqlCSBuilder_Src.Password = oledbCSBuilder_Src["Password"].ToString();
}
return sqlCSBuilder_Src.ConnectionString;
}

Related

C# Error Selecting Table in OleDbCommand ...*LIBL not found

I'm trying to make a connection to a DB2 Database sitting on our AS400 (ISeries). I can connect to is successfully using the connection string but once I try to access the Tables I get this error: CPF9812: File SELECT in library *LIBL not found.
At this point I'm just trying to see if i can access the data in the table GLPCT.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Data;
namespace Testing_Connection_to_GLDBFA
{
class Program
{
static void Main(string[] args)
{
string connectionstring = "Provider=IBMDARLA.DataSource.1;Data Source=INFINIUM;Persist Security Info=True;Password=MyPassword;User ID=UserID;Initial Catalog=S06947A4;Default Collection=GLDBFA";
string querySTring = "";
DataTable schema;
int i = 0;
using( OleDbConnection cn = new OleDbConnection(connectionstring))
{
querySTring = "SELECT * FROM GLPCT";
OleDbCommand command = new OleDbCommand(querySTring, cn);
cn.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0].ToString());
i++;
if (i == 20)
break;
}
cn.Close();
}
}
}
}
Any help or guidance is greatly appreciated.
Thanks in advance.
I'd expect to see the following error:
CPF9812: File GLPCT in library USERID not found.
As by default when using SQL naming the system will implicitly qualify unqualified table names with the user ID. For details, see here
It appears you are using an OLE DB provider instead of the .NET provider
If you want to use the library list, you'll need use system naming and ensure that the library list is configured on the connection.
For the OLEDB providers, you want to set the Library List and Naming Convention
<connection>.Open('Provider=IBMDA400;Data Source=SystemA;Library List=lib1,lib2, *USRLIBL;Naming Convention=1', 'Userid', 'Password');
For .NET provider, it's LibraryList and Naming properties.
Lastly, if you want to stay with the OLE DB provider, you might consider using the IBMDASQL instead of the IBMDARLA one.

App.startup path does not work in my visual studio project?

There is no error in this code but when i insert the values,they are not actually inserted in database.
Here is my connection string class :
public class DBConn
{
public static SqlConnection GetConnection()
{
string sDBPath = Application.StartupPath + #"\App_Data\Database3.mdf";
string connStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename='" + sDBPath + "';Integrated Security=True;User Instance=True";
return new SqlConnection(connStr);
}
}
and in this class i call the connection string class :
string query = "INSERT INTO Table1 VALUES('" + textBox1.Text + "')";
SqlConnection con = DBConn.GetConnection();
SqlCommand com = new SqlCommand(query,con);
con.Open();
using (con)
{
com.ExecuteNonQuery();
MessageBox.Show("Insert");
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Do work here; connection closed on following line.
}
Your use of the using statement is not recommended and leads to
problems. You have to instantiate the resource object inside the
using statement! It's scope or lifetime is now limited to the
statement block and will be properly garbage collected. The way you
use it (by passing an already instantiated object into the using
statement) the objects remains valid although not properly accessible
since it was never properly closed or disposed. MSDN - using
statement. So instead of creating the connection and passing it
around your application (bad practice) you should create the
connection settings (connection string) and the query and use
them to create a connection resource inside a using statement
everytime you need a connection. This way the resource is
always correctly disposed. The provided link gives you an
example how to use a using statement.
Check your connection string well if all provided information is
valid or all needed information is provided (e.g. username and password).
Check database settings (e.g. permissions)
SqlConnection class has an event called InfoMessage. In case the
connection produces any warnings or errors you will get notified.
Check your database (e.g. log) for the occurance of errors.

Create .mdf/.sdf database dynamically

How can I with "code" create a new .mdf/.sdf database?
I've tried this:
http://support.microsoft.com/kb/307283
All it does is fail on the ConnectionString. Since I have no connection to a file that exists before I create it, how can I only connect to the SQL Express Server just to create a mdf/sdf database?
I want to be able to just connect to the server and create the file, from there it probably will be easier to create the tables and such.
Any suggestions?
public static void CreateSqlDatabase(string filename)
{
string databaseName = System.IO.Path.GetFileNameWithoutExtension(filename);
using (var connection = new System.Data.SqlClient.SqlConnection(
"Data Source=.\\sqlexpress;Initial Catalog=tempdb; Integrated Security=true;User Instance=True;"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText =
String.Format("CREATE DATABASE {0} ON PRIMARY (NAME={0}, FILENAME='{1}')", databaseName, filename);
command.ExecuteNonQuery();
command.CommandText =
String.Format("EXEC sp_detach_db '{0}', 'true'", databaseName);
command.ExecuteNonQuery();
}
}
}
Change Catalog=tempdb to Catalog=master, its good worked
Sample use:
var filename = System.IO.Path.Combine("D:\\", "testdb.mdf");
if (!System.IO.File.Exists(filename))
{
CreateSqlDatabase(filename);
}
Regarding .sdf files (SQL Server CE), you can use the SqlCeEngine class to create a new database, as described in this MSDN article.
Create .sdf database
using System.Data.SqlServerCe;
using System.IO;
string folderPath="D:\\Compact_DB"
string connectionString;
string fileName =folderPath+"\\School.sdf";
string password = "12345";
if (File.Exists(fileName))
{
File.Delete(fileName);
}
connectionString = string.Format("DataSource=\"{0}\"; Password='{1}'", fileName, password);
SqlCeEngine obj_ceEngine = new SqlCeEngine(connectionString);
obj_ceEngine.CreateDatabase();
Make sure you have a valid connection string.
The database/catalog that you need must be set to a valid database, usually this can be the "master" which is always available and since you will be using master to create a database.
If you need to create a database from scratch programmatically i normal go into the SQL Server Management Studio and create it through the gui in a first step. But instead of clicking on the OK button in the bottom right, i click on the Script button in the top toolbar. This will give me a complete sql script for creating the database i'd like to have. Then i can alter the script and change the parts i'd like dynamically.
I suppose the problem is in the ConnectionString. It should point to the valid instance of the master db (as in the article you refer to). Make sure it is correct, and it should work.
Use a connectionString with InitialCatalog = master. Since only master has default access to create a database.

commonly integrate a line of code at many places in c#

OK here my piece of code
MySqlConnection conn = new MySqlConnection("Userid=root;pwd=root;port=3306;host=localhost;database=test");
conn.Open();
Due to some issue with the new version of the devart connector i'm using i have to add a line of code OldCompatibility.BinaryAsString = true;
everywhere in my code as shown below
OldCompatibility.BinaryAsString = true;
MySqlConnection conn = new MySqlConnectio("User id=root;pwd=root;port=3306;host=localhost;database=test");
conn.Open();
But the problem is i have to make this change all over my application which have many pages with this piece of code.So is there any way to do this globally so that i dont have to make this change all over my application.
i'm using devart connector 6
Assuming that your connection is remotely similar each time; don't. Keep all your connection logic in one shared method, and use that instead of repeating the connection code everywhere.
public static MySqlConnection Connect() {
OldCompatibility.BinaryAsString = true;
MySqlConnection conn = new MySqlConnection("User id=root;pwd=root;port=3306;host=localhost;database=test");
conn.Open();
return conn;
}
MySqlConnection is your custom class if you put OldCompatibility.BinaryAsString = true in the constructor of MySqlConnection then it would work
Change all your code at once with find and replace using regular expressions:
1.- Hit Ctrl+H to open the “Find and Replace” window Enter your search, replace line breaks with “\n” (no quotes)
2.- Expand “Find options” and check “Use”, select “Regular Expressions” (this also activates the right arrow next to the “Find what” box. It lists a few commands/shortcuts).
For example:
Type this on find:
{MySqlConnection conn = new MySqlConnection}
Then try this on replace:
OldCompatibility.BinaryAsString = true;\n\t\t\1 MySqlConnection conn = new MySqlConnection
This will find all the code that matches the search and add an additional line infront of it. Notice the place holder {...} being replaced with \1
You can use a factory method
public class FactoryMethods
{
public static MySqlConnection GetConfiguredConnection()
{
OldCompatibility.BinaryAsString = true;
MySqlConnection conn = new MySqlConnectio("User id=root;pwd=root;port=3306;host=localhost;database=test");
conn.Open();
return conn;
}
}
And assuming the connection is IDispose-able
using (var myConn = FactoryMethods.GetConfiguredConnection())
{
// Use your connection here
}
You should really consider #minitech's suggestion on using a method, but if you really can't change the code anywhere, there are only really two options I can see;
Extend MySQLConnection to a new class using the same name in another namespace, just changing the constructor to include your line. Then replace only the using line at the top of the file.
If that can't be done, implement a wrapper class in the same manner.
Both these options may fail to work (#1 if the class is final for example, and #2 if the class is passed as a parameter to any functions), but unless you can at least do a global search/replace or implement #minitech's suggestion with a method, I can't see any other way.

I can't connect to my local SQL Server database

I'm currently learning ADO.NET on C#. I'm learning by a book and tutorials that I found online. I wanted to try some of the samples to get myself familiarized with the whole SQL connnection and command objects and so on. Hence, I tried this:
namespace ConsoleApplication
{
class SqlDemo
{
public void InitConnection ()
{
string connString = #"data source=C:\SQL Server 2000 Sample Databases; database=northwnd; integrated security=SSPI";
SqlConnection conn = null;
try
{
conn = new SqlConnection (connString);
conn.Open ();
Console.WriteLine ("DataBase connection established");
}
catch
{
Console.WriteLine ("DataBase connection not established");
}
finally
{
if (conn != null) conn.Close ();
}
Console.ReadKey (true);
}
static void Main (string[] args)
{
SqlDemo d = new SqlDemo ();
d.InitConnection ();
}
}
}
And no matter how I try, I can connect to the local database. "data source=(local)" don't work.
A couple of things:
1) It looks like you may have a typo in your database name. It should probably be:
database=northwind
2) Your data source should be (local) or . OR you may have an instance installed, in which case you may need to include the instance name as well, such as .\SQLExpress or .\SQLServer.
If you wish to connect to a database file using a path:
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;
From: http://www.connectionstrings.com/sql-server-2008
However, you may also need to "Attach" the database to Sql Server. In Management studio, right click the Databases folder and select "Attach..."
If you are using SQL Server 2000, then just put 'local' or simply '.' (exclude the quotes) for the data source. And you have a typo in the database name. It should be 'Northwind'

Categories

Resources