ADO.NET Max Pool Size Behavior - c#

I'm using MSSQL 2008R2. I wrote a C# app and purposely did not close my SqlConnection. Debugging locally on VS 2010. Following is the code I used:
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString = "server=s; database=db; User ID=sa; Password=p; Max Pool Size=1;Connect Timeout=3";
SqlConnection conn = new SqlConnection(connectionString);
string query = "SELECT * FROM dbo.Numbers";
SqlCommand comm = new SqlCommand(query, conn);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
//reader.Read() and display results to Textbox1.Text
}
Max Pool Size = 1; was expecting to error out on second click try on 2nd browser.
Why is it I can go to 3 different browsers (Mozilla, Chrome, IE) and call click method once each. That equates to 3 simultaneous connections right? The timeout error only occurs when I use a browser, but call method twice on that browser. Why is this?

Just because you left the connection object open doesn't imply three separate connections. The .NET framework actually leverages the connection pooling in SQL Server and manages it by connection string. Since the connection string was the same for all three requests - and the connection was available - there is no conflict.
Now, if you were to simulate a situation where you had a long running query start up on one of the requests and then try and hit it again - you would probably find that it would wait first - and you would get a timeout exception.
Here is a lengthy and dry document on connection pooling in the .NET framework on MSDN.

So there appears to be a discrepancy between debugging locally in VS 2010 and IIS 7.5. I had to deploy the sample web site to IIS for the max pool size to behave as expected. If I try to call click event a second time no matter which browser I try, it will throw timeout error, this is expected. Perform website/app pool restart/recycle as needed to retest.
For some reason debugging locally in VS 2010 bypasses max pool size restriction. Each browser may call click event which in my example opens 3 sqlconnection objects. The only time it throws the timeout error is if you stay in a browser and call click method twice. Strange behavior but something developers should be aware of.

Related

Too many Oracle connections open

I have a .NET Core web api on IIS running and I'm using oracle as database and I do connect to it like this.
using(OracleConnection con = new OracleConnection(connectionString))
{
OracleCommand cmd = new OracleCommand();
//some other code here
con.Open();
}
I'm not using EF or so. I (de)serialze the data from the reader directly into a json or xml string.
I have a small batch file to test the api. The batch sends a request using curl every second and when I run the batch file 5 times, to simulate a little bit of traffic, (I know there are some tools for that, but thats not the problem) the api has open 7 connections to the database. Why are 7 db connections open, how to handle it, so that a maximum of 2 or 3 simultaneously are open, even if a request has to wait?
I do not want to "just make it work", I want it to work the right way. Because of that, I want to now, is "connection pooling" the keyword here? Especially the max pool size, could I just set it to 3, or did I forget something to set up, or something?

.NET SQL Server connection issue - Maybe connection pool related

I am having a very strange problem and am hoping someone out there has had a similar experience.
My companies application for one client is getting "banned" from the SQL Server at the beginning of our application. The behavior is strange. I'll write it out in point form.
SQL Connections are created, data is retrieved, the connections are closed, talk to another datasource and then denied access to SQL Server.
Here's the long winded version:
.NET application connects to database multiple times. Gets some data, does some work. It then goes to get some more data and then gets an error that the "SQL Server cannot be found or access is denied". If the process is started over again without re-starting the app then no more connections are able to be made to SQL Server. All new connections result in "SQL Server cannot be found or access is denied". If the application is restarted then it will repeat the above process.
This is the first in 5 years of my experience with the software to have this problem. The application does have code written in Delphi 7. The dephi 7 / VBA code has not issues. My .NET code that performs the actual query looks like:
protected abstract DbConnection GetConnection();
protected abstract DbDataAdapter GetDataAdapter(DbCommand cmd);
protected abstract DbCommand GetCommand(DbConnection conn, String sql);
protected abstract DbCommandBuilder GetCommandBuilder(DbDataAdapter adapter);
public virtual DataTable Query(string sql)
{
var dt = new DataTable();
using (var conn = GetConnection())
{
try
{
using (var cmd = GetCommand(conn, sql))
{
using (var adapter = GetDataAdapter(cmd))
{
adapter.Fill(dt);
}
}
}
catch (Exception ex)
{
throw new SqlStatementException(sql, ex);
}
}
return dt;
}
It is my own quite and dirty DAL. When it is used it is using an OleDbConnection.
Note: Due to legacy code the connection string is configured for OleDbConnection. After taking a moment to review my code I do have the ability to change the connection type to SqlConnection. I haven't tried that yet.
On the client's machine I have not been able to reproduce the issue outside of the main application. I tried creating a little app that would make 100 calls back to back using the format above with an OleDbConnection but it executed successfully.
The failure in the main app happens in the same spot. That should give me a clue except I cannot make sense of it since it is making duplicate query, getting the same data. But I will say that the application talks to two data sources and transfers data from one to the other. Before it does the transfer it does some validation on the sources. So it talks to another database (proprietary file based) via ODBC and comes back successfully and then fails when trying to talk to SQL Server through OleDbConnection.
My suspicion is something is happening in the connection pool. That is causing a failure which in turns causes a denial of access.
Other interesting points. All worked fine for about a year, client got a new machine a couple of months ago, all work fine and then suddenly stopped. I put the application on another machine at the client's site and all worked well for a week and then the same issue appeared. We turned everything off on the client's machine but the issue persisted. I thought firewall but no luck there.
Any assistance is greatly appreciated.
Was gonna put this in a comment, but it got too big :-)
I see your connection-creating methods are abstract. This of course means that derivatives can do all sorts of bad things when they create the connection. I'd look there first.
One thing I found in a similar situation...if you're doing something in the code that creates the connection that makes the connection string unique, you won't be reusing those pooled connections. So...doing something like adding an "App=MyApp" + an incrementing number, date/time, or guid, it will destroy your ability to use pooled connections. When this happened to me, it took me forever to figure it out.
If your application was "slow enough" in the past, such that "old" pooled connections fall out of the pool, you might never see a problem...but then, say a customer gets hot new hardware...and blam...weird errors from nowhere! This might not be what's happening to you, but maybe it will give you some ideas about where to look. Good luck!

Process sqlservr.exe keeps running after Connection.Close() in C#

I created a connection to a SQL database, but when I close it, the process sqlservr.exe keeps running even after closing the application. I've tried to use Dispose too, but had the same problem. sqlservr.exe is meant to keep running(It wasn't before starting the application)? Is there any way of killing it?
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string conexao = "Data Source=(LocalDB)\\v11.0;AttachDbFilename=C:\\Users\\SMITH\\Documents\\C#\\WindowsFormsApplication3\\WindowsFormsApplication3\\Database1.mdf;Integrated Security=True";
SqlConnection conn = new SqlConnection(conexao);
SqlCommand comando = new SqlCommand("SELECT COUNT(*) FROM Usuarios WHERE NomeUser = #user and SenhaUser = #senha", conn);
comando.Parameters.Add("#user", SqlDbType.VarChar).Value = textBox1.Text;
comando.Parameters.Add("#senha", SqlDbType.VarChar).Value = textBox2.Text;
conn.Open();
int i = (int)comando.ExecuteScalar();
string a = i.ToString();
textBox3.Text = a;
if(i>0){
MessageBox.Show("Existe");
}else{
MessageBox.Show("Nem existe");
conn.Dispose();
}
}
}
}
You're probably thinking you're doing something else than what you're really doing.
You're expecting you've got local access to a local DB through an embedded SQL server. This is not the case. In reality, you're just starting the full fledged MS SQL Server service (sqlservr.exe) which is not tied to your application at all - apart from being started by your process, it's the same as if you had it configured to run at startup of Windows etc.
This isn't necessarily a bad thing, but if you're expecting your application to work with an embedded server, you can run into issues. Namely, the SQL server is configured on the computer, not through your application, it has to be installed (separately), if there is another server running, you're attaching to that one - for which you don't necessarily have permissions etc.
If you only use this for an internal tool, don't bother with changing anything, having the sql server process running is fine and you can shut it down through Services. If this is a part of your distributed application, consider using a different SQL server, for example SQL Server Anywhere (SQL Server CE), or perhaps even something completely different, like MS Access (freely available on every Windows PC, not just with Office) or FireBird.
Since your connection string indicates you're using LocalDB, from Introducing LocalDB, an improved SQL Express
LocalDB doesn't create any database services; LocalDB processes are started and stopped automatically when needed. The application is just connecting to "Data Source=(localdb)\v11.0" and LocalDB process is started as a child process of the application. A few minutes after the last connection to this process is closed the process shuts down. (emphasis added)
I have confirmed the "few minutes after" behavior in my own environment. But be sure you don't have any processes holding onto a connection anywhere.

SQL Server: Could not find prepared statement with handle x

Recently our QA team reported a very interesting bug in one of our applications. Our application is a C# .Net 3.5 SP1 based application interacting with a SQL Server 2005 Express Edition database.
By design the application is developed to detect database offline scenarios and if so to wait until the database is online (by retrying to connect in a timely manner) and once online, reconnect and resume functionality.
What our QA team did was, while the application is retrieving a bulk of data from the database, stop the database server, wait for a while and restart the database. Once the database restarts the application reconnects to the database without any issues but it started to continuously report the exception "Could not find prepared statement with handle x" (x is some number).
Our application is using prepared statements and it is already designed to call the Prepare() method again on all the SqlCommand objects when the application reconnects to the database. For example,
At application startup,
SqlCommand _commandA = connection.CreateCommand();
_commandA.CommandText = #"SELECT COMPANYNAME FROM TBCOMPANY WHERE ID = #ID";
_commandA.CommandType = CommandType.Text;
SqlParameter _paramA = _commandA.CreateParameter();
_paramA.ParameterName = "#ID";
_paramA.SqlDbType = SqlDbType.Int;
_paramA.Direction = ParameterDirection.Input;
_paramA.Size = 0;
_commandA.Parameters.Add(_paramA);
_commandA.Prepare();
After that we use ExceuteReader() on this _commandA with different #ID parameter values in each cycle of the application.
Once the application detects the database going offline and coming back online, upon reconnect to the database the application only executes,
_commandA.Prepare();
Two more strange things we noticed.
1. The above situation on happens with CommandType.Text type commands in the code. Our application also uses the same exact logic to invoke stored procedures but we never get this issue with stored procedures.
2. Up to now we were unable to reproduce this issue no matter how many different ways we try it in the Debug mode in Visual Studio.
Thanks in advance..
I think with almost 3 days of asking the question and close to 20 views of the question and 1 answer, I have to conclude that this is not a scenario that we can handle in the way we have tried with SQL server.
The best way to mitigate this issue in your application is to re-create the SqlCommand object instance again once the application detects that the database is online.
We did the change in our application and our QA team is happy about this modification since it provided the best (or maybe the only) fix for the issue they reported.
A final thanks to everyone who viewed and answered the question.
The server caches the query plan when you call 'command.Prepare'. The error indicates that it cannot find this cached query plan when you invoke 'Prepare' again. Try creating a new 'SqlCommand' instance and invoking the query on it. I've experienced this exception before and it fixes itself when the server refreshes the cache. I doubt there is anything that can be done programmatically on the client side, to fix this.
This is not necessarily related exactly to your problem but I'm posting this as I have spent a couple of days trying to fix the same error message in my application. We have a Java application using a C3P0 connection pool, JTDS driver, connecting to a SQL Server database.
We had disabled statement caching in our the C3P0 connection pool, but had not done this on the driver level. Adding maxStatements=0 to our connection URL stopped the driver caching statements, and fixed the error.

How do I reset an asp.net website within the site itself with a button?

I am working on an ASP.NET 2.0 website. The issue that I'm having is that it queries a database to get the info it displays on screen, but the database occasionally gets to where it has too many open connections. This causes the website to reject the attempt to log-in for anyone, after that database error.
This is caused because many users will log-in, do what they need to do, but then leave the website running while they do other things without logging out. It will time out on them, but the connection still seems to be open. We then have to contact the person in charge of the server it's running on and have him reset it for us.
I have looked and all connections made to the database seem to be closed after the request and query is made. So, what I want to do is to add a button that when clicked will reset the website, instead of having to call the guy in charge of the server every time. Then we can reset it whenever we need to. So, how do I reset an ASP.NET 2.0 website with a button on one of the pages inside the site?
Many thanks,
Mike
all connections made to the database seem to be closed after the request
The problem here is the word "seem". For example, this code "seems" like it will close the connection, but in some situations it won't:
var conn = new SqlConnection("MyConnection");
var cmd = new SqlCommand("query string here", conn);
cmd.ExecuteNonQuery();
conn.Close():
I can hear you saying, "Of course it closes the connection. Don't you see the 'conn.Close();' line?" The problem is that there are things that can happen that prevent the conn.Close() line from executing.
Instead, you need to do something like this:
using (var conn = new SqlConnection("MyConnection"))
using (var cmd = new SqlCommand("query string here", conn))
{
cmd.ExecuteNonQuery();
}
That code will always close the connection.
If you're really serious about "resetting" the application, you might try calling Environment.Exit(), but again: this is a bad idea.
I don't think adding a button to reset the website is the correct choice.
You should really look into why the connections aren't closing.
If you're using SqlConnections, then wrap them in a using statement, this will dispose of the connection after you're finished.
Here's an example:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// Do work here; connection closed on following line.
}
To answer your actual question, the easiest way to reset a ASP.NET site is to just modify the web.config which will cause the site to reload.
So if I wanted to implement a button all I would do is set a value in the app settings that is meaningless (perhaps a date time of the last reset) and then use ConfigurationManager to save the changes.
MSDN reference: ConfigurationManager Class

Categories