I have read the numerous posts on why you should give the using statement preference over manually doing .Open() then .Close() and finally .Dispose().
When I initially wrote my code, I had something like this:
private static void doIt(string strConnectionString, string strUsername)
{
SqlConnection conn = new SqlConnection(strConnectionString);
try
{
conn.Open();
string strSqlCommandText = $"CREATE USER {strUsername} for LOGIN {strUsername} WITH DEFAULT SCHEMA = [dbo];";
SqlCommand sqlCommand = new SqlCommand(strSqlCommandText, conn);
var sqlNonReader = sqlCommand.ExecuteNonQuery();
if (sqlNonReader == -1) Utility.Notify($"User Added: {strUsername}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
conn.Close();
conn.Dispose();
}
}
and this works... no problem. but only ONCE.
so, if I do something like this:
private static void doItLots(string strConnectionString, string strUsername)
{
for(int i=0; i<10; i++)
{
doIt(strConnectionString, $"{strUsername}_{i}");
}
}
it works the FIRST time when i=0, but any subsequent iterations fail with Cannot open database "myDbName" requested by the login. The login failed.
However, if I go back and comment out the conn.Dispose(); line, then it works fine on all iterations.
The problem is simply that if I want to do the .Dispose() part outside of the method, then I am forced to pass a SqlConnection object instead of simply passing the credentials, potentially making my code a bit less portable and then I need to keep the connection around longer as well. I was always under the impression that you want to open and close connections quickly but clearly I'm misunderstanding the way the .Dispose() command works.
As I stated at the outset, I also tried doing this with using like this...
private static void doIt(string strConnectionString, string strUsername)
{
using (SqlConnection conn = new SqlConnection(strConnectionString))
{
try
{
conn.Open();
string strSqlCommandText = $"CREATE USER {strUsername} for LOGIN {strUsername} WITH DEFAULT SCHEMA = [dbo];";
SqlCommand sqlCommand = new SqlCommand(strSqlCommandText, conn);
var sqlNonReader = sqlCommand.ExecuteNonQuery();
if (sqlNonReader == -1) Utility.Notify($"User Added: {strUsername}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
conn.Close();
}
}
}
and this does the exact same thing as the initial code with .Dispose() called manually.
Any help here would be greatly appreciated. I'd love to convert to the using statements but having trouble figuring out how to write reusable methods that way...
UPDATE:
I have narrowed it down a bit. The issue is NOT the iterations or making the calls over-and-over again. But I am still getting an access error. Here is the code:
string strConnectionString = $#"Data Source={StrSqlServerDataSource};Initial Catalog={StrDatabaseName};User id={StrSqlServerMasterUser};Password={StrSqlServerMasterPassword}";
using (SqlConnection connUserDb = new SqlConnection(strConnectionString))
{
try
{
Utility.Notify($"Connection State: {connUserDb.State.ToString()}"); // Responds as 'Closed'
connUserDb.Open(); // <-- throws error
Utility.Notify($"Connection State: {connUserDb.State.ToString()}");
Utility.Notify($"MSSQL Connection Open... Adding User '{strUsername}' to Database: '{strDatabaseName}'");
string sqlCommandText =
//$#"USE {StrDatabaseName}; " +
$#"CREATE USER [{strUsername}] FOR LOGIN [{strUsername}] WITH DEFAULT_SCHEMA = [dbo]; " +
$#"ALTER ROLE [db_datareader] ADD MEMBER [{strUsername}]; " +
$#"ALTER ROLE [db_datawriter] ADD MEMBER [{strUsername}]; " +
$#"ALTER ROLE [db_ddladmin] ADD MEMBER [{strUsername}]; ";
using (SqlCommand sqlCommand = new SqlCommand(sqlCommandText, connUserDb))
{
var sqlNonReader = sqlCommand.ExecuteNonQuery();
if (sqlNonReader == -1) Utility.Notify($"User Added: {strUsername} ({sqlNonReader})");
}
result = true;
}
catch (Exception ex)
{
Utility.Notify($"Creating User and Updating Roles Failed: {ex.Message}", Priority.High);
}
finally
{
connUserDb.Close();
Utility.Notify($"MSSQL Connection Closed");
}
}
return result;
}
The error I am getting here is: Cannot open database requested by the login. The login failed.
One clue I have is that prior to this, I was running this same code with two changes:
1) uncommented the USE statement in the sqlCommandText
2) connected to the Master database instead
When I did that, it didn't work either, and instead I got this error: The server principal is not able to access the database under the current security context.
If I go into SSMS and review the MasterUser they are listed as db_owner and I can perform any activities I want, including running the command included in the code above.
I rewrote all the code to make use of a single connection per the recommendations here. After running into the "server principal" error, I added one more connection to attempt to directly connect to this database rather than the master.
UPDATE 2:
Here is another plot twist...
This is working from my local computer fine (now). But, not (always) working when run from an Azure Webjob that targets an Amazon Web Services (AWS) Relational Database Server (RDS) running MSSQL.
I will have to audit the git commits tomorrow, but as of 5p today, it was working on BOTH local and Azure. After the last update, I was able to test local and get it to work, but when run on Azure Webjob it failed as outlined above.
SqlConnection implements IDisposable. You don't call dispose or close.
try{
using (SqlConnection conn = new SqlConnection(strConnectionString))
{
conn.Open();
string strSqlCommandText = $"CREATE USER {strUsername} for LOGIN {strUsername} WITH DEFAULT SCHEMA = [dbo];";
SqlCommand sqlCommand = new SqlCommand(strSqlCommandText, conn);
var sqlNonReader = sqlCommand.ExecuteNonQuery();
if (sqlNonReader == -1) Utility.Notify($"User Added: {strUsername}");
}}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Related
I have the following INSERT method in a C# web project. If I run the project without MySQL connection poling everything works fine, but when I activate Pooling=True in the DB connection string this method stops working, the insert statements never complete.
I realized how to modify the code to make it work, but I would like to understand what is happening and I hope you could help.
When I comment line //myR.Close(); everything works fine.
using MySql.Data.MySqlClient;
//query example consulta="INSERT INTO users (id, name) VALUES (1, 'Rob');
public static MySqlConnection GetWriteConnection()
{
string connStr = MySqlConnectionStrings.WriteConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
return conn;
}
public static MySqlConnection GetReadConnection()
{
string connStr = MySqlConnectionStrings.ReadConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
return conn;
}
public static bool Insert(string consulta)
{
MySqlConnection conn = BdaHelper.GetWriteConnection();
conn.Open();
using (conn)
{
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
MySqlCommand micomando = new MySqlCommand(consulta, conn);
micomando.ExecuteNonQuery(); //still not working
return true;
}
catch (Exception ex)
{
return false;
}
}
}
My app has also multi-thread concurrency and two types of database connections, one specifically for only-read purposes and other different for write. When an insert statement fails I don't get any error simply the change doesn't commit in the database. Reading the article in the comments I don't think this applies to this issue but I would add an example of my main program:
MySqlConnection readConnection = BdaHelper.GetReadConnection();
using (readConnection)
{
var users = GetUsers(readConnection);
var credentials = GetCredentials(readConnection);
//Example is the query that fails don't giving any exception
Insert("INSERT INTO login_log (id_user, date) VALUES (1, now())");
}
May the problem be caused because there are two concurrent connections?
I shouldn't reuse read connection, even is a different connection than the write connection?
I'm attempting to implement an Application Role with my connections in a C# Winforms Desktop application. Everything works fine with the first connection, and I am closing it properly with a using{} construct. However, when I create a second connection, I get the "Cannot continue the execution because the session is in the kill state" error. Any idea as to why I'm getting this error and how to troubleshoot? Here is my code where I get the error along with my method to set the application role:
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
oAppRole.setApplicationRole(connection);
string query = "<sql statement here>";
using (var cmd = new SqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("#EmpID", empID);
cmd.Parameters.AddWithValue("#ExpDate", priorExpDate);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dtReturnTable);
}
}
}
catch (Exception ex)
{
throw ex;
}
public bool setApplicationRole(SqlConnection connection)
{
bool retVal = true;
string procName = "sys.sp_setapprole";
SqlCommand cmd = new SqlCommand(procName);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Connection = connection;
// Parameter for Application Role Name
SqlParameter parmAppRoleName = new SqlParameter();
parmAppRoleName.ParameterName = "#rolename";
parmAppRoleName.Value = "myAppRole";
cmd.Parameters.Add(parmAppRoleName);
// Parameter for Application Role Password
SqlParameter parmAppRolePwd = new SqlParameter();
parmAppRolePwd.ParameterName = "#password";
parmAppRolePwd.Value = "myPassword";
cmd.Parameters.Add(parmAppRolePwd);
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
retVal = false;
throw(ex);
}
return retVal;
}
First, Application Roles are rarely the right security approach. They are designed to work in combination with End Users connecting with Windows Integrated Authentication as low-privilege users. This enables the Application code to use a semi-secret password to elevate the session from the end-user's identity to the Application Role. This is really a desktop, client/server app solution. And as such it never really played nicely with Connection Pooling.
When a Connection Pool attempts to reset a connection which has had an Application Role set, an error is thrown. So to get Application Roles to work with SqlConnection you either have to disable Connection Pooling (on by default in all applications, but can be disabled in the connection string), or sp_unsetapprole before returning the connection to the pool.
For alternative approaches see Application Role Alternatives.
I write a C# program which uses a database, Matches.mdf.
I want to test the database file existence, using File.Exists routine (codes will come at the end of the question). If the file doesn't exist, the program creates a new database with the above name. To test the database existence routine, I renamed the database file, but when I wanted to create the database, I got the following error message: Database "Matches" already exists, please specify a different name.
At a second test, I used a database dropping routine before calling the creating routine. Big mistake. Every time I try to create the Matches.mdf database, I get the following error message:
I am sure that the cause of this error message is me, tinkering around, because the same database creation and deletion routines worked fine before.
I know I can solve the problem by changing the path of the database file, but I want to know what exactly I broke up here so I know for next time.
What I am asking is: what can I do to solve the above error?
Later edit: I tried to manually recreate the Matches.mdf using the query tool from SQL Server Object Explorer from VS 2019. Worked perfectly, but I don't think it's a good solution long term.
Necessary codes:
Variable declarations:
static readonly string DatabaseFolder = Path.GetDirectoryName(Application.ExecutablePath) + "\\db";
readonly string DatabaseFile = DatabaseFolder + "\\Matches.mdf";
readonly string DatabaseLog = DatabaseFolder + "\\MatchesLog.ldf";
The function that checks the database file existence:
public bool DatabaseExists()
{
return File.Exists(DatabaseFile);
}
The database creation routine:
private bool CreateDatabaseFile()
{
SqlConnection MyConn = new SqlConnection(CreateDatabaseConnectionString);
string Str = "Create Database Matches on Primary (Name=Matches, Filename='#DatabaseFile') log on (Name=MatchesLog, Filename='#DatabaseLog')";
SqlCommand DatabaseCreationCommand = new SqlCommand(Str, MyConn);
DatabaseCreationCommand.Parameters.Add("#DatabaseFile", SqlDbType.Text).Value = DatabaseFile;
DatabaseCreationCommand.Parameters.Add("#DatabaseLog", SqlDbType.Text).Value = DatabaseLog;
try
{
MyConn.Open();
DatabaseCreationCommand.ExecuteNonQuery();
}
catch (SqlException S)
{
MessageBox.Show(S.Message);
return false;
}
catch (IOException I)
{
MessageBox.Show(I.Message);
return false;
}
catch (InvalidOperationException I)
{
MessageBox.Show(I.Message);
return false;
}
catch (InvalidCastException I)
{
MessageBox.Show(I.Message);
return false;
}
finally
{
MyConn.Close();
}
return true;
}
The database deleting routine:
public void DeleteDatabase()
{
string Str;
SqlConnection MyConn = new SqlConnection(CreateDatabaseConnectionString);
Str = "Alter database Matches set single_user with rollback immediate\r\ndrop database Matches";
SqlCommand command = new SqlCommand(Str, MyConn);
try
{
MyConn.Open();
command.ExecuteNonQuery();
}
catch (SqlException S)
{
MessageBox.Show(S.Message);
}
catch (IOException I)
{
MessageBox.Show(I.Message);
}
catch (InvalidOperationException I)
{
MessageBox.Show(I.Message);
}
catch (InvalidCastException I)
{
MessageBox.Show(I.Message);
}
finally
{
MyConn.Close();
}
}
As it is said here and confirmed by Jeroen Mostert, Create database does not accept queries. The database was created before, using some string concatenation. Afterwards the query string was parametrized, without realizing that this command doesn't take parameters. This is why changing the creating database query to
Create Database Matches
works perfectly.
Well, live and learn!
Connection string that my app is using to connect to DB is the following:
private const string oradb = "Data Source=(DESCRIPTION=(ADDRESS_LIST="
+ "(ADDRESS=(PROTOCOL=TCP)(HOST=host.name)(PORT=1521)))"
+ "(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=service.name)));"
+ "User Id=myusername;Password=mypass;";
In all DB access points of my app I am using the following pattern:
OracleConnection conn = new OracleConnection(oradb);
try
{
Console.WriteLine("Opening DB Connection...");
conn.Open();
string queryString = string.Format(#"SELECT ...");
using (OracleCommand command = new OracleCommand(queryString, conn))
{
using (OracleDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
...
}
}
}
}
catch (Exception e)
{
Console.WriteLine("Exception occured during DB access: {0}", e.Message);
dbr.Error = e.Message;
}
finally
{
Console.WriteLine("Closing DB connection");
conn.Close();
conn.Dispose();
}
For sure I am properly handling exceptions and in try/catch/finally closing AND disposing connection object. However, often I am receiving oracle service message that I am holding oracle sessions. Moreover, if I just leave my app open and next day try to make operation, I am getting ora-12537 network session end of file exception first time, then second attempt is going through. After some reading it looks like I have to disable connection pool. If this is the right way to solve, how to disable pool? If not, then what other thing can be wrong?
You could add Pooling=False in the connection string, but this means a new connection is created each time.
+ "User Id=myusername;Password=mypass;Pooling=False;";
Take a look at this article, it might help with your issue. Also, take a look at this website page, specifically the Using Connection Pooling section
I'm using asp.net c# and upload a SqLite database to a server and then I do some inserting and updating. The problem is that sometimes (I think it's when somethings go wrong with the updating or so) the database gets locked. So the next time I try to upload a file again it's locked and I get an error saying "The process cannot access the file because it is being used by another process". Maybe the database file isn't disposed if something goes wrong during the transaction? The only thing to solve this problem is restarting the server.
How can I solve it in my code so I can be sure it's always unlocked even if something goes wrong?
This is my code:
try
{
string filepath = Server.MapPath("~/files/db.sql");
//Gets the file and save it on the server
((HttpPostedFile)HttpContext.Current.Request.Files["sqlitedb"]).SaveAs(filepath);
//Open the database
SQLiteConnection conn = new SQLiteConnection("Data Source=" + filepath + ";Version=3;");
conn.Open();
SQLiteCommand cmd = new SQLiteCommand(conn);
using (SQLiteTransaction transaction = conn.BeginTransaction())
{
using (cmd)
{
//Here I do some stuff to the database, update, insert etc
}
transaction.Commit();
}
conn.Close();
cmd.Dispose();
}
catch (Exception exp)
{
//Error
}
You could try placing the Connection in a using block as well, or calling Dispose on it:
//Open the database
using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + filepath + ";Version=3;")) {
conn.Open();
using (SQLiteCommand cmd = new SQLiteCommand(conn)) {
using (SQLiteTransaction transaction = conn.BeginTransaction()) {
//Here I do some stuff to the database, update, insert etc
transaction.Commit();
}
}
}
This will ensure that you're disposing of the connection object's correctly (you're not at the moment, only closing it).
Wrapping them in using blocks ensures that Dispose is called even if an exception happens - it's effectively the same as writing:
// Create connection, command, etc objects.
SQLiteConnection conn;
try {
conn = new SQLiteConnection("Data Source=" + filepath + ";Version=3;");
// Do Stuff here...
}
catch (exception e) {
// Although there are arguments to say don't catch generic exceptions,
// but instead catch each explicit exception you can handle.
}
finally {
// Check for null, and if not, close and dispose
if (null != conn)
conn.Dispose();
}
The code in the finally block is going to be called regardless of the exception, and helps you clean up.
An asp.net application is multithreaded in the server.
You can't do simultaneous writing (insert, select, update...) because the whole db is locked. Simultaneously selecting is allowed when no writing is happening.
You should use the .NET ReaderWriterLock class: http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlock.aspx
Shouldn't you do cmd.Dispose() before conn.Close()? I don't know if it makes any difference, but you generally want to clean things up in the opposite of initialization order.
In short, SQLite handles unmanaged resources slightly differently than other providers. You'll have to explicitly dispose the command (which seems to work even if you are working with the reader outside of the using() block.
Read this thread for more flavor:
http://sqlite.phxsoftware.com/forums/p/909/4164.aspx