I want to execute methods within a Sql Connection. I want to use the C# "using" object since it makes the connection safe.
The reason I want to execute queries in this way is so I can reuse this connection and build the queries in a separate class/location.
class foo
{
public void connectionMethod()
{
using(SqlConnection aConnection=new SqlConnection('ConnectionString')
{
//Query here.
}
}
}
Thanks for your help!
In the class you where you want to build your queries, declare each method to accept a SqlConnection parameter.
// query method
public void SomeQuery(SqlConnection connection)
{
...
}
// use it
using(SqlConnection aConnection=new SqlConnection('ConnectionString')
{
aConnection.Open();
otherClass.SomeQuery(aConnection);
}
Passing a parameter will create a copy of the reference to the SqlConnection object which will be in scope within the called method. Make sure you don't leak it outside the method though.
Related
I am writing SQL Server integration tests using xUnit.
My tests look like this:
[Fact]
public void Test()
{
using (IDbConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
connection.Query(#$"...");
//DO SOMETHING
}
}
Since I am planning to create multiple tests in the same class I was trying to avoid creating a new SqlConnection every time. I know that xUnit framework per se creates an instance of the class per each running test inside it.
This means I could make the creation of the SqlConnection in the constructor since anyway a new one will be created every time a new test run.
The problem is disposing it. Is it good practice or do you see any problem in disposing manually the SqlConnection at the end of each test?
Such as:
public class MyTestClass
{
private const string _connectionString = "...";
private readonly IDbConnection _connection;
public MyTestClass()
{
_connection = new SqlConnection(_connectionString));
}
[Fact]
public void Test()
{
_connection.Open();
_connection.Query(#$"...");
//DO SOMETHING
_connection.Dispose();
}
}
I was trying to avoid creating a new SqlConnection every time.
It's okay to create and dispose a new SqlConnection over and over. The connection instance is disposed, but the underlying connection is pooled. Under the hood it may actually use the same connection repeatedly without closing it, and that's okay.
See SQL Server Connection Pooling.
So if that's your concern, don't worry. What you are doing in the first example is completely harmless. And however your code is structured, if you're creating a new connection when you need it, using it, and disposing it, that's fine. You can do that all day long.
If what concerns you is the repetitive code, I find this helpful. I often have a class like this in my unit tests:
static class SqlExecution
{
public static void ExecuteSql(string sql)
{
using (var connection = new SqlConnection(GetConnectionString()))
{
using (var command = new SqlCommand(sql, connection))
{
connection.Open();
command.ExecuteNonQuery();
}
}
}
public static T ExecuteScalar<T>(string sql)
{
using (var connection = new SqlConnection(GetConnectionString()))
{
using (var command = new SqlCommand(sql, connection))
{
connection.Open();
return (T)command.ExecuteScalar();
}
}
}
public static string GetConnectionString()
{
// This may vary
}
}
How you obtain the connection string may vary, which is why I left that method empty. It might be a configuration file, or it could be hard-coded.
This covers the common scenarios of executing something and retrieving a value, and allows me to keep all the repetitive database code out of my tests. Within the test is just one line:
SqlExecution.ExecuteSql("UPDATE WHATEVER");
You can also use dependency injection with xUnit, so you could write something as an instance class and inject it. But I doubt that it's worth the effort.
If I find myself writing more and more repetitive code then I might add test-specific methods. For example the test class might have a method that executes a certain stored procedure or formats arguments into a query and executes it.
You can also do dependency injection with xUnit so that dependencies are injected into the class like with any other class. There are lots of answers about this. You may find it useful. Maybe it's the reason why you're using xUnit. But something simpler might get the job done.
Someone is bound to say that unit tests shouldn't talk to the database. And they're mostly right. But it doesn't matter. Sometimes we have to do it anyway. Maybe the code we need
to unit test is a stored procedure, and executing it from a unit test and verifying the
results is the simplest way to do that.
Someone else might say that we shouldn't have logic in the database that needs testing, and I agree with them too. But we don't always have that choice. If I have to put logic in SQL I still want to test it, and writing a unit test is usually the easiest way. (We can call it an "integration test" if it makes anyone happy.)
There's a couple different things at play here. First, SqlConnection uses connection pooling so it should be fine to create/dispose the connections within a single test.
Having said that disposing of the connections on a per test class basis would also be doable. XUnit will dispose of test classes that are IDisposable. So either would work. I'd suggest it's cleaner to create/dispose them within the test.
public class MyTestClass : IDisposable
{
const string ConnectionStr = "";
SqlConnection conn;
public MyTestClass()
{
this.conn = new SqlConnection(ConnectionStr);
}
public void Dispose()
{
this.conn?.Dispose();
this.conn = null;
}
public void Test()
{
using (var conn = new SqlConnection(ConnectionStr))
{
}
}
}
I'm new to .Net MVC and I wanted to run a raw query on my UserInRoles table.
I think I will need a database context to run it.
I'm unsure what context to use. Can some one recommend me a direction to take? Currently, the ObjectContext does not allow me to instantiate without a connection string. Is directly grabbing the connection string from web config correct?
Error 1 'System.Data.Entity.Core.Objects.ObjectContext' does not contain a constructor that takes 0 arguments
using (var ctx = new ObjectContext())
{
string query = "INSERT INTO dbo.webpages_UsersInRoles (RoleId,UserId) values ("+chk+","+id+");";
ExecuteSql(ctx,query);
}
ExecuteSql is using ADO.net connections different from what EF recommends but I need to do this manual insert in order for this section to work.
static void ExecuteSql(ObjectContext c, string sql)
{
var entityConnection = (System.Data.EntityClient.EntityConnection)c.Connection;
DbConnection conn = entityConnection.StoreConnection;
ConnectionState initialState = conn.State;
try
{
if (initialState != ConnectionState.Open)
conn.Open(); // open connection if not already open
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
}
finally
{
if (initialState != ConnectionState.Open)
conn.Close(); // only close connection if not initially open
}
}
The ObjectContext (MSDN Link) requires you to provide a connection string to execute against. The ObjectContext is not your EF container but a context to query against a database and transform to objects. Because it is a generic query mechanism it does not know which connection string to use. In addition, your query is a simple insert query making the ObjectContext the wrong tool for the job. As the ObjectContext provides mapping mechanisms that you will not require I would suggest using your EF container to execute the query. This can be done by calling (sample code)
dbContainer.Database.ExecuteSqlCommand(query)
This command will grab your existing connection string from your configuration file and execute the query provided. Finally there is another option if you really want a ObjectContext without having to enter the connection string. You can do this by providing a wrapper, or static method to create an ObjectContext without the connection string. Such as.
Method 1: Wrapper (inheritance)
class MyObjectContext : ObjectContext
{
public MyObjectContext()
: base(MyObjectContext.connectionString)
{ }
/// <summary>
/// the connection string id in the config
/// </summary>
const string connectionStringID = "dbCon";
/// <summary>
/// gets the connection string
/// </summary>
static string connectionString
{
get
{
return ConfigurationManager.ConnectionStrings[connectionStringID].ConnectionString
}
}
}
Method 2. Static Property (or method)
static ObjectContext New
{
get
{
return new ObjectContext(ConfigurationManager.ConnectionStrings["dbCon"].ConnectionString);
}
}
Now personally I prefer method 1 (if i had to do this) as it also gives me the ability to extend this class to define my queries in one class such as.
class MyObjectContext : ObjectContext
{
//.....
public void Insert_UserInRole(string roleID, string id)
{
///TODO DO: insert role
}
//.....
}
And can be called such as.
using (var context = new MyObjectContext())
{
context.Insert_UserInRole("abc", "123");
}
[Just a thought]
Important In addition your query is begging for SQL Injection. Use "parameters" in your queries. Using parameters will prevent SQL inject atacks. Here is a SO topic regarding parameters. How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?
I hope this helps.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
in a “using” block is a SqlConnection closed on return or exception?
Would this using close this _connection?
using(SqlConnection _connection = Class1.GetSqlConnection())
{ //code inside the connection
}
//connection should be closed/ended?
I'm just wondering because GetSqlConnection() is a static function of Class1 and the whole connection might not be closed because it is calling outside class' static function instead of straight?
using(SqlConnection _connection = new SqlConnection(_connectionString)
{ //code inside the connection
}
The using statement does not care how the variable gets its value, - be it from a static function, a member function, a new operator, or any other way. As soon as the closing brace of the using is reached, the Dispose() method on the variable will be called, closing the connection if it's an IDbConnection instance, or doing whatever else the IDisposable is to do upon disposing.
Yes it does.
Here is an alternative way to implement the GetSqlFunction method so that you have a more explicit behaviour:
public class Class1
{
private static SqlConnection GetSqlConnection() { /* unchanged */ }
public static void UseSqlConnection(Action<SqlConnection> action)
{
using (var connection = Class1.GetSqlConnection())
{
action(connection);
}
}
}
Then you call it like so:
Class1.UseSqlConnection(c =>
{
/* use connection here */
});
You could then extend this method to use an existing connection or create a new one depending on the semantics you prefer.
Yes, by design.
A using block is used to handle disposing of, well, disposable objects when the block ends. To Dispose() an object means to release all of the resources for that object. For objects such as SqlConnection, this will close their connection.
Today I noticed a snippet of code that looks like the one below:
public class Test
{
SqlConnection connection1 =
new SqlConnection(ConfigurationManager.ConnectionStrings["c1"].ToString());
SqlConnection connection2 =
new SqlConnection(ConfigurationManager.ConnectionStrings["c2"].ToString());
public void Method1()
{
using (connection1)
{
connection1.Open();
using (SqlCommand newSqlCommand = new SqlCommand("text",connection2))
{
// do something
}
}
}
public void Method2()
{
using (connection1)
{
// do something
}
}
}
I am just wondering why would anyone want to open the connection when creating the class and not when calling the corresponding methods inside the class?
EDIT: I should have probably posted the whole code instead. So I do see where they are opening connection1, but then they are instantiating a sqlcommand with a different sql connection (connection2) which has not been opened anywhere. What am I missing here?
Thanks,
This line only initializes a connection object, which can later be used to open a connection to a database server.
SqlConnection connection1 =
new SqlConnection(ConfigurationManager.ConnectionStrings["c1"].ToString());
What I know is that using disposes of an object (and in the case of Connection objects they are automatically closed) after its scope so I wouldn't recommend such usage because it might be problematic with other object types (other than Connection) that can't be used after having their dispose called.
connection1 = new SqlConnection(...) does not really open the connection. It just creates the connection object.
You have to call connection1.Open(); to actually open it. You can do this inside using statement block.
Refer to this MSDN page for more details.
It either
written this way to enforce only single call to a method be performed on the class
unintentionally confusing by throwing ObjectDisposed exception if you call 2 methods
contains connection re-initialization code in blocks you've ommited.
The code is dangerous.
If you call Method1 then Method2 (or visa versa) you will get an error (connection string not initialized).
The error occurs because the using statement will close the connection AND Disposes the object. I double checked what happens when dispose is called...the connection string is cleared (and possibly some other things I didn't notice).
You don't want to re-use a disposed object.
The cost of instantiating a new connection object is insignificant so I would just create the object where needed, maybe with a little factory method to reduce code duplication, so change to something like:-
private static SqlConnection GetSqlConnection()
{
return new SqlConnection(ConfigurationManager.ConnectionStrings["c1"].ToString());
}
private void Method1()
{
using (var conn = GetSqlConnection())
{
conn.Open();
// do stuff...
}
}
private void Method2()
{
using (var conn = GetSqlConnection())
{
conn.Open();
// do other stuff...
}
}
Of course there are many different ways of approaching this problem, this is just one and indeed quite a simplistic one...but it is a good starting point and is safe :-)
I am building an application with c# and I decided to use the Enterprise Library for the DAL (SQL Server).
I don't remember where, but I had read an article about EntLib which said that the connections are closed automatically.
Is it true?
If not, what is the best approach of managing the connections in the middle layer?
Open and close in each method?
The above is a sample method of how I am using the EntLib
public DataSet ReturnSomething
{
var sqlStr = "select something";
DbCommand cmd = db.GetSqlStringCommand(sqlStr);
db.AddInParameter(cmd, "#param1", SqlDbType.BigInt, hotelID);
db.AddInParameter(cmd, "#param2", SqlDbType.NVarChar, date);
return db.ExecuteDataSet(cmd);
}
Thanks in advance.
the ExecuteDataSet method returns a DataSet object that contains all the data. This gives you your own local copy. The call to ExecuteDataSet opens a connection, populates a DataSet, and closes the connection before returning the result
for more info:
http://msdn.microsoft.com/en-us/library/ff648933.aspx
I think you should have something like a static class used as a Façade which would provide the correct connection for your library subsystems.
public static class SystemFacade {
// Used as a subsystem to which the connections are provided.
private static readonly SystemFactory _systemFactory = new SystemFactory();
public static IList<Customer> GetCustomers() {
using (var connection = OpenConnection(nameOfEntLibNamedConnection))
return _systemFactory.GetCustomers(connection);
}
public static DbConnection OpenConnection(string connectionName) {
var connection =
// Read EntLib config and create a new connection here, and assure
// it is opened before you return it.
if (connection.State == ConnectionState.Closed)
connection.Open();
return connection;
}
}
internal class SystemFactory {
internal IList<Customer> GetCustomers(DbConnection connection) {
// Place code to get customers here.
}
}
And using this code:
public class MyPageClass {
private void DisplayCustomers() {
GridView.DataSource = SystemFacade.GetCustomers();
}
}
In this code sample, you have a static class that provides the functionalities and features of a class library. The Façade class is used to provide the user with all possible action, but you don't want to get a headache with what connection to use, etc. All you want is the list of customers out of the underlying datastore. Then, a call to GetCustomers will do it.
The Façade is an "intelligent" class that knows where to get the information from, so creates the connection accordingly and order the customers from the subsystem factory. The factory does what it is asked for, take the available connection and retrieve the customers without asking any further questions.
Does this help?
Yes, EntLib closes connections for you (actually it releases them back into the connection pool). That is the main reason why we originally started to use EntLib.
However, for all new development we have now gone on to use Entity Framework, we find that much more productive.