class CommonConnection
{
public class dStructure
{
public static string ConnectionString = "";
}
public SqlConnection Conn;
#region "Connection Procedures"
public string ConnectionString
{
get
{
string sConn = string.Empty;
sConn = @"Server=ServerName;Initial Catalog=Database;User ID=userid;Password=password;";
dStructure.ConnectionString = sConn;
return dStructure.ConnectionString;
}
}
public void cnOpen()
{
try
{
if (Conn == null)
{
Conn = new System.Data.SqlClient.SqlConnection();
}
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
Conn.ConnectionString = ConnectionString;
Conn.Open();
}
catch (SqlException e)
{
SqlConnection.ClearAllPools();
throw e;
}
catch (Exception ex)
{
throw ex;
}
}
public void cnClose()
{
try
{
if ((Conn != null))
{
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
Conn = null;
}
}
#endregion
public int ExecuteQuery(string strQuery, Int16 TimeOut = 30)
{
int RecordsAffected;
SqlCommand cmd;
try
{
cnOpen();
cmd = new SqlCommand(strQuery, Conn);
cmd.CommandTimeout = TimeOut;
RecordsAffected = cmd.ExecuteNonQuery();
return RecordsAffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
cnClose();
cmd = null;
}
}
}
// Tried another option like below,
public int ExecuteQuery(string strQuery, short TimeOut = 10)
{
SqlConnection NewConn = new SqlConnection();
try
{
if (NewConn == null)
{
NewConn = new System.Data.SqlClient.SqlConnection();
}
if (NewConn.State == ConnectionState.Open)
{
NewConn.Close();
}
NewConn.ConnectionString = "Server=ServerName;Initial Catalog=Database;User ID=userid;Password=password;";
NewConn.Open();
return new SqlCommand(strQuery, NewConn)
{
CommandTimeout = ((int)TimeOut)
}.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
NewConn.Close();
}
}
But still getting same issue. Its desktop application, multi threaded. But while more query load on this, i'm getting Not allowed to change the 'ConnectionString' property. The connection's current state is open. Note that not every time i get this issue, only when more query are executing.
// Update 2 As per suggested in another question, i tried with below code but problem remains same.
public int ExecuteQuery(string strQuery, short TimeOut = 10)
{
int executeReader = 0;
try
{
using (SqlConnection connection = new SqlConnection(@"Server=Server;Initial Catalog=DB;User ID=id;Password=Password;"))
{
try
{
connection.Open();
SqlCommand command = new SqlCommand(strQuery, connection);
command.CommandType = CommandType.Text;
command.CommandTimeout = TimeOut;
executeReader = command.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
}
return executeReader;
}
catch (Exception ex)
{
throw ex;
}
}
As suggested there, using command used default IDisposable so no need to close connection.