Using closes sql connection brought over by a function [duplicate] - c#

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.

Related

Will supplying a SQLCommand with a new SQLConnection call Dispose on the new SQL Connection? [duplicate]

This question already has answers here:
Dispose object that has been instantiated as method parameter c#
(2 answers)
Closed 3 years ago.
PREAMBLE
I understand that normally most SQL calls run thusly
using(var cnn = new DbConnection("YOURCONNECTIONSTRINGHERE")
{
cnn.Open(); //Open the connection.
using(var cmd = new DbCommand("YourSQL", cnn)
{
cmd.ExecuteScalar; //Or whatever type of execution you want.
}
}
This will properly dispose of both the connection and the command.
My Question: Will this code properly dispose of both objects?
using(var cmd = new SqlCommand("YourSQL", new Connection("YOURCONNECTIONSTRINGHERE"))
{
cmd.ExecuteScalar; //Or whatever type of execution you want.
}
In reality I'm using a method that provides and opens the connection.
public SqlConnection Connection()
{
var product = new SQLConnection("ConnectionString");
product.Open();
return product;
}
So at the end of the day the call looks like this:
using(var cmd = new SqlCommand("YourSQL", Connection())
{
cmd.ExecuteScalar; //Or whatever type of execution you want.
}
I know the SqlCommand object will be disposed of but will the SQLConnection, created within the using parameter declaration, be disposed of? I've tried running some simple unit tests but it seems inconclusive.
Will this code properly dispose of both objects?
using(var cmd = new SqlCommand("YourSQL", new Connection("YOURCONNECTIONSTRINGHERE"))
{
cmd.ExecuteScalar; //Or whatever type of execution you want.
}
The above code does not call Dispose() on the connection. The using block ensures that cmd.Dispose() is called immediately after the execution of the block, but the connection remains open. Since the connection has no object referencing it, it will be eventually closed/disposed by the Garbage Collector.
If you want to dispose the Command and Connection immediately, then try:
using (var con = Connection()) // <-- GetConnection() would be a better name
using (var cmd = new SqlCommand(con)
{
cmd.ExecuteScalar;
}

Object Disposes Before Using Datas [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I'm struggling with some System.Data.SqlClient.SqlDataReader problems.
Actually, I made a DatabaseHandler for execute queries more convenient, with IDisposable interface for using statements.
When I use the handler for reading single article, query successfully executed, however, the handler disposed before I use data.
Then, the result is NullReferenceException. Here's the article reading code, and Dispose().
// Article Reading Code
using (var ArticleHandler = new DatabaseHandler())
{
var ArticleReader = ArticleHandler.ExecuteCommand("ARTICLE_INQUIRY",
DatabaseHandler.QueryType.ExecuteReader,
new DatabaseParameter[]
{
new DatabaseParameter("seq", Sequence)
}) as System.Data.SqlClient.SqlDataReader; //Query Successful
if (!ArticleReader.HasRows)
{
Response.Redirect("/articles/list.aspx");
}
else
{
ArticleReader.Read(); //Data Read Successful
CurrentArticle.title = (string)ArticleReader["title"]; //NullReferenceException ?
CurrentArticle.category = (string)ArticleReader["category"];
CurrentArticle.datetime = (string)ArticleReader["written_datetime"];
CurrentArticle.content = (string)ArticleReader["content"];
}
}
/* Database Handler Dispose() */
public void Dispose()
{
CurrentConnection = null;
}
P.S. I checked column names, and they are match with database information.
Check inside your database handler if you are closing the underlying sqlconnection before accessing the reader to access data in the next line. If the sqlconnection is getting closed, the reader will get closes automatically. Paste the handler Execute command code so we can have look at it

How to pass methods into an open SQL connection

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.

using statements

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 :-)

Can an object be declared above a using statement instead of in the brackets

Most of the examples of the using statement in C# declare the object inside the brackets like this:
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", connection))
{
// Code goes here
}
What happens if I use the using statement in the following way with the object declared outside the using statement:
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", connection);
using (cmd)
{
// Code goes here
}
Is it a bad idea to use the using statement in the way I have in the second example and why?
Declaring the variable inside the using statement's control expression limits the scope of the variable to inside the using statement. In your second example the variable cmd can continue to be used after the using statement (when it will have been disposed).
Generally it is recommended to only use a variable for one purpose, limiting its scope allows another command with the same name later in scope (maybe in another using expression). Perhaps more importantly it tells a reader of your code (and maintenance takes more effort than initial writing) that cmd is not used beyond the using statement: your code is a little bit more understandable.
Yes, that is valid - the object will still be disposed in the same manner, ie, at the end and if execution flow tries to leave the block (return / exception).
However if you try to use it again after the using, it will have been disposed, so you cannot know if that instance is safe to continue using as dispose doesn't have to reset the object state. Also if an exception occurs during construction, it will not have hit the using block.
I'd declare and initialize the variable inside the statement to define its scope. Chances are very good you won't need it outside the scope if you are using a using anyway.
MemoryStream ms = new MemoryStream(); // Initialisation not compiled into the using.
using (ms) { }
int i = ms.ReadByte(); // Will fail on closed stream.
Below is valid, but somewhat unnecessary in most cases:
MemoryStream ms = null;
using (ms = new MemoryStream())
{ }
// Do not continue to use ms unless re-initializing.
I wrote a little code along with some unit tests. I like it when I can validate statements about the question at hand. My findings:
Whether an object is created before or in the using statement doesn't matter. It must implement IDisposable and Dispose() will be called upon leaving the using statement block (closing brace).
If the constructor throws an exception when invoked in the using statement Dispose() will not be invoked. This is reasonable as the object has not been successfully constructed when an exception is thrown in the constructor. Therefore no instance exists at that point and calling instance members (non-static members) on the object doesn't make sense. This includes Dispose().
To reproduce my findings, please refer to the source code below.
So bottom line you can - as pointed out by others - instantiate an object ahead of the using statement and then use it inside the using statement. I also agree, however, moving the construction outside the using statement leads to code that is less readable.
One more item that you may want to be aware of is the fact that some classes can throw an exception in the Dispose() implementation. Although the guideline is not to do that, even Microsoft has cases of this, e.g. as discussed here.
So here is my source code include a (lengthy) test:
public class Bar : IDisposable {
public Bar() {
DisposeCalled = false;
}
public void Blah() {
if (DisposeCalled) {
// object was disposed you shouldn't use it anymore
throw new ObjectDisposedException("Object was already disposed.");
}
}
public void Dispose() {
// give back / free up resources that were used by the Bar object
DisposeCalled = true;
}
public bool DisposeCalled { get; private set; }
}
public class ConstructorThrows : IDisposable {
public ConstructorThrows(int argument) {
throw new ArgumentException("argument");
}
public void Dispose() {
Log.Info("Constructor.Dispose() called.");
}
}
[Test]
public void Foo() {
var bar = new Bar();
using (bar) {
bar.Blah(); // ok to call
}// Upon hitting this closing brace Dispose() will be invoked on bar.
try {
bar.Blah(); // Throws ObjectDisposedException
Assert.Fail();
}
catch(ObjectDisposedException) {
// This exception is expected here
}
using (bar = new Bar()) { // can reuse the variable, though
bar.Blah(); // Fine to call as this is a second instance.
}
// The following code demonstrates that Dispose() won't be called if
// the constructor throws an exception:
using (var throws = new ConstructorThrows(35)) {
}
}
The idea behind using is to define a scope, outside of which an object or objects will be disposed.
If you declare the object you are about to use inside using in advance, there's no point to use the using statement at all.
It has been answered and the answer is: Yes, it's possible.However, from a programmers viewpoint, don't do it! It will confuse any programmer who will be working on this code and who doesn't expect such a construction. Basically, if you give the code to someone else to work on, that other person could end up being very confused if they use the "cmd" variable after the using. This becomes even worse if there's even more lines of code between the creation of the object and the "using" part.

Categories