AccessViolationException on service - c#

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;
}

Related

SQLite connection string: 'Version' keyword is not supported in C#

I have a c# winform project that supposes to save data to SQLite database, I've already used the dll properly and it runs without error, but I get an exception when trigger the method with buttonClick event
here the exception i got : Keyword not supported :'version'.
this the connection string:
"Data Source = Diary.db;Version = 3;New = False;Compress = True;";
and this the complete method :
private void AddToDbaseSQL3()
{
try{
string query = "insert into Diary(title,date,mood,wheater,content)
values('"+TitleTextbox.Text+"','"
+dateTimePicker.Value.Date.ToString("yyyy-MM-dd HH:mm")+"','"
+MoodCombobox.SelectedItem+"','"
+WheaterCombobox.SelectedItem+"','"
+ContentTextbox.Text+"');";;
SqlConnection connect2 = new SqlConnection(connection2);
SqlCommand cmd = new SqlCommand(query,connect2);
SqlDataReader read;
connect2.Open();
read = cmd.ExecuteReader();
while(read.Read())
{
}
MessageBox.Show("created");
TitleTextbox.Text = "Title";
TitleTextbox.ForeColor = SystemColors.ControlLight;
ContentTextbox.Clear();
connect2.Close();
}catch(Exception e){
MessageBox.Show(e.Message);
}
}
I've looked to this link:
Keyword not supported: 'version'
and it said to change SqlConnection to SQLiteConnection but it ended with an error, can you tell what's is the right connection string ? or there is something wrong from my code/method? please tell me, thank you, I'm sorry because it's my first time using the SQLite
SqlConnection from System.Data.SqlClient is for SQL Server.
You need an dedicated SQLite ADO.NET provider.
You can found the System.Data.SQLite provider from SQLite team here:
https://system.data.sqlite.org
Or you can use any libre or commercial provider.
You can also use the free and open-source SQLite ODBC driver that works fine and allow to use VS Visual Designers to create strongly typed ADO.NET DataSets, in addition to the use of OdbcConnection, OdbcCommand and so on:
http://www.ch-werner.de/sqliteodbc
C# Reading data from existing SQLite database

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)

Using SQLOLEDB in c# or wpf Devexpress

just run into https://social.msdn.microsoft.com/Forums/sqlserver/en-US/0ff7f210-7697-431b-9e6b-0f2e10f4c031/sql-2016-slow-connection-using-server-name-fast-using-127001?forum=sqlsetupandupgrade.
Is it possible to simply bypasse .net in a c# program and simply have this kind of performance ?
Is this is juste a change in the connection in order to use this provider, or its something more complexe ?
Success: Provider=SQLOLEDB;Data Source=::1;Integrated Security=SSPI
Elapsed: 00:00:00.0015378
Here is how we do it now:
SqlCommand command =
new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
...
}
// Call Close when done reading.
reader.Close();
Here is the connection string:
Server=...;Database=...;Uid=...;Pwd=...;Encrypt=True;TrustServerCertificate = true;Asynchronous Processing=true;MultipleActiveResultSets=True
That thread is from a user having slow connection times to local SQL Server using .NET's SqlClient, but I couldn't reproduce it.
Are you having some sort of actual problem?
And no, you can't use SqlClient with an OleDB provider or ODBC driver. There are different ADO.NET providers for those. And SQLOLEDB is deprecated, so SqlClient is the only modern, supported SQL Server connection stack that ships as part of Windows.

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

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