"An operation is already in progress" on DataAdaper.Fill - c#

I am trying the Postgres Plus 9.5 with .Net 4.5, Npgsql 3.1.6 NuGet package.
I have read what is here about this error, but I do not understand why I get it. Everything is disposed. Here the is code:
public override DataTable getActListData(int FunkNr)
{
using (var cmd = new NpgsqlCommand())
{
cmd.CommandText = npgsqlCommand3.CommandText;
cmd.Connection = this.npgsqlConnection;
cmd.Parameters.Add(new Npgsql.NpgsqlParameter("ANWENDUNG", NpgsqlTypes.NpgsqlDbType.Numeric));
cmd.Parameters.Add(new Npgsql.NpgsqlParameter("XFUNKNR", NpgsqlTypes.NpgsqlDbType.Numeric));
using (var da = new NpgsqlDataAdapter(npgsqlCommand3))
{
var tab = new DataTable();
da.SelectCommand.Parameters["ANWENDUNG"].Value = getAnwendung();
da.SelectCommand.Parameters["XFUNKNR"].Value = FunkNr;
da.Fill(tab); // Here is the error on the 5th call
return tab;
}
}
}
Does this problem comes from Npgsql or is from Postgres?
Some other questions:
I have read here, that lazy loading is impossible, but I didn't understand is is because of the Npgsql or from Postgres?
Is it possible in Postgres to open several cursors and read on demand in the same connection?
Edit: Changed the code:
using (var npgsqlConnection = new NpgsqlConnection())
{
ConnectionString = string.Format(DataClientFactory.DataBaseConnectString, DB, User, PW);
npgsqlConnection.ConnectionString = ConnectionString;
npgsqlConnection.Open();
....
the code above here
....
}
The same error in the same call. The error:
System.InvalidOperationException occurred
HResult=-2146233079
Message=An operation is already in progress.
Source=Npgsql
StackTrace:
bei Npgsql.NpgsqlConnector.StartUserAction(ConnectorState newState)
InnerException:

If the piece of code you posted runs concurrently on the same connection, then that's your problem - Npgsql connections aren't thread-safe, and it's not possible to have multiple readers opened at the same time (MARS).

Related

ASP.NET MVC kills my IIS - too many request

I facing a big issuse. I've build software that now over 100 users use at once.
Since than my MVC ASP.NET Application is dying. The IIS Crashes over 30-40 times a day.
i dont have any recursively code
Main Probleme is that all users fetch a boolean which tell's them if they need to get new data.
That fetch-http method is called 1-5 times a second from diffrent users.
But the SQL-Reader is slower than the request made.
Error Message: There is already an open DataReader associated with this Command which must be closed first.
or
Error Message: Internal connection fatal error. Error state: 15, Token : 97
My method:
[HttpGet]
[Route("fetch")]
public IHttpActionResult fetch()
{
SqlConnection connection = new SqlConnection(con);
string sql = "SELECT whentime FROM did_datachange WHERE ux_admin_id = " + id;
connection.Open();
using (SqlCommand command = new SqlCommand(sql, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
if (reader.FieldCount == 1)
dateTime = reader.GetDateTime(0);
}
}
}
connection.Close();
....following code...
}
i know that lock cloud solve that problem, but using lock slows down the code significantly. what can i do?
it was bad code (multi threading that threw alot of execeptions)

Additional information: Connection error: Trying to add unknown port '192.168.1.100'

static void Main(string[] args)
{
OleDbConnection conn = new OleDbConnection("Provider=SAOLEDB.10;LINKS=tcpip(IP=192.168.1.100,Port=2638);ENG=dental;Persist Security Info = True; User ID = dba; PWD = sql");
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT tran_num FROM transactions WHERE tran_date > '2015-10-01'", conn);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("{0}", reader.GetValue(0).ToString());
}
reader.Close();
conn.Close();
if (Debugger.IsAttached)
{
Console.ReadLine();
}
}
As the title suggests, I'm getting an error when attempting to connect to this server. The driver (Provider) works fine for a local database using the same server setup, trying to adjust the code to connect remotely to the same setup at a different location. This is an old SQL Anywhere 10 database and I've tried hard to find answers for this with no success so far.
Edit: I changed the string a little to reflect some suggestions, now just getting a new error: Additional information: Connection error: TCPIP requires a server name
Update: The syntax changes to LINKS seems to have progressed my attempts but now I'm having issues with the syntax it's looking for when searching for a server at that IP. Receiving an error: Additional information: Database server not found
This is the connection string in registry:
DBN=DENTSERV;DSN=DENTAL;UID=DBA;PWD=SQL
I've tried both ServerName= and ENG= using the DSN and DBN, also while having them in ' ' but still receiving that same error. Any thoughts?

C# MySql.Data.MySqlClient.MySqlException Error for no reason

For the past month I've been getting data with a C# program in tandem with a company's API. Just yesterday all the sudden it would no longer work, even though I haven't changed the code at all. Here's the code:
public string GetMatchCode()
{
//this could be loaded from config file or other source
string connectString = "Server=123.123.1.23;Database=blah_users;Uid=blah_data;Pwd=blahblah;";
string sql = "SELECT MAX(match_id) FROM `data_blah`";
using (var connect = new MySqlConnection(connectString))
using (var command = new MySqlCommand(sql, connect))
{
connect.Open();
return command.ExecuteScalar().ToString();
}
}
And I get this error:
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Additional information: Access denied for user 'blah_data'#'cpe-86-80-21-54.san.res.rr.com' (using password: YES)
Any idea what could have happened and how to fix it? The only thing I think could've happened is that my support ticket dealing with node.js compatibility was executed wrong by support employees. Thanks!
Your db user's permission has failed. The user may have been removed; the permissions may have been modified. Contact the db owner.
So it looks like you are not authenticating: Either incorrect credentials or server needs a different method. Try disabling "sslmode" like below:
public string GetMatchCode()
{
//this could be loaded from config file or other source
string connectString = "Server=123.123.1.23;Database=blah_users;Uid=blah_data;Pwd=blahblah;sslmode=none;";
string sql = "SELECT MAX(match_id) FROM `data_blah`";
using (var connect = new MySqlConnection(connectString))
using (var command = new MySqlCommand(sql, connect))
{
connect.Open();
return command.ExecuteScalar().ToString();
}
}
That should do it
string sql = "SELECT MAX(match_id) FROM `data_blah`";
Isn't it supposed to be " ' " instead of " ` " surrounding "data_blah"?

NpgsqlCopyIn fails by timeout ("CommandTimeout" setting ignored)

I have a quite large dataset (900K records, 140Mb disk space) stored in CSV file in a client app (.NET 4.0). I need to load this data to Postgres 9 db the fastest way. I use Npgsql "NpgsqlCopyIn" technique (Npgsql library version=2.1.0).
For a probe load (138K) insertion works fine - it takes about 7 secons.
But for the whole batch (900K), the code throws timeout exception:
"ERROR: 57014: canceling statement due to statement timeout"
The stack trace is:
Npgsql.NpgsqlState.d_9.MoveNext() at
Npgsql.NpgsqlState.ProcessAndDiscardBackendResponses(NpgsqlConnector
context) at Npgsql.NpgsqlCopyInState.SendCopyDone(NpgsqlConnector
context) at Npgsql.NpgsqlCopyInState.StartCopy(NpgsqlConnector
context, NpgsqlCopyFormat copyFormat) at
Npgsql.NpgsqlState.d_9.MoveNext() at
Npgsql.NpgsqlState.ProcessAndDiscardBackendResponses(NpgsqlConnector
context) at
Npgsql.NpgsqlConnector.ProcessAndDiscardBackendResponses() at
Npgsql.NpgsqlCommand.ExecuteBlind() at Npgsql.NpgsqlCopyIn.Start()
I tried setting CommandTimeout to kilo values(>7200), zero; tried same values for connection "Timeout" parameter. Also I was trying to set "CommandTimeout" via connection string, but still with no result - "ERROR 57014" comes out again and again.
Please, help to load the batch correctly!
Here is the code I use:
private static void pgBulkCopy(string connection_string, FileInfo fiDataFile)
{
using (Npgsql.NpgsqlConnection con = new Npgsql.NpgsqlConnection(connection_string))
{
con.Open();
FileStream ifs = new FileStream(fiDataFile.FullName, FileMode.Open, FileAccess.Read);
string queryString = "COPY schm.Addresses(FullAddress,lat,lon) FROM STDIN;";
NpgsqlCommand cmd = new NpgsqlCommand(queryString, con);
cmd.CommandTimeout = 7200; //7200sec, 120 min, 2 hours
NpgsqlCopyIn copyIn = new NpgsqlCopyIn(cmd, con, ifs);
try{
copyIn.Start();
copyIn.End();
}catch(Exception ex)
{
Console.WriteLine("[DB] pgBulkCopy error: " + ex.Message );
}
finally
{
con.Close();
}
}
}
Npgsql has a bug regarding command timeout and NpgsqlCopyIn handling.
You may test our current master where we had a lot of fixes about command timeout handling.
You can download a copy of the project in our GitHub page: https://github.com/npgsql/Npgsql/archive/master.zip
Please, give it a try and let us know if it works for you.

No read permission on MSysObject error

I am trying to connect to an MS Access database (.mdb) through OleDb. My query is
SELECT * FROM ListQueries
which fetches me the error
SQL Execution Error.
Executed SQL Statement: SELECT * FROM ListQueries
Error Source: Microsoft JET Database Engine
Error Message: Records cannot be read; No read permission on 'MSysObjects'.
Then I tried this answer, but it did not help. Then I saw another answer says to do this.
strDdl = "GRANT SELECT ON MSysObjects TO Admin;"
CurrentProject.Connection.Execute strDdl
I do not know how to implement that in my web project. Was writing something like this as per this suggestion by #HansUp
Alternatively, it should work from c# if you run it from an OleDb connection to the Access db
The code is,
OleDbConnection con;
using (con = new OleDbConnection(Connection.connectionString()))
{
con.Open();
using (var com = new OleDbCommand("GRANT SELECT ON MSysObjects TO Admin", con))
{
com.ExecuteNonQuery();
}
using (var com = new OleDbCommand("Select * from ListQueries", con))
{
using (var dr = com.ExecuteReader())
{
while (dr.Read())
{
qryList.Add(SQLReaderExtensions.SafeGetString(dr, "Name"));
}
dr.Close();
}
}
con.Close();
}
The first com.ExecuteNonQuery() gives me this error.
Cannot open the Microsoft Jet engine workgroup information file.
I would really like to know how to grant permission for an OleDb call to work. Any suggestions will be wonderful
P.S: BTW, I am using MS Access 2010.
I strongly suggest that you do not use MS Access system objects. There are other and better ways to get the information.
You have a choice of ADO and DAO. Which would you prefer? Note that in ADO there is a difference between action (adSchemaProcedures) and select queries (adSchemaViews).
For example,
public static List<string> GetAllQueriesFromDataBase()
{
var queries = new List<string>();
using (var con = new OleDbConnection(Connection.connectionString()))
{
con.Open();
var dt = con.GetSchema("Views");
queries = dt.AsEnumerable().Select(dr => dr.Field<string>("TABLE_NAME")).ToList();
}
return queries;
}

Categories

Resources