SEHException on OleDb connection open - c#

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.

Related

Pythonnet Runtime Error using C# dll (Database Incompatibility)

enter image description hereI am using a C# dll using pythonnet on python 2.7.13 (which uses other dll files and .mdb database files) to make some technical calculations. This dll files does not have a good documentation (only namespaces, class and method names). Well the program in most PC Works Fine but in all office computers it throws a runtime Error from Dll files (my doubt is connection with database). This dll files are compiled to target .NET 4.0 (in office computers is installed .NET 4.7.1 or other versions newer than 4.0) and EntityFramework is also being used (programs target 5.0 and this is a dll file in program folder, but in office computers is installed EntityFramework 6.2 tool). Microsoft database Engine 2010 is also installed in those computers.
In every other computer that I have tested the program it works perfectly. In office computers I found a group of input data for which program works, but anyway this is not correct because it should work also for the default data.
To make tests in office computers I have compiled python code using PyInstaller (I repeat, compiled version work fine in other PCs).
I am using .NET Reflector to decompile dll files and programs Exception to find the Error. The method that throws Exception is in the following code.
Thanks in advance!
public int LoadRanghiAmmessi(int[] vRanghi, string geometria)
{
int index = 0;
CrConnection connection = new CrConnection(this.PathDB);
string query = "SELECT * FROM RanghiAmmessi WHERE (Geometria='" + geometria + "') ORDER BY NRanghi";
OleDbDataReader recordset = connection.GetRecordset(query, #"\Coils.mdb;");
if (!recordset.HasRows)
{
if (recordset != null)
{
recordset.Close();
}
query = "SELECT * FROM RanghiAmmessi WHERE (Geometria='*') ORDER BY NRanghi";
recordset = connection.GetRecordset(query, #"\Coils.mdb;");
while (recordset.Read())
{
vRanghi[index] = int.Parse(recordset["NRanghi"].ToString());
index++;
}
if (recordset != null)
{
recordset.Close();
}
}
return index;
}
public OleDbDataReader GetRecordset(string query, string NomeDB)
{
string connectionString = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + this.PathDB + NomeDB + "Jet OLEDB:Database Password=123456";
this.ChiudiConnessioni();
this.conn = new OleDbConnection(connectionString);
OleDbCommand command = new OleDbCommand(query, this.conn);
try
{
this.ApriConnessione();
return command.ExecuteReader();
}
catch (Exception exception)
{
exception.Message.ToString();
this.ChiudiConnessioni();
return null;
}
}
After many tests I found out that the program is working also in other PC after declaring some objects like function parameters and after compiling running the program as compatible with Windows 7. Before the objects were created like variables and those variables were passed as parameters, (in this case, reasonably the first thought is that the problem is "pass by reference" mechanism and that some values are not inserted in the right mode, but this is not the case because:
- the same exactly code did function very well in most PC (compatibility
problem)
- the same exactly mechanism is used to specify the objects attributes and
to make calculations
In this conditions I would say that it is not clear where the problem was. In the first version installing the SQL Server Express made possible for the program to work well even without last modifications.
Umm... given the details that it works fine on "Other PC", I am guessing that the problem is your so-called database. I don't see in any way, however, how anyone could be certain at what the problem is until it is solved.

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

The type initializer for 'Oracle.DataAcces.Client.OracleConnection' threw an exception

When I try to connect to an Oracle database in my C# application and I try to click a button I get this error:
The type initializer for 'Oracle.DataAcces.Client.OracleConnection'
threw an exception
My code for accessing the database:
static string column;
static string OracleServer = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=something)(HOST=something)(PORT=something)) (CONNECT_DATA=(SERVICE_NAME=name)));User Id=something;Password=something;";
public void read()
{
try
{
var conn = new OracleConnection(OracleServer);
conn.Open();
OracleCommand cmd = new OracleCommand("select * from t1", conn);
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
var column1 = reader["vermogen"];
column = (column1.ToString());
listBox1.Items.Add(column);
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Now I am using the reference Oracle.DataAccess and as code: using Oracle.DataAccess.Client;
The application is an arcgis add in application, and I converted it to a form application and it does connect to the database. But I have to have it work in the add in application.
I have never experienced this error and I am not experienced at Oracle databases and I was wondering what is causing this error? When I run the application, I dont get any errors. But when I click the buttons of the User Interface of the application, I get this error.
What should I do to lose the error and what is causing it?
This can also happen if your Oracle client DLL version number is mildly different from the reference you have in Visual Studio and even if you set that reference's "Specific Version" property to false.
This is an error inside the Oracle dll. My guess is that you installed the .NET dlls but did not install the Oracle client on your system. Can you connect to Oracle through the SQLPlus client software? If it's not installed, you need to install the Oracle client software.
Change your project properties.
Build section, Palatform : x86
Since you don't have administrator permission for Oracle Client. Add this in App.config file :
<IPermission class="Oracle.DataAccess.Client.OraclePermission,
Oracle.DataAccess, Version=2.111.7.20, Culture=neutral,
PublicKeyToken=89b483f429c47342" version= "1" Unrestricted="true"/>

OracleDataAdapter.Fill "Connection must be open" error

I have some code that uses ODP.Net
using (OracleConnection connection = new OracleConnection(connectionString))
{
connection.Open();
boxCommand = new OracleCommand(sql, connection);
OracleDataAdapter boxAdapter = new OracleDataAdapter(boxCommand);
DataTable boxTable = new DataTable();
boxAdapter.Fill(boxTable);
}
I then get an error below on a production server. The test server is fine.
I don't understand as its complaining about a connection not being open but if there was a problem it should occur at the point my Open is called not on the Fill. Also I thought Fill was supposed to open the connection anyway.
Can anyone suggest what might be going on?
UPDATE: From the comments I tried adding this but same problem:
using (OracleConnection connection = new OracleConnection(connectionString))
{
connection.Open();
while(connection.State != ConnectionState.Open)
{
connection.Close();
connection.Open();
}
boxCommand = new OracleCommand(sql, connection);
OracleDataAdapter boxAdapter = new OracleDataAdapter(boxCommand);
DataTable boxTable = new DataTable();
boxAdapter.Fill(boxTable);
}
UPDATE 2 : I have added logging and the Validate Connection = true to the connection string and I know the connection state is open, the box command was done, the adapter created and the table created, it definitely errors on the Fill
Can you try installing the latest version of ODP.Net and see if you still have the problem? You should be able to run latest ODP.Net even against older Oracle DBs (10g in your case).
EDIT:
Since you're restricted to a specific ODP.net version, here are some other things to try:
Make sure the proper Oracle folders are at the beginning of your system path. For example, I have the Oracle folders at the beginning of my path, like this (I have ODP.net installed in c:\oracle\ora11g and I also have Oracle 10g Express Edition installed, but note that the ODP.net folders are first:
c:\oracle\ora11g\product\11.1.0\client_1;c:\oracle\ora11g\product\11.1.0\client_1\bin;C:\oracle\ora10g\bin;
I've seen situations where Oracle does weird things and won't work properly if the path isn't correct.
Try reinstalling the specific ODP.net version you are using. This should clean things up and hopefully resolve your issue.

Paradox Tables in C#

I'm trying to read a Paradox 5 table into a dataset or simular data structure with the view to putting it into an SQL server 2005 table. I've trawled google and SO but with not much luck. I've tried ODBC:
public void ParadoxGet()
{
string ConnectionString = #"Driver={Microsoft Paradox Driver (*.db )};DriverID=538;Fil=Paradox 5.X;DefaultDir=C:\Data\;Dbq=C:\Data\;CollatingSequence=ASCII;";
DataSet ds = new DataSet();
ds = GetDataSetFromAdapter(ds, ConnectionString, "SELECT * FROM Growth");
foreach (String s in ds.Tables[0].Rows)
{
Console.WriteLine(s);
}
}
public DataSet GetDataSetFromAdapter(DataSet dataSet, string connectionString, string queryString)
{
using (OdbcConnection connection = new OdbcConnection(connectionString))
{
OdbcDataAdapter adapter = new OdbcDataAdapter(queryString, connection);
connection.Open();
adapter.Fill(dataSet);
connection.Close();
}
return dataSet;
}
This just return the error
ERROR [HY000] [Microsoft][ODBC Paradox Driver] External table is not in the expected format.
I've also tired OELDB (Jet 4.0) but get the same External table is not in the expected format error.
I have the DB file and the PX (of the Growth table) in the Data folder... Any help would be much appriciated.
I've had the same error. It appeared when I started my C# project on Win2008 64 (previos OS was Win2003 32). Also I found out that it worked fine in console apps and gave different errors in winforms. It seems that problem comes from the specifics of 32 ODBC driver working on 64-bit systems.
My solution was:
// Program.cs
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// it is important to open paradox connection before creating
// the first form in the project
if (!Data.OpenParadoxDatabase())
return;
Application.Run(new MainForm());
}
The connectionstring is common:
string connStr = #"Driver={{Microsoft Paradox Driver (*.db )}};DriverID=538;
Fil=Paradox 7.X;DefaultDir=C:\\DB;Dbq=C:\\DB;
CollatingSequence=ASCII;";
After opening connection you may close it in any place after creating first Form (if you need to keep DB closed most of time), for example:
private void MainForm_Load(object sender, EventArgs e)
{
Data.CloseParadoxDatabase();
}
After doing that you may open and close connection every time you want during execution of your application and you willn't get any exceptions.
Maybe this will help you out,
http://support.microsoft.com/support/kb/articles/Q237/9/94.ASP?LN=EN-US&SD=SO&FR=1
http://support.microsoft.com/support/kb/articles/Q230/1/26.ASP
It appears that the latest version of the Microsoft Jet Database Engine
(JDE) does not fully support Paradox unless the Borland Database Engine
(BDE) is also installed.
Try to Run all The Applications with the "Run As Administrator" privileges especially run the VS.NET with "Run As Administrator "... and I am sure your problem get solved
This isn't an answer, but more of a question: any particular reason you're trying to use C# to do the data manipulation as opposed to using SQL Server tools to load the data directly? Something like DTS or SSIS would seem like a better tool for the job.
Thanks, I'll give that a try. I wanted to use C# so I can put it on some web pages without the extra set of putting it in SQL server.

Categories