Will Db conneection get closed in following situaltion? - c#

I have question on connection I create in C# code
To Read data I have written Factory Class for all the read which is as follows
Public static OracleDataReader(CommandType ct,string command,params OracleParameter[] cp)
{
OracleConnection cn = new OracleConnection(getconnection());
try
{
return ExecuteReader(cn,ct,command,cp);
}
catch
{
cn.close();
}
}
Now I use it as follows
qry = "select * from emp";
using(IDataReader dr = OracleFacoty.ExecuteReader(CommandType.Text,qry,null)
{
while(dr.read())
{
//Do operation
}
}
Now my question is, will the connection opened in factory method will be closed automatically or I Need pass the connection from calling method and close the connection once i am done with data read.

The using statement will dispose the dB connection properly when it's instantiated within it checkout this from msdn regarding this approach of like you did
You can instantiate the resource object and then pass the variable to the using statement, but this is not a best practice. In this case, the object remains in scope after control leaves the using block even though it will probably no longer have access to its unmanaged resources. In other words, it will no longer be fully initialized. If you try to use the object outside the using block, you risk causing an exception to be thrown. For this reason, it is generally better to instantiate the object in the using statement and limit its scope to the using block.
I would suggest probably use using and instantiate connection and pass that instance to your factory methods to perform any operations, by end the using will then properly dispose the database connection.
https://msdn.microsoft.com/en-us/library/yh598w02.aspx
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection(v=vs.110).aspx

By looking at your code, I can say
You have a static method in class which Creates new Connection each time you call it and returns some DataTable object(?)
Whenever an error occurs within ExecuteReader(), exception is suppressed and connection closes without questions.
But in Second snippet, you're not using OracleDataReader you're directly calling ExecuteReader() which, as I believe, will not handle any exceptions.
Also, in first snippet, connection closes only when an error occurs. If no error, connection will not close and will cause memory leaks and after some attempts it max outs connection limits.
If you need new connection for every call, then put the Cn.close() in finally{} block.

Related

What is the proper way to close a connection when using ExecuteScalar and EnterpriseLibrary.Data.Database

I haven't found the proper way to close the connection or Dispose when I use Microsoft.Practices.EnterpriseLibrary.Data.Database and the ExecuteScalar method.
I can't use a using block cause object doesn't implement IDisposable. And I haven't figured out how to Dispose if I use a Finally block instead. Do I need to do this, or my first using block will Dispose/Close the connection on the ExecuteScalar ?
This is my code:
DatabaseProviderFactory factory = new DatabaseProviderFactory();
DatabaseFactory.SetDatabaseProviderFactory(factory, false);
Database db = ... ;
// Initialize command
using (DbCommand dbCommand = db.GetStoredProcCommand("XXXXXX"))
{
object r;
// Execute command
using (r = (object)db.ExecuteScalar(dbCommand)) //Getting error here
{
//Other code here
}
}
The second using statement is not required.
Here the object that should be disposed is dbCommand. Not the objects returned from it's methods.
The first using statement takes care of it.
If you do not want to use using at all, (on the dbCommand) then you can dispose with try/finally in finally block.
Below link explains how to do that.
https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/using-objects

Handle Exception that happens within a using statement (IDisposable)

I'm using the DataWriter and DataReader interfaces.
These classes have the IDisposable interface implemented, therefore I wrap them around the using keyword:
using(var datareader = new DataReader(SerialPortInputStream))
{
CancellationTokenSource cancellation = new CancellationTokenSource();
//Timeout
cancellation.CancelAfter(1000);
//...
datareader.LoadAsync(120).AsTask(cancellation.Token);
//Some fancy methods
...
//Last step: Detach the InputStream to use it again
datareader.DetachStream();
}
This thread here is saying that if an Exception (here a "TaskCancelledException" happens inside a using statement, the object gets disposed. Now, the problem is with the UWP-DataReader and DataWriter: They will close the underlying stream if the object gets disposed. To prevent that I've to call datareader.DetachStream() and then dispose.
We cannot use the DataReader/DataWriter with a using statement when we need the underlying InputStream/Outputstream later again.
Is this conclusion correct or are there other ways to handle this situation?
The whole meaning of using is to make sure that the object gets disposed at the end of the block no matter what happens without having to write all the code for this by yourself. This is done by disposing the object inside a finally block.
What you are trying to do is to call datareader.DetachStream() before the object gets disposed - again no matter what happens.
So my conclusion would be that the using statement isn't very helpful here and you should do this by yourself, maybe like this:
DataReader datareader = null;
try
{
datareader = new DataReader(SerialPortInputStream);
CancellationTokenSource cancellation = new CancellationTokenSource();
//Timeout
cancellation.CancelAfter(1000);
//...
datareader.LoadAsync(120).AsTask(cancellation.Token);
//Some fancy methods
...
}
finally
{
//Last step: Detach the InputStream to use it again
datareader?.DetachStream();
datareader?.Dispose();
}
So this is essentially what the using statement does to your code, except that you can insert the datareader?.DetachStream() call.
Note that the datareader would eventually get disposed anyway even without the using statement. When the scope of this variable is left, the garbage collection may anytime decide to remove this instance from memory which would lead to a call to its Dispose method. So a call to DetachStream() is needed before leaving the scope.

SQL Connection constructor outside the using statement

I have the following code:
SqlConnection Connect = new SqlConnection(IST_DBConnect.SQLConnectionString);
SqlCommand command = new SqlCommand(sqlCommandString, Connect);
RequestRow Result = new RequestRow();
Connect.Open();
using (Connect)
...
This is not my code, I would write the creation of the SQL Connection in a using statement, this is a code of my friend, I am no exactly sure if this is going to dispose properly the SQL connection object if something goes wrong in the constructor or in the Open method. So my question is if the connection object is created and the open method throws an exception => the connection is never opened, will this be disposed properly?
Thanks.
From documentation;
As a rule, when you use an IDisposable object, you should declare and
instantiate it in a using statement.
and
You can instantiate the resource object and then pass the variable to
the using statement, but this is not a best practice. In this case,
the object remains in scope after control leaves the using block even
though it will probably no longer have access to its unmanaged
resources. In other words, it will no longer be fully initialized. If
you try to use the object outside the using block, you risk causing an
exception to be thrown. For this reason, it is generally better to
instantiate the object in the using statement and limit its scope to
the using block.
Based on your example, if somethings goes wrong in constructor, of Open method, there is nothing using can do since you use it as a resource after you initialize it.
Sure this is the best way;
using(var Connect = new SqlConnection(IST_DBConnect.SQLConnectionString))
using(var command = Connect.CreateCommand())
{
//
} // <-- Both Connect and command will disposed here no matter exception is thrown or not

SqlConnection.Close() inside using statement

I'm using this code:
public void InsertMember(Member member)
{
string INSERT = "INSERT INTO Members (Name, Surname, EntryDate) VALUES (#Name, #Surname, #EntryDate)";
using (sqlConnection = new SqlConnection(sqlConnectionString_WORK))
{
sqlConnection.Open();
using (SqlCommand sqlCommand = new SqlCommand(INSERT, sqlConnection))
{
sqlCommand.Parameters.Add("#Name", SqlDbType.VarChar).Value = member.Name;
sqlCommand.Parameters.Add("#Surname", SqlDbType.VarChar).Value = member.Surname;
sqlCommand.Parameters.Add("#EntryDate", SqlDbType.Date).Value = member.EntryDate;
sqlCommand.ExecuteNonQuery();
}
}
}
Is it wrong if I don't add sqlConnection.Close(); before disposing it? I mean. It's not showing any errors, no problems at all. Is it better to Close it first? If yes, why?
No need to Close or Dispose the using block will take care of that for you.
As stated from MSDN:
The following example creates a SqlConnection, opens it, displays some
of its properties. The connection is automatically closed at the end
of the using block.
private static void OpenSqlConnection(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
}
}
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. MSDN
So ultimately your code line
using (sqlConnection = new SqlConnection(sqlConnectionString_WORK))
will be converted into a normal try finally block by compiler calling IDisposable object in the finally
According to MSDN documentation for the Close method:
you must explicitly close the connection by calling Close or Dispose. Close and Dispose are functionally equivalent.
Therefore, calling Dispose (implicitly so, even, using using) will cover your bases, as it were.
It's worth noting, too, I think,though not specific to your case, that Close will always effectively be called when the thing is wrapped in a using statement - which might not be the case should it be omitted and an exception occur without the proper try/catch/finally handling.
Is it wrong if I don't add sqlConnection.Close(); before disposing it
No, it is not as long as you are using your connection within Using. When you will leave the using scope, Dispose will be called for sql connection. which will close the existing connection and free-up all the resources as well.
The using statement is a try finally block and in your case the final block would have a connection.Dispose() call. So you don't really need a independent connection.Close() statement there.
The advantage is that this ensures the disposal even in case of an exception since the finally block will always run.
try
{
sqlConnection.Open();
// ....
}
finally
{
if(sqlConnection != null)
sqlConnection.Dispose();
}
You are using a Using which will Dispose() the object for you.
If you take the connection outside of the Using statement, then yes - you would need to close the connection when finished.
No, it is not wrong. The sqlConnection will close the connection after it will pass using block and call Dispose method. SqlConnection.Dispose() equal to SqlConnection.Close() method.
From MSDN: If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose. Close and Dispose are functionally equivalent.

Using the using statement in C# [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
What is the C# Using block and why should I use it?
I have seen the using statement used in the middle of a codeblock what is the reason for this?
The using syntax can(should) be used as a way of defining a scope for anything that implements IDisposable. The using statement ensures that Dispose is called if an exception occurs.
//the compiler will create a local variable
//which will go out of scope outside this context
using (FileStream fs = new FileStream(file, FileMode.Open))
{
//do stuff
}
Alternatively you could just use:
FileStream fs;
try{
fs = new FileStream();
//do Stuff
}
finally{
if(fs!=null)
fs.Dispose();
}
Extra reading from MSDN
C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.
The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.
It is often used when opening a connection to a stream or a database.
It behaves like a try { ... } finally { ... } block. After the using block, the IDisposable object that was instantiated in the parenthesis will be closed properly.
using (Stream stream = new Stream(...))
{
}
With this example, the stream is closed properly after the block.
using is try finally syntaxical suger for anything that has an IDisposable.. like a sqlconnection. Its use it make sure something is disposed after its out of the using(){} scope.
using(SqlConnection conn = new SqlConnection(connString))
{
//use connection
}
//shorter than
SqlConnection conn = new SqlConnection(connString)
try
{
//use connection
}
finally
{
conn.Dispose();
}
The using statement ensures an object is properly disposed once it is nolonger required.
It basically saves you writing obj.Dispose(); and gives a visual guide as to the scope and usage of an variable.
See the MSDN page for more info
This form of using has to do with freeing resources. It can only be used in combination with class that implement the IDisposable interface.
example:
using(SqlConnection conn = new SqlConnection(someConnectionString))
{
//Do some database stuff here
}
at the end of the using block conn.Dispose is called, even if an exception was thrown inside the block. In the case of a SwqlConnection object means that the connection is always closed.
A drawback of this construction is that there is now way of knowing what happend.
Hope this helps answer your question?
Whenever your code creates an object that implements IDisposable, your code should do the creation inside a using block, as seen above.
There is one exception to this rule. An error in the design of WCF proxy classes prevents using statements from being useful for proxy classes. Briefly, the Dispose method on a proxy class may throw an exception. The WCF team saw no reason not to permit this.
Unfortunately, not seeing a reason doesn't mean that there is no reason:
try
{
using (var svc = new ServiceReference.ServiceName())
{
throw new Exception("Testing");
}
}
catch (Exception ex)
{
// What exception is caught here?
}
If the implicit Dispose call throws an exception, then the catch block will catch that exception instead of the one thrown within the using block.

Categories

Resources