C# application possibly not disposing properly - c#

I'm writing a Class Library in C# as an add-on to another application that provides an API. Essentially, the application is set to execute the code in my Class Library upon changing a specific text field in the application. I'm finding that after I change that field once, changing any other text field also triggers my code to run and I cannot figure out why.
The Class Library has a function executed by the application. Essentially, I'm connecting to a SQL Database, calling a Windows Form to show, then disposing of everything. I find that by removing the SqlConnection, the issue does not occur.
Any thoughts would be greatly appreciated.
SqlConnection myConnection;
myConnection = new SqlConnection("user id=" + Username + ";" +
"password=" + Password + ";" +
"server=" + Server + ";" +
"database=" + DBName + ";" +
"connection timeout=" + ConnectionTimeout + ";"
);
myConnection.Open();
string currentValue = htableData["Test"].ToString().Trim();
if (!(String.IsNullOrEmpty(currentValue)))
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 form = new Form1();
Application.Run(form);
form.Dispose();
}
myConnection.Dispose();

Any thoughts would be greatly appreciated.
This isn't quite what you asked about, but it is not good practice to call Dispose explicitly. It is best to use using blocks instead.
SqlConnection connection;
using (connection = ... ) {
// use the connection
} // connection is automatically disposed (and error handling is done for you)
Ideally, you should also use the same pattern on the form

using(SqlConnection myConnection = new SqlConnection(
"user id=" + Username + ";" +
"password=" + Password + ";" +
"server=" + Server + ";" +
"database=" + DBName + ";" +
"connection timeout=" + ConnectionTimeout + ";")
){
myConnection.Open();
string currentValue = htableData["Test"].ToString().Trim();
if (!(String.IsNullOrEmpty(currentValue)))
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Form1 form = new Form1();
Application.Run(form);
form.Dispose();
}
myConnection.Close();
}

You are not providing enough code to tell why it is called twice. But I do have a couple of comments to make.
This is not the correct way to display a form within and already running application that already displays other UI elements. The correct way is form.Show() or form.ShowDialog(). I guess the latter in your case. Avoid calling EnableVisualStyles and SetCompatibleTextRenderingDefault as well.
To ensure the correct disposal of things (especially when exceptions occur), you could make use of the using statement, even though I don't think that this is the cause of your problem. Here is a nice showcase: Understanding the 'using' statement in C#
Again, it will not solve your problem, but a more elegant way of creating your connection string would be to use the SqlConnectionStringBuilder, instead of concatenating the strings. Here is how: How to use SqlConnectionStringBuilder in C#

Related

"database is locked" C# & SQLite

I keep getting this exception over and over. I've tried separating my query into two separate queries, that didn't work. I've checked to make sure the db connection is closed elsewhere before it's opened during this method, it's definitely closed before the function is called and opened before any queries.
Below iss the code for the function. I've set breakpoints and the query itself is fine. The code is the exact same that I used previously for updating a PIN function, with just the query string changed, so I don't know why it's causing issues:
Code:
public void transferMoney(string senderIban, decimal senderBalance, string receiverIban, decimal transferAmount,string messageOptional)
{
//myBankAccount.AccountPin = updatedPin;
DataTable dtUser = new DataTable();
sqlconnConnection.Open();
string strQuery2 = #"UPDATE Accounts SET Balance = Balance + " + Convert.ToDecimal(transferAmount) + " WHERE GUID = '" + receiverIban + "';"
+ "UPDATE Accounts SET Balance = Balance - " + Convert.ToDecimal(transferAmount) + " WHERE GUID = '" + senderIban + "';";
// example of a Paramaterised SQL statement.
SQLiteCommand sqlcomCommand2 = new SQLiteCommand(strQuery2, sqlconnConnection);
SQLiteDataAdapter sqldatadptAdapter = new SQLiteDataAdapter(sqlcomCommand2); // local SQL data Adaptor
try
{
// sqldatadptAdapter.Fill(dtUser);
sqlcomCommand2.ExecuteNonQuery();
}
catch (Exception ex)
{
// Exception will the "thrown" when there was a problem
throw new Exception($"UPDATE WAS unsuccessful:\n{ex.Message}");
}
finally
{
sqlconnConnection.Close();
}
Maybe you have a DB browser opened? Or you have accessed the DB some other way. This error only occurs when DB is modified or used elsewhere. If you can't find it, I'd suggest restarting PC just in case there something hidden :)
P.S. Posting this as answer as I cannot comment under the question for technical reasons :)

C# MySQL Change Credentials or Logout on the fly

I am currently developing a C# WPF application. It is only used by a small amount of people/devices.
To make things easier I decided to talk directly to the MySQL db.
Now I wanted to be able to switch the current User / db Credentials with the click of a button, or be able to implement a logout feature.
I just currently tried this:
public DBConnect()
{
Initialize(null, null);
}
private void Initialize(string uid, string password)
{
string connectionstring;
connectionstring = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionstring);
}
public void setCredentials(string uid, string password)
{
Initialize(uid, password);
}
public void destroyCredentialsAndConnection()
{
connection = null;
}
But apparently while Debugging I found out, that the old connection string is still cached statically by the MySQLConnection Class in the background.
Currently it does look like my approach is working, but I'm actually worried about the security of that implementation to list a few concerns:
memory dumps (usage of strings for passwords that can not be encrypted and may not be removed for quite some time by the garbage collector)
memory dumps (the fact that the connection string is being cached even after a "logout")
network traffic sniffing (is the connection between the database and my C# application encrypted)?
physical access to the server (is the MySQL database stored encrypted on the harddrive)?
Is there any better (more secure) way to switch credentials or to completely log the user out?
I did not really find any similar attempts here or anywhere else while doing research.
And if I would try to develop a php backend would that be safer without much experience? And could I still use my audit tables that I have created based on MySQL Triggers?
If I am understanding what you are asking correctly, you could try making a method to build the connection string based on user input, and inject the user's credentials into the connection string each time the method is called.
static SqlConnection Connection()
{
string UserName = UserNameField.Text;
string Password = PasswordField.Text;
SqlConnection Connection = new SqlConection("Server=ServerName,Port;Initial Catalog=Catalog;User Id=" + UserName + ";Password=" + Password + ";");
return Connection;
}

Database connection closure location in try catch/using

Which is better to make sure that the db connection is closed if the execution fails?
try
{
using (var mySqlConnection = new MySqlConnection(DatabaseManagement.DatabaseConnectionString))
{
DatabaseManagement.DatabaseCommand = mySqlConnection.CreateCommand();
DatabaseManagement.DatabaseCommand.CommandText = "INSERT INTO lastlaptimes Values ('" + UserObject.UserName + "','" + _lastLapTime + "')";
mySqlConnection.Open();
DatabaseManagement.DatabaseCommand.ExecuteNonQuery();
}
}
catch (MySqlException exception)
{
Logger.Error(exception);
}
Or this:
using (var mySqlConnection = new MySqlConnection(DatabaseManagement.DatabaseConnectionString))
{
try
{
DatabaseManagement.DatabaseCommand = mySqlConnection.CreateCommand();
DatabaseManagement.DatabaseCommand.CommandText = "INSERT INTO lastlaptimes Values ('" + UserObject.UserName + "','" + _lastLapTime + "')";
mySqlConnection.Open();
DatabaseManagement.DatabaseCommand.ExecuteNonQuery();
}
catch (MySqlException exception)
{
mySqlConnection.Close();
Logger.Error(exception);
}
}
I'm having issue with too many connections against the db, and I'm wondering if my first approach is leading to the problem with the connections, as the code is called numerous times and a new connection is opened and fails again and increasing the connections by 1.
Thanks for any help.
The only difference between these is whether or not you are explicitly calling the Close statement (both have a using statement, which runs Dispose automatically).
So the real question here is - does Dispose close the connection or do you need to call it explicitly? I believe the answer is that Dispose will call this for you (see this question). What that means is either works well - pick whichever you favor (I suppose the first is technically one line less code...)

ExecuteNonQuery() not saving any record

I'm working a WinForms based C# tool which has an attached MDF file based database. I'm trying to use the SqlCommand.ExecuteNonQuery() method to save a record to this attached MDF database, but the record is not saved. No error or exception occurs; only problem is that the record is not actually saved.
I have a Console.WriteLine at the top which shows the query I'm trying to run. Its correct syntax-wise, and if I copy-paste it from the output windows and run it separately, it works.
I have correctly defined the connection string as the following, and it works fine for fetching records:
public static String connectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\TestBuildDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
Here the function I'm using to save records:
public static void PerformDBWriteTransaction(string inputSQLStatement)
{
Console.WriteLine(inputSQLStatement);
DataTable returnDataTable = new DataTable();
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString = connectionString;
SqlCommand cmd = new SqlCommand();
cmd.Connection = sqlConnection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = inputSQLStatement;
cmd.Connection.Open();
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
errorMessages.Clear();
errorMessages.Append("The following errors were found in the SQL statement:\n\n");
for (int i = 0; i < ex.Errors.Count; i++)
{
errorMessages.Append("Index #" + i + "\n" +
"Message: " + ex.Errors[i].Message + "\n" +
"LineNumber: " + ex.Errors[i].LineNumber + "\n" +
"Source: " + ex.Errors[i].Source + "\n" +
"Procedure: " + ex.Errors[i].Procedure + "\n");
}
MessageBox.Show(errorMessages.ToString());
}
finally
{
cmd.Connection.Close();
}
}
Can someone tell me what might be the problem ? Do I need to perform a 'commit' somehow ?
EDIT:
I have found the problem, and have written up a solution below .. Thanks to all who helped me out though :)
I found the problem ! It was very simple, and it was stupid really :) .. The code above is all correct .. Yes, people pointed out optimizations, etc, but still the code above was correct.
The problem was that when I imported the TestDB.MDF file into my Visual 2010 project, a copy of that was made inside the project's folder. When you run/debug the program, another copy of the this file is made and is put in the \bin\Debug\ folder. In the connection string I was using, I had mentioned: AttachDbFilename=|DataDirectory|\TestBuildDB.mdf .. This meant that all reads/writes were done to the copy in the bin\Debug folder. However, the TestDB.MDF file I was looking into to verify if records were inserted or not, was in the project's folder ! So basically, there were two MDF files, and I was writing the records into one file, but was trying to find them in the other :)
When you add an MDF file into your VS2010 Project, VS2010 by default makes a connection to that MDF file, from where you can browse the stuff in that MDF file .. The MDF file used for this purpose was the one placed in the project's folder, NOT the one in bin\Debug\ folder. And like I said earlier, my code used the one in the bin\Debug folder :)
So what I've done now is that I've removed the Test.MDF file reference from my project, which removes the copy present in the project's folder. However, I DO have a copy of TestDB.MDF file in the bin\Debug\ folder, which I connect to from within my application. And if I want to browse the MDf file outside my project, I use SQL Management Studio. The only problem here is that an MDF file can only be used by one program at a given time. So if I have to use it with my application, I have to take it offline from SQL Management studio, and vica versa !
I hope this explanation helps someone out there :)
The solution to this problem is very simple just give the full path of the original MDF file in the connection String like this:
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=**C:\VISUAL STUDIO 2012\PROJECTS\ENGLISHTOHINDIDICTIONARY\ENGLISHTOHINDIDICTIONARY\DICTIONARY.MDF**;Initial Catalog=Dictionary;Integrated Security=false"
providerName="System.Data.SqlClient"
That's it, your problem is solved.
I had the same challenge, I simply changed the database property "Copy to Output Directory" from "Copy always" to "Do not copy" then moved my database.mdf (drag & drop from my IDE) into the bin\debug folder.
Tip:
The bin directory is normally hidden, use the "Show All Files" to display it
Provide a catch clause for all Exceptions. If there something wrong other than SqlException, you will never see what is it and your db will neved be updated. Imagine there is a FormatException...
Also check the return of ExecuteNonQuery : it's the number of rows affected by the query.
First, you should always wrap up your IDisposable objects in a using to ensure they're closed and disposed of properly (and that connection pooling can do its thing). Second, when modifying data wrap up your sql in a transaction to maintain data integrity.
Try the following code and see if any exceptions are raised. I wouldn't normally recommend catching Exception as it's too general, I'd let that bubble up to the calling mechanism and handle it there - but for this instance it will show you any and all issues. I think your particular issue is at the .Open stage of the connection, so try stepping through.
public static void PerformDBWriteTransaction(string inputSQLStatement)
{
DataTable returnDataTable = new DataTable();
try
{
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
using (SqlTransaction sqlTrans = sqlConnection.BeginTransaction())
{
try
{
using (SqlCommand cmd = new SqlCommand(inputSQLStatement, sqlConnection))
{
cmd.CommandType = CommandType.Text;
cmd.Transaction = sqlTrans;
cmd.ExecuteNonQuery();
}
}
catch (SqlException sqlEx)
{
sqlTrans.Rollback();
throw sqlEx;
}
sqlTrans.Commit();
}
}
}
catch (Exception ex)
{
errorMessages.Clear();
errorMessages.Append("The following errors were found in the SQL statement:\n\n");
for (int i = 0; i < ex.Errors.Count; i++)
{
errorMessages.Append("Index #" + i + "\n" +
"Message: " + ex.Errors[i].Message + "\n" +
"LineNumber: " + ex.Errors[i].LineNumber + "\n" +
"Source: " + ex.Errors[i].Source + "\n" +
"Procedure: " + ex.Errors[i].Procedure + "\n");
}
MessageBox.Show(errorMessages.ToString());
}
}
Hi I am working on library database when I add student record executionNonQuery
shows error like invalid column name page opens but saving data from not happening.
Here I have given the code statement
public partial class add_student_info : Form
{
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-SPT6GLG\SQLEXPRESS;Initial Catalog=library_managment;Integrated Security=True;Pooling=False");
public add_student_info()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into student_info values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "','" + textBox4.Text + "'," + textBox5.Text + "," + textBox6.Text + "," + textBox7.Text + ")";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Student recorc addedd sussfully");
}
}
}

button sometimes redirects to "This page cannot be displayed"

I have an ASP.NET c# web application published to a server of ours. It consists of three pages, each with a form on them, sort of like a 3-page login. After the third page's form is validated, it sends the user to a different site. Here's a little diagram so I can explain it better:
NamePage ---> DateOfBirthPage ---> IDNumberPage ---> OtherSite
This has been working great in all of our development tests and stress tests. However, after we put it into production, occasionally when the "Next" button on the IDNumberPage is clicked, the user sees "This page cannot be displayed" with a "diagnose connection problems" button. When this occurs for one user, the same problem occurs for all users (meaning once it happens, nobody can fully authenticate). NamePage and DateOfBirthPage always work, and when the crash occurs, the IDNumberPage link doesn't change, suggesting that the crash is occurring on this side of the application, not after it redirects to OtherSite. I have friendly HTTP errors turned off but it's not showing any errors on the page. If we go into the server and restart the application, it works again.
The frustrating part is that we can't replicate this error to see how/why it's occurring.
Some things that are noteworthy:
Each page uses one query on a MS SQL server database
Each page passes up to 4 Session variables (only small Strings containing what was entered into the textbox form on the previous page(s))
The session is abandoned when the final "next" button is clicked.
All resultsets/connections/commands are closed before redirect.
Redirects use the overloaded version using Response.Redirect(siteName, false)
Sorry if all of this is very vague, but the problem itself has done an oddly good job of hiding from us. We have tried hammering the server with test requests (many at once, many over a period of time, etc) and different combinations of logging in/trying to break the page in general, to no avail. Can anyone suggest some things to try to diagnose/fix/replicate this problem?
Edit: The click function on IDNumberPage's code-behind that is causing the problem:
{ SqlConnection dbconn = new SqlConnection(Application["dbconn"].ToString());
SqlCommand sqlValidate = dbconn.CreateCommand();
dbconn.Open();
sqlValidate.CommandText = "SELECT lastName, csn FROM Demographics WHERE lastName = '" + Session["lastName"].ToString() + "' " +
"AND dob = '" + Session["dobCheck"].ToString() + "' AND mrn = " + strMRN;
SqlDataReader results = sqlValidate.ExecuteReader();
if (results.HasRows)
{
string csn = "";
while (results.Read())
{
if (!String.IsNullOrEmpty(results["csn"].ToString()))
{
csn = results["csn"].ToString();
break;
}
}
string url = Application["surveyUrlString"] + "&lastname=" + Session["lastName"].ToString() + "&mrn=" + strMRN + "&dobday=" + Session["dobday"].ToString()
+ "&dobmonth=" + Session["dobmonth"].ToString() + "&dobyear=" + Session["dobyear"].ToString() + "&csn=" + csn;
results.Close();
dbconn.Close();
Response.Redirect(url, false);
}
The problem is due to leaking sql connections.
You aren't properly disposing of your resources. Over time these are going to stack up in the connection pool until you reach a point where the pool overflows and your app dies. Resetting will obviously fix the issue.
Also this issue might not show up in "stress" tests depending on how, exactly you are testing the application.
The solution is to reformat that code to handle your database call better.
{
string url = string.empty;
using (SqlConnection dbconn = new SqlConnection(Application["dbconn"].ToString())) {
using (SqlCommand sqlValidate = dbconn.CreateCommand()) {
dbconn.Open();
sqlValidate.CommandText = "SELECT lastName, csn FROM Demographics WHERE lastName = '" + Session["lastName"].ToString() + "' " +
"AND dob = '" + Session["dobCheck"].ToString() + "' AND mrn = " + strMRN;
using (SqlDataReader results = sqlValidate.ExecuteReader()) {
if (results.HasRows) {
string csn = "";
while (results.Read())
{
if (!String.IsNullOrEmpty(results["csn"].ToString()))
{
csn = results["csn"].ToString();
break;
}
}
url = Application["surveyUrlString"] + "&lastname=" + Session["lastName"].ToString() + "&mrn=" + strMRN + "&dobday=" + Session["dobday"].ToString()
+ "&dobmonth=" + Session["dobmonth"].ToString() + "&dobyear=" + Session["dobyear"].ToString() + "&csn=" + csn;
}
} // sqldatareader
} // using sqlcommand
} // using sqlconnection
if (!String.IsNullOrEmpty(url)) {
Response.Redirect(url, false);
}
}
notice that you aren't redirecting until after everything is cleaned up.
SqlConnection, SqlCommand and SqlDataReader all implement IDisposable. You have to properly clean up after use otherwise the resources will be left hanging. The "best" way of doing this is to wrap them in a using clause. This ensures they are properly removed once the code block is exited as they aren't garbage collected like other objects.
Also note that the above code has a good side benefit. Namely, in case of error it STILL cleans up after you. Whereas the original code that was posted would clearly leak in the event the DB server didn't respond or threw some type of error when running the query.
The query could error out depending on the values contained in dboCheck, lastname and mrn parameters. For example, what if "BOB" was passed in for the dobCheck field, or Nothing was passed in for mrn... If dob is a datetime field in your database then the query will throw an error that will result in a leaked connection. Do that enough times and your site is down.
Upon further review, I'm guessing that's probably what is happening: people are putting in garbage data that your app is allowing to get to this point and the query is failing. Most likely this isn't something that you've handled in your test cases.
Side note: Please don't create your sql statements by using concatentation. That is a complete security no no. At the very least, parameterize those queries.
Nice answer Chris, one question aren't the .Close() statements missing in the Using statements?. Both for the connection and the datareader:
results.Close();
} // using sqldatareader
} // using sqlcommand
dbconn.Close();
} // using sqlconnection

Categories

Resources