How to connect to oracle database with ODAC c# - 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

Related

MySQLConnection has no implementation

I'm new to C# and connecting to databases.
The problem is: whenever I try to connect to DB by running this code:
string connparams = "server=127.0.0.1;uid=root;pwd=12345;database=test;";
try
{
MySqlConnection connection = new MySqlConnection(connparams);
}
catch (System.ArgumentException me)
{
Console.WriteLine(me.ToString());
}
connection.Open();
connection.Close();
I get the window "The application is in break mode"
When I take a look at the events window I can see an exception with description "No source code". When I try to see the implementations of functions in MySQLConnection I can see none of them, only declarations. So what should I do/redo/reinstall in order to solve this? Using VS2017, .NET Framework 4.6.1, Connector/NET (MySQL)

Informix db connection and loading to datatable is not working

i am trying to connect to an informix database in my web application and retrieve the data based on an item code entered by the user and store it in a datatable later i want to take the data from the datatable and display it on my textboxes for the item selected. its an odbc connection DRIVER={IBM INFORMIX ODBC DRIVER} in my connection string
if (DropDownList4.Text == "***.**.**.**" || DropDownList4.Text == "***.**.**.**" || DropDownList4.Text == "***.**.**.**")
{
//string abilene = ConfigurationManager.ConnectionStrings["Abeliene"].ConnectionString.ToString();
IfxConnection conn = new IfxConnection("User Id=****;Password=****;" +"Host=abkrisc1;Server=abkrisc1;" +"Service=1719;DB=circa119;");
DataTable Abilene = new DataTable();
Abilene.Columns.Add("item");
Abilene.Columns.Add("desc");
Abilene.Columns.Add("upc");
Abilene.Columns.Add("itemupc");
Abilene.Columns.Add("ctyp");
Abilene.Columns.Add("citg");
Abilene.Columns.Add("best");
Abilene.Columns.Add("disp");
Abilene.Columns.Add("mold");
Abilene.Columns.Add("csel");
IfxCommand cmd;
cmd = new IfxCommand("Select t_item,t_idsc,t_upct,t_item_upc,t_ctyp,t_citg,t_best,t_disp,t_mold,t_csel from tsckcm907 where t_item = #item'");
conn.Open();
cmd.Parameters.Add("#item", IfxType.VarChar).Value = TxtItem.Text;
try
{
IfxDataReader myreader = cmd.ExecuteReader();
Abilene.Load(myreader);
Response.Write(Abilene.Columns);
con = true;
}
catch (Exception ex)
{
throw ex;
con = false;
}
if (con == true)
{
while (Abilene.Rows.Count > 0)
{
TxtItem.Text = Abilene.Rows[0]["item"].ToString();
lbldesc.Text = Abilene.Rows[1]["desc"].ToString();
}
}
The error i get when i debugged was at conn.open() -> ERROR [HY000] [Informix .NET provider][Informix]Server abkrisc1 is not listed as a dbserver name in sqlhosts.
i have done a similar scenario with sql database, but informix i have never worked with. Please if anyone could help me with this code that would be awesome, even this code that i used was found from ibm website.
Check your informix server configuration (the problem might be in your sqlhosts file, as the error states), it should contain server with the name abkrisc1, listening at port 1719.
If that's ok, then check your DSN configuration (this may vary depending on your operating system - check out this page for details).
Documentation in internet and the error message are misleading.
I had the same error and meanwhile I found out how to solve it.
When you install the Informix Client SDK for Windows and use the ODBC driver for Informix (with or without .NET) you must pass the following parameters:
Host
Server
Service or Port
Protocol
User ID
Password
All these parameters are mandatory. The database is optional.
In your connection string the protocol is missing. In the case that any parameter is missing the OBDC driver searches the server in the registry under
32 bit driver:
HKLM\Software\Wow6432Node\Informix\SQLHOSTS\Servername
64 bit driver:
HKLM\Software\Informix\SQLHOSTS\Servername
If the server is not listed there you get the error "Server XYZ is not listed as a dbserver name in sqlhosts."
Please note that only Linux uses an sqlhosts file. On Windows the same data is stored in the registry instead.
You do NOT need to create a sqlhosts file although the error message and the documentation and several webpages make you think that.
You do NOT need to use the IBM tool SetNet32 to generate entries for your server.
You just have to pass ALL mandatory parameters to the ODBC driver and the error is gone.
It is really a pitty that IBM is not able to give a more intelligent error message.

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

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.

AccessViolationException on service

I have a service running, that is connected to a few clients. It has been up and running for weeks and this function is called many times every minute, I have a few catches in the different function, but this exception made it all the way to crash. I never seen the issue before. Whan can make this occure?
Stack:
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException
Stack:
at System.Data.OleDb.OleDbServicesWrapper.GetDataSource(System.Data.OleDb.OleDbConnectionString, System.Data.OleDb.DataSourceWrapper ByRef)
at System.Data.OleDb.OleDbConnectionInternal..ctor(System.Data.OleDb.OleDbConnectionString, System.Data.OleDb.OleDbConnection)
at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(System.Data.Common.DbConnectionOptions, System.Object, System.Data.ProviderBase.DbConnectionPool, System.Data.Common.DbConnection)
at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(System.Data.Common.DbConnection, System.Data.ProviderBase.DbConnectionPoolGroup)
at System.Data.ProviderBase.DbConnectionFactory.GetConnection(System.Data.Common.DbConnection)
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(System.Data.Common.DbConnection, System.Data.ProviderBase.DbConnectionFactory)
at System.Data.OleDb.OleDbConnection.Open()
at EServer.Database.DBManager.DoesObjectExsist(System.String)
at EServer.Database.DBManager.setObjectOnline(System.String, Boolean, System.String, System.String)
at EServer.Network.SocketListener.handleToDo()
at EServer.Network.Token.ProcessData(System.Net.Sockets.SocketAsyncEventArgs)
at EServer.Network.SocketListener.ProcessReceive(System.Net.Sockets.SocketAsyncEventArgs)
at EServer.Network.SocketListener.OnIOCompleted(System.Object, System.Net.Sockets.SocketAsyncEventArgs)
at System.Net.Sockets.SocketAsyncEventArgs.OnCompleted(System.Net.Sockets.SocketAsyncEventArgs)
at System.Net.Sockets.SocketAsyncEventArgs.ExecutionCallback(System.Object)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
at System.Net.Sockets.SocketAsyncEventArgs.FinishOperationSuccess(System.Net.Sockets.SocketError, Int32, System.Net.Sockets.SocketFlags)
at System.Net.Sockets.SocketAsyncEventArgs.CompletionPortCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32, UInt32, System.Threading.NativeOverlapped*)
Code:
public bool DoesObjectExsist(String ID)
{
try
{
String connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + dbPath + "'";
string mySelectQuery = "SELECT * FROM Object WHERE ID = \"" + ID + "\"";
OleDbConnection myConnection = new OleDbConnection(connectionString);
OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection);
myConnection.Open();
OleDbDataReader myReader = myCommand.ExecuteReader();
try
{
while (myReader.Read())
{
return true;
}
}
finally
{
myReader.Close();
myConnection.Close();
}
return false;
}
catch (Exception e)
{
return false;
}
}
EF Core Update
The followings sections are a bit dated and are about EF6 and .NET Framework 4.x.
Nowadays, if you are using .NET (Core), use the EntityFrameworkCore.Jet EF Core provider. Use the latest prerelease, that references the 5.0.0 OLE DB libraries, that contain some major bugfixes.
AccessViolationException
This issue is a bug within the ACE 2010 engine. A workaround can be found in the original bug report on microsoft connect (see FranzT):
In my Applicationn I have the same problem. MS Access DB is a backend for this app(C#, .NET 2.0, VS 2005).
When in connection string as provider OLEDB.4.0 is used, it works fine. When the data access provider is ACE.OLEDB.12 I get an Exception if OpenFileDialog is used.
In connection string is possibel to set many parameters, OLE DB Services too.
When OLE DB Services=default (-13, pooling disabled) I get the
Exception. When OLE DB Services=EnableAll (-1, pooling enabled) it
works fine.
If I set OLE DB Services=-2 (EnableAll without pooling) I get the Exception.
My workaround is: set the OLE DB services=-1(EnableAll).
The workaround is based on the research of a microsoft forum user by the name of Elmar Boye, who goes into detail about the nature of the issue (though in German):
https://social.msdn.microsoft.com/Forums/de-DE/500055e5-6189-418c-b119-fdc0367e0969/accessviolationexception-bei-openfiledialog-nach-ffnen-und-schlieen-einer-2-form?forum=dotnetframeworkde
Basically, the ACE 2010 engine is accessing memory it doesn't own. And if the database is already unloaded at the time the engine accesses the memory, the exception is thrown. To workaround the issue, connection pooling can be used, since it keeps the database connection open and therefore the database in memory. It can be enabled using different combinations of OLE DB Services flags.
A good flag value is the original default, which enables all services (though this default seems to be overwritten by a registry key, which is why it makes sense to manually provide the value in the connection string):
OLE DB Services=-1
Though the bug report addresses a problem within the open file dialog, the root cause is the same as for other AccessViolationException cases using the ACE 2010 provider for Access.
There is also a link to a Hotfix that supposedly fixes the issue.
By the way, this exception does not occur using the Microsoft.Jet.OLEDB.4.0 provider.
JetEntityFrameworkProvider
For those like me who are using the JetEntityFrameworkProvider by bubibubi make sure that you are using the workaround in your production connection string, but not in your connection string you use for applying database migrations, because it will throw a OleDbException E_UNEXPECTED(0x8000FFFF) on the second Update-Database command while trying to open the database and will lockup the Package Manager Console on every command execution thereafter (until you restart Visual Studio).
Access and multi user scenarios
Access is build for simultaneous multi user access over a network share. So this is a scenario that is explicitly supported.
#Hans Passant and #user2905764
Why dont you make it more sumpler by using this. If would greate if you wrap connection, command and reader objects inside a using statement block. See usage of using.
Update
Sorry , I saw this couple of minutes ago that, you are using Access db for Services, which is, I think completely insane. Since services are consumed by various clients at a time so it might lead to inconsistency. So, as Hans Passant suggested in his comment, kindly go for Sql Server Express or MySql like Server-Oriented database for such scenarios.
public bool DoesObjectExsist(String ID)
{
bool result=false;
try
{
String connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + dbPath + "'";
string mySelectQuery = "SELECT Count(*) FROM Object WHERE ID = ?";
OleDbConnection myConnection = new OleDbConnection(connectionString);
OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection);
command.Parameters.AddWithValue("#id",ID);
myConnection.Open();
OleDbDataReader myReader = myCommand.ExecuteReader();
try
{
if(reader.HasRows)
result=true;
}
finally
{
myReader.Close();
myConnection.Close();
}
}
catch (Exception e)
{
//log exception
}
return result;
}

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.

Categories