System.Runtime.InteropServices.ExternalException on calling Oracle.DataAccess.Client.OracleConnection.Open() - c#

I have following code to connect to a database using ODP.net:
// connection information removed to protect sensitive information
string host = "******";
string sid = "*****";
string connectDescriptor = string.Format("(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST={0})(PORT=1521))(CONNECT_DATA=(SID={1})))", host, sid);
string username = "*****";
string password = "*****";
string connectionString = string.Format("Data Source={0};User ID={1};Password={2};", connectDescriptor, username, password);
OracleConnection conn = null;
try
{
conn = new OracleConnection(connectionString);
conn.Open();
}
catch (OracleException oraex)
{
MessageBox.Show(oraex.ErrorCode + ": " + oraex.Message);
}
finally
{
conn.Close();
}
Call to Open() throws an error, and I am unable to figure out much about it. oraex.ErrorCode is -2147467259 and oraex.Message is "". Trying to access most members of the thrown exception results in a NullReferenceException.
Also, I can see that the base exception is a System.Runtime.InteropServices.ExternalException.
What is going on here? Because of the InteropServices exception I am guessing that it is something to do with COM.
Extra information
I have just installed ODAC 12c.
Connection information is verified. I can connect to same database using a SilverLight application which uses deprecated System.Data.OracleClient. They are OK.

Sounds like it's something with the oracle client. I've faced similar issues with web projects while the console projects were working just fine.
If you installed 64bit ODAC, then uninstall it completely and try with 32bit. Also double check the target platform at Visual Studio is "32bit". If that works, you can search what was wrong with 64 bit installation.

Related

How to connect to oracle database with ODAC c#

I am using this code but getting an error of 'Object reference not set to an instance of an object.' at con.open() ? what am I doing wrong ?
I have already download and installed ODAC component version 10 , 11 ,12 trying each one at the failure of the latest one but still same error
using Oracle.DataAccess.Client;
namespace WindowsFormsApplication1
{
class OraTest
{
public OracleConnection con = new OracleConnection();
public void Connect()
{
con.ConnectionString = "Data Source=(DESCRIPTION= (ADDRESS = (PROTOCOL = TCP)(HOST =myip) (PORT = myport))(CONNECT_DATA = (SERVER = dedicated)(SERVICE_NAME = mydb)));User ID=myid;Password=mypass;";
con.Open(); //error here
}
public void Close()
{
con.Close();
con.Dispose();
}
}
Please go through this link
Getting Started with Oracle Data Provider for .NET (C# Version)
http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/dotnet/GettingStartedNETVersion/GettingStartedNETVersion.htm
If you add a try/catch block in Connect(), you'll be able to catch the error.
For example:
When opening an oracle connection, connection object is null
I added the try catch block, and it returned ORA12154 - TNS could not
be resolved. After some research, I added an SID to my tnsnames.ora
file in my ODP for .NET Oracle home path, and it worked
See also Troubleshooting Oracle Net Services for troubleshooting possible connection issues from Oracle clients (such as your C# program).
But your first step is absolutely to determine the Oracle-level error (for example, ORA-12543 (could not connect to server host) or TNS-12514 (could not find service name)
MSDN: OracleException Class
public void ShowOracleException()
{
OracleConnection myConnection =
new OracleConnection("Data Source=Oracle8i;Integrated Security=yes");
try
{
myConnection.Open();
}
catch (OracleException e)
{
string errorMessage = "Code: " + e.Code + "\n" +
"Message: " + e.Message;
System.Diagnostics.EventLog log = new System.Diagnostics.EventLog();
log.Source = "My Application";
log.WriteEntry(errorMessage);
Console.WriteLine("An exception occurred. Please contact your system administrator.");
}
}
It's significant that con.ConnectionString = xyz works, but the following `con.Open()" fails. This means .Net is creating the C# object, but Oracle/TNS is failing when you try to use it.
ADDITIONAL SUGGESTIONS:
Re-read
When opening an oracle connection, connection object is null.
Read all of the suggestions, including the one about "Data Source in your connection string".
Focus on your connection string. It couldn't hurt to specify the connection string in your OracleConnection() constructor, if possible. Here's another link:
ODP.NET Connection exception
It would be great if you can verify connectivity from your PC with some other Oracle client, besides your C#/.Net program. To verify you're talking to the right TNS host and service, with the correct username/password. For example, maybe you have SQLDeveloper or sqlplus.
Finally, re-read the TNS troubleshooting link:
https://docs.oracle.com/cd/E11882_01/network.112/e41945/trouble.htm#NETAG016
What worked for me with the same error was to simply switch from the 'plain' Oracle DataAccess library, to the 'Managed' version.
This is an extemely easy change to make -
Add a Reference in your c# project to the Oracle.ManagedDataAccess library
Replace the existing use statements at the top of your Oracle client code with the following:
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.Types;
Include the Oracle.ManagedDataAccess.dll file with your exe

SEHException on OleDb connection open

I'm developing a small application that will simplify logging, it does so by adding some inputs to an MS Access database through OleDB.
let private conn = new OleDbConnection(connectionString)
let private submitCmd date wins =
let cmd = new OleDbCommand("INSERT INTO ArenaStats ([Date], [Wins]) VALUES (#Date, #Wins)",
Connection = conn, CommandType = CommandType.Text)
["#Date", box date; "#Wins", box wins]
|> List.iter (cmd.Parameters.AddWithValue >> ignore)
cmd
let private submit date wins =
try
conn.Open()
(submitCmd date wins).ExecuteNonQuery() |> ignore
finally
conn.Close()
[<CompiledName "AddEntry">]
let addEntry(date:DateTime, wins:int) =
submit date wins
Now testing this through FSI works just as expected. However, when I consume this API from a C# WPF project it will throw an SEHException at conn.Open(). I am really scratching my head over why this is happening.
Edit
As suggested, I have also tried to implement the same code purely in C# and in the same project, it will throw the same exception at the same place but I am posting the code below for reference.
class MsAccessDatabase : IArenaWinsDatabase {
private OleDbConnection connection = new OleDbConnection(connectionString);
private OleDbCommand SubmitCommand(DateTime date, int wins) {
return new OleDbCommand("INSERT INTO ArenaStats ([Date], [Wins]) VALUES (#Date, #Wins)") {
Connection = connection,
CommandType = System.Data.CommandType.Text,
Parameters = {
new OleDbParameter("#Date", date),
new OleDbParameter("#Wins", wins)
}
};
}
public void Submit(DateTime date, int wins) {
try {
connection.Open();
SubmitCommand(date, wins).ExecuteNonQuery();
}
finally {
connection.Close();
}
}
}
With some help from Philip I was able to figure it out. It seems that by default FSI is configured to run in 64-bit by default while the WPF project is set to "prefer 32-bit". Changing the target platform for the WPF project to 64-bit resolved the issue.
When trying to run the following code:
var connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties=Excel 12.0;", FilePath);
OleDbConnection OleDbConnection = new System.Data.OleDb.OleDbConnection(connectionString);
OleDbConnection.Open();
An SEHException exception is thrown at runtime, with the error message 'External Component has thrown an Exception'
This will usually occur when the build configuration platform in Visual Studio is incorrect, this can occur in both build configuration platforms, x86 and x64.
This is due to a mismatch between the build configuration platform of your project and the Microsoft Access Database Engine which is installed on your machine.
In order to resolve this error:
Change the build configuration platform in Visual Studio - make sure it matches the Microsoft Access Database Engine version on your machine
Recompile and run your project
The run time error should now be resolved
I know this is a really old thread, but I just ran into the same problem with a different solution.
When I installed the Access Database Engine 2016 Redistributable (x64) for the ACE provider the installer gave me an error that VCRUNTIME140.DLL wasn't installed, but the installer completed anyways and the ACE provider was available.
Uninstalling the Access Database Engine, installing the VC++ 2015 Redistributable R3 (https://www.microsoft.com/en-us/download/confirmation.aspx?id=52685), then re-installing the Access Database Engine solved the problem.

Connection String Problem Oracle .Net

I am new to oracle and am trying to simply connect to an oracle db, but I am not sure where to find the proper credentials to put in the connection string. I simply downloaded and install oracle express edition on my machine, then installed the .Net references. My simple code is here:
string oradb = "Data Source=XE;User Id=hr;Password=hr;";
OracleConnection conn = new OracleConnection(oradb); // C#
try
{
conn.Open();
string sql = "SELECT FIRST_NAME FROM EMPLOYEES WHERE EMAIL='SKING'"; // C#
OracleCommand cmd = new OracleCommand(sql, conn);
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader(); // C#
dr.Read();
//label1.Text = dr["dname"].ToString(); // C# retrieve by column name
label1.Text = dr.GetString(0).ToString(); // return a .NET data type
//label1.Text = dr.GetOracleString(0).ToString(); // return an Oracle data type
}
catch (OracleException ex)
{
label1.Text = ex.Message;
}
finally
{
conn.Close();
}
I am getting a TNS:could not resolve the connect identifier specified exception. Its probably because my connection string is wrong is what I am guessing. I cannot even go to the Server Explorer dialog in Visual Studio and test a connection correctly to my oracle db.
What steps do I need to take to figure out the proper credentials to plug into my connection string?
Or wording it like this....
If you were going to install oracle express on your machine, then connect to a .Net app what steps would you take to set up the connection string?
Maybe it is looking for a data source defined in a tnsnames.ora file called XE.
Try the Easy Connect naming method in the Express edition. It enables application clients to connect to a database without using any configuration files, simply by specifying the data source attribute through syntax shown below:
user id=hr;password=hr;data source=hr-server
user id=hr;password=hr;data source=hr-server:1521
user id=hr;password=hr;data source=hr-server:1521/XE
Replace hr-server with the dns name or ip of your machine.

C# MySql connection cannot find host

I have a java program that connects to a MySql database and it's working fine.
Now I want to convert it to a C# program, but I keep getting the error "Unable to connect to any of the specified hosts".
I've already followed the following solutions:
Connect to MySql with C#
C# MySqlConnector
Configure the ODBC DNS
And the reference to MySql.Data has been added to the project.
Here is the code to connect to the database:
string connectionString = string.Format(
"SERVER={0}; DATABASE={1}; UID={2}; PASSWORD={3};",
"jdbc:mysql://" + host + ":" + port, dbName, userName, password);
// Prepare connecting to the database.
myConn = new MySqlConnection(connectionString);
MySqlCommand command = myConn.CreateCommand();
command.CommandText = #"SELECT * FROM table_name";
myConn.Open(); // <- MySqlException: Unable to connect to any of the specified MySQL hosts.
MySqlDataReader reader = command.ExecuteReader();
List<string> exampleStore = new List<string>();
while (reader.Read())
{
// Just an example for storing data.
exampleStore.Add(reader.GetString(0));
}
The java version connects to the same server with the same values as I used here, so please don't suggest checking if the server is online.
So the problem must be in my C# code, I noticed Class.forName("com.mysql.jdbc.Driver").newInstance ();
In the java code. Seems like the driver is made active here, maybe C# needs to do something similar that I'm missing?
Edit: So the connection string should be: string connectionString = string.Format("SERVER={0}; DATABASE={1}; Port={2}; UID={3}; PASSWORD={4};", host, dbName, port, userName, password));
Was using some extra elements from the java version, din't think they would cause these problems. Thanks for the help guys.
The standard connection string is:
Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPassword;.
Please note that the port is specified separately, with Port=1234, not in the Server field. Also, eliminate jdbc:mysql: from the start of the server field, as it's specific to the JDBC driver; use a normal URI string. Nothing else should be needed.
Your connection string is wrong.
Try:
string connectionString = string.Format("SERVER={0}; DATABASE={1}; Port={2}; UID={3}; PASSWORD={4};", host, dbName, port, userName, password));

OracleClient, intermittent connection issue: app hangs on OracleConnection.Open(), no timeout, no exception thrown

Application works fine and connects every single time from any machine except the server, where it's supposed to be deployed :/ When run on the server it manages to connect once in like 20 or something attempts. Judging on the funky symptoms, I suspect it to be some kind of a network configuration related issue (as in some randomly lost packets?), but my fellow network administrator tried many different settings and we were not able to find the cause/solution.
Every single piece of advise will be appreciated, as it's seriously driving me nuts. I was wondering if switching to ODP.NET would solve the problem or at least make it easier to troubleshoot (I've read MS's provider is not very stable). However, since the architecture is not very flexible, it would take quite a lot of time to switch. But if it's the only reasonable thing to do...
Piece of code I'm using:
DbConnection conn = new OracleConnection();
conn.ConnectionString = _connectionString;
try
{
conn.Open();
DbCommand cmd = conn.CreateCommand();
cmd.CommandText = "select sysdate from dual";
cmd.Connection = conn;
_logger.Info("Sysdate: " + cmd.ExecuteScalar().ToString());
}
catch (OracleException oex)
{
_logger.ErrorException("Oracle exception: " + oex.Message, oex);
}
catch (Exception ex)
{
_logger.ErrorException("Exception: " + ex.Message, ex);
}
finally
{
if (conn != null) conn.Close();
}
More info:
Provider: System.Data.OracleClient
Lib: instantclient-basiclite-win32-10.2.0.3-20061115
Connection string is of the form: Data Source=ip_address:port_number/instance;Persist Security Info=True;User ID=user;Password=passwd
Other apps which connect without a problem: QueryExpress using same libs, Sql Developer
Os: Windows Server 2008 Standard SP 2
We ended up using ODP.NET because of some buggy issues we were having using WCF transferring data from our service to Oracle. I dont recall the actual issue-think something was not working with a certain data type-but it ended up working out pretty well for us.

Categories