Process sqlservr.exe keeps running after Connection.Close() in C# - 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.

Related

Why does C# Winforms stops queriyng the Mysql Database after a couple of queries on a WebHosting?

I have a small database used for a C# WinForms with Mysql Net Connector.
All worked well during localhost development but when I moved it to a GoDaddy hosting I started getting 'ContextSwitchDeadlock'.
I suspect this is because the server is rejecting the new connections as the programs starts okey and open the first connection but as I try to recover data from it, it stops responding. I use this main schema in most of the forms.
try
{
Using(MySqlConnection Connection = new MySqlConnection("ConnectionString"))
{
Connection.Open();
//Fetching Data putting in Combobox,Textbox,DatagridView etc.
}
}
catch(MySqlException ex)
{
//Handling
}
This is in most forms OnLoad event, so each time a form is opened a new connection is opened. Im aware of Connection pooling so I opened a connection in the main form and in the next one I did just
Using(MySqlConnection Connection = new MySqlConnection())
{
Connection.Open();
}
I also disabled the exeption in the debugger options but it just no longer fetch data after some queries.

.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!

SQL Server Compact 4.0 database not detected after ClickOnce deploy

I have a WPF C# application and an SQL Server Compact 4.0 database. Initially I had my Data Source pointing to the location of the database like this:
public static SqlCeConnection sqlCeConnection = new SqlCeConnection(#"C:\VSP Road Maintenance Solution\VSPApp_Mono\VSPApp\VSPCompactDatabasse.sdf");
This worked great on my local machine but when I wanted to package the application (ClickOnce), it didn't work on the client's machine. After going through MSDN documentation on creating an ms sql server compact database and deploying it and other related similar issues such as http://social.msdn.microsoft.com/Forums/sqlserver/en-US/dc31ea59-5718-49b6-9f1f-7039da425296/where-is-datadirectory-?forum=sqlce and http://msdn.microsoft.com/en-us/library/37z40s1c(v=vs.110).aspx
I tried to access the AppDomain via C# like (in App.xaml.cs):
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Process p = Process.GetCurrentProcess(); // Pick desired process
p.PriorityClass = ProcessPriorityClass.RealTime; // Assign priority
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.SetData("DataDirectory", #"C:\VSP Road Maintenance Solution\VSPApp_Mono\VSPApp");
}
And now to create a connection to the database I just:
public static string dbFileName = "VspCompactDatabase.sdf";
SqlCeConnection sqlCeConnection = new SqlCeConnection(#"Data Source=|DataDirectory|\" +dbFileName);
This works on my local machine too, but when I create the ClickOnce package. The application does not seem to find the database. All the prerequisite software gets installed. Why is it that when the application is deployed on a different machine, the seems to be no connection with the database?

ADO.NET Max Pool Size Behavior

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.

Local Database with Visual Studio 2012

I am creating a application and I want to use a local database stored on the clients local machines. I am debating over if I should use SQLITE or is there something in Visual Studio to help me. The other thing is that I want to create the database programmatically in the users directory when the application is launched.
I am see a few things online but the articles were all about SQL Server stuff and that is not want I want to do with this application. All data will need to be stored on the local machine.
You can use SQL Server Compact, which has tooling in Visual Studio. It's syntax-compatible with SQL Server, but stores its data in a local file, which you can create on the fly (at app startup, for example).
You can create the SQLite database on the fly with the libraries provided from their website. I have used it in many projects for my personal code, as well as it being used in some of the internal architecture of Data Explorer (IBM Product). Some sample C# to create a database file:
if (!Directory.Exists(Application.StartupPath + "\\data"))
{
Directory.CreateDirectory(Application.StartupPath + "\\data");
}
SQLiteConnection conGlobal;
if (!File.Exists(dbGlobal))
{
conGlobal = new SQLiteConnection("Data Source=" + dbGlobal + ";New=True;Compress=True;PRAGMA synchronous = 1;PRAGMA journal_mode=WAL");
conGlobal.SetExtendedResultCodes(true);
firstRun = true;
}
else
{
conGlobal = new SQLiteConnection("Data Source=" + dbGlobal + ";Compress=True;PRAGMA synchronous = 1;PRAGMA journal_mode=WAL");
conGlobal.SetExtendedResultCodes(true);
}
try
{
conGlobal.Open();
}
catch (Exception)
{
//do stuff
}
Simply initiating a connection to the file will create it if the new=true is passed as the connection string. Then you can query it and get results just like you would any database.
You also have the ability to password protect the database files to prevent access to them from just opening them with an SQLite-Shell or a different SQLite DB viewer.
For more info on the pragma statements that are being passed in the connection string, see the following: http://www.sqlite.org/pragma.html
I'm not sure about programmatically (that's probably what you meant, right?) creating the database, but SQL Server Compact Edition has served me well in the past for simple apps. It's embedded and even runs in medium trust.

Categories