Using when working with SQLCommand/Connection - c#

I`ve used a function to open sql connection and generate a command.So I don`t use using for them.
But what happens if I get an exception ?while catch the exception nedd I explicitly dispose them?

using translates into try-finally block. If you don't want to use using statement then you can mimic the same using try-finally, in your case with catch just have finally block and dispose the connection there. Something like:
{
SqlConnection conn = new SqlConnection("your connection string");
try
{
//your code
}
catch (SqlException se)
{
//handle particular exception first
}
catch (Exception ex)
{
//handle all other exceptions
}
finally
{
if (conn != null)
conn.Dispose();
}
}
That will ensure the disposal of connection in case of an exception and normal flow (when no exception occurs)

Related

How to catch Ignite thin .net client exception

I am using Apache Ignite 2.7.5.
I don't know whether is there any way is there or not but trying to handle .net thin client exception,but i am not approaching to correct way,how to catch ignite java one throwable exception in c# .net catch block.
code:
public async void loadData(string configPath,List<JObject> dataList)
{
using (var ldr = _ignite.GetDataStreamer<string, Employee>(cacheName))
{
try
{
await ldr.AddData(base64EncodedKey, emp);//from this line i am getting exception on console but not able to catch
}
catch (Exception ex)//how to catch here java one throw exception
{
}
}
}
Any one suggest me correct approach to get exception in catch block.

Send exception to Caller method in c#

Hello guys i'm working on Database assignment in this i have one windows form and one class that i use to connect database and to execute queries and non-queries.
Question: I m using Post-Message label which inform only when "Product added successfully".but when i send wrong-data which can occur exception in executeNonQuery() in database class and after catching this exception and showing Error in message box.Control goes back to caller and it prints lblPostMsg in both cases which is "Product has been added successfully".
I want that when exception occur in database class i can stop executing rest of the code or if there is way that exception in calling method can be caught by caller method.
below is Code of windows Form button
private void btnInsert_Click(object sender, EventArgs e)
{
con = new DbConnection();
con.SqlQuery("INSERT INTO products VALUES(#products_ID,#products_Name)");
con.cmd.Parameters.AddWithValue("#products_ID", txtProID.Text);
con.cmd.Parameters.AddWithValue("#products_Name", txtProName.Text);
try
{
con.ExecuteNonQueryF();
this.categoriesTableAdapter1.Fill(this.purchasemasterDS.categories);
SystemSounds.Beep.Play();
lblPostMsg.Show();
lblPostMsg.Text = "Product has been added successfully";
}
catch (Exception ex)
{
throw;
}
finally
{
con.CloseCon();
}
}
This code is from dbclass
public void ExecuteNonQueryF()
{
try
{
_con.Open();
cmd.ExecuteNonQuery();
}
catch (System.Exception ex)
{
MessageBox.Show("Exception " + ex);
}
you are catching, handling, and suppressing the Exception in ExecuteNonQueryF:
catch (System.Exception ex)
{
MessageBox.Show("Exception " + ex);
}
Though this handles the Exception by showing the message, it causes the code to continue executing; the Exception won't be raised to the caller.
If you add throw after your MessageBox.Show is executed, the Exception will be raised to the caller and execution stops.
catch (System.Exception ex)
{
MessageBox.Show("Exception " + ex);
throw;
}
Another option is to completely remove that try-catch in ExecuteNonQueryF - letting the caller (your button onclick method) handle the Exception.
you need to throw an explicit exception in ExecuteNonQuery's catch block like
throw new Exception(ex)
and then in calle's catch block you need to write "return" to return from function. This will stop furter execution of function.
If you want the Exception will be raised to the caller and execution stops, then you must use throw at the last line of your catch block.
catch (System.Exception ex)
{
/*
write your desire code. then throw
*/
throw;
}

How to properly close ODP.net connection : dispose() or close()?

this is my powershell code :
[void][System.Reflection.Assembly]::LoadFile("C:\DLL\Oracle.ManagedDataAccess.dll")
$OracleConnexion = New-Object Oracle.ManagedDataAccess.Client.OracleConnection('User Id=test;Password="test";Data Source=10.2.2.1/TEST')
$TimeOut = 60
$OracleConnexion.Open()
$Query=$OracleConnexion.CreateCommand()
$Query.CommandText="Select * FROM TEST"
$Query.CommandTimeout = $Timeout
$ExecuteRequete=$Requete.ExecuteReader()
while ($ExecuteRequete.Read()) {
$SiebelLastRecord += $ExecuteRequete.GetDateTime(0).ToString()
}
$OracleConnexion.Close()
So I'm opening ODP.NET connection with $OracleConnexion.open() then closing it with $OracleConnexion.close() is it sufficient to close properly my connection to Oracle Database? Or should I use $OracleConnexion.Dispose() ?
I execute my powershell every 5min via Task scheduler... So maybe Should I use Dispose() to avoid memory saturation?
It looks like everybody else, I noticed late that you're in powershell. In that case, it doesn't really matter. Everything is going to get cleaned up when the shell ends regardless. I suppose you could add a [catch] and maybe close/dispose the connection there if it's still open, but I think that would only be necessary if you planned on letting your script continue.
I'll leave my longwinded c# answer below. Even though it doesn't really apply to your script, it explains the difference (or lack thereof).
The short answer (for c#):
using (var conn = new OracleConnection(connectionString))
{
}
"using" ensures that .Dispose is called at the end of the block even if an exception is thrown. That way you never risk a connection being orphaned until garbage collection finally gets around to cleaning it up and that might be well after you run out of database connections.
The long answer:
Using a reflector, you will see that Dispose calls Close:
protected override void Dispose(bool disposing)
{
if (ProviderConfig.m_bTraceLevelPublic)
Trace.Write(OracleTraceLevel.Public, OracleTraceTag.Entry);
this.m_disposed = true;
this.m_dataSource = string.Empty;
this.m_serverVersion = string.Empty;
try
{
bool flag = this.m_connectionState == ConnectionState.Closed && this.m_oracleConnectionImpl == null;
try
{
if (!disposing)
{
if (!flag)
{
if (OraclePool.m_bPerfNumberOfReclaimedConnections)
OraclePool.PerformanceCounterIncrement(OraclePerfParams.CounterIndex.NumberOfReclaimedConnections, this.m_oracleConnectionImpl, this.m_oracleConnectionImpl.m_cp);
}
}
}
catch (Exception ex)
{
if (ProviderConfig.m_bTraceLevelPublic)
Trace.Write(OracleTraceLevel.Public, OracleTraceTag.Error, ex.ToString());
}
if (!flag)
{
try
{
this.Close();
}
catch (Exception ex)
{
if (ProviderConfig.m_bTraceLevelPublic)
Trace.Write(OracleTraceLevel.Public, OracleTraceTag.Error, ex.ToString());
}
}
try
{
base.Dispose(disposing);
}
catch (Exception ex)
{
if (ProviderConfig.m_bTraceLevelPublic)
Trace.Write(OracleTraceLevel.Public, OracleTraceTag.Error, ex.ToString());
}
try
{
GC.SuppressFinalize((object) this);
}
catch (Exception ex)
{
if (!ProviderConfig.m_bTraceLevelPublic)
return;
Trace.Write(OracleTraceLevel.Public, OracleTraceTag.Error, ex.ToString());
}
}
catch (Exception ex)
{
if (!ProviderConfig.m_bTraceLevelPublic)
return;
Trace.Write(OracleTraceLevel.Public, OracleTraceTag.Error, ex.ToString());
}
finally
{
if (ProviderConfig.m_bTraceLevelPublic)
Trace.Write(OracleTraceLevel.Public, OracleTraceTag.Exit);
}
}
Is there any real difference? No - the unmanaged resource IS the connection which is taken care of with .Close. You'd see no functional difference (other than delayed tracing) if you checked the connection status in a finally block and called .Close there if it was still open.
OracleConnection conn = null;
try
{
conn = new OracleConnection(connectionString);
}
finally
{
if(conn.State != ConnectionState.Closed)
conn.Close();
}
That said the recommended pattern for idisposible objects is to use a "using" block. Yes I suppose it is true that you have the option to reopen the connection with close, but I don't see that being a useful thing to do.
If you didn't use a using or a finally and an exception is thrown and close/dispose is never called, then freeing the connection to the db would be nondeterministic - Dispose(false) would happen whenever the garbage collector got around to it - and that might be long after you run out of connections to your db.
OracleConnection conn = null;
conn = new OracleConnection(connectionString);
conn.Open();
//exception occurs - Close is never called - resource leak!!
conn.Close();
Close closes the connection and allows you to reopen it again.
Dispose closes the connection if it hasn't been closed and also disposes of it so you can't reopen it again.
Use dispose - dispose frees up memory of a resource,
if that resource is open, then a well behaved .dispose method will close the resource.
Dispose() vs. Close() with ConnectionPooling:
https://community.oracle.com/thread/165664?start=0&tstart=0
More standard implementation for resource which implement IDisposable is by wrapping it by using:
using (OracleConnection connection = new OracleConnection(connectionString)){
using (OracleCommand command = new OracleCommand(sql, connection))
using (OracleDataReader reader = cmd.ExecuteReader())
{
}
connection.Close(); //optional
}
It is equivalent to implementing .Dispose after the execution block. Internally, Dispose will also handle the closing. Nevertheless, you could also call the .Close() after the command block.
A sample in the oracle documentation which uses Oracle.DataAccess encourages the use of Dispose too.
I would wrap your connection by a using statement. When you're done with your connection then close it before adding the bracket. To be 100% safe I would do something like this:
using(OracleConnexion Con = new OracleConnection (...))
{
Con.Open()
...
Con.Close()
}
Edit:
I added the Con.Close(), because in the past the dispose was not implemented correctly in the ODP.NET. The connection was kept open. We had to force the connection to close manually and that's why in the example, I specify the Close.

Exception handling (I want to check if the connection.Open() runs)

I'd like my code to give a warning or something whenever the database is not available.
(That's why I commented the connection string), but my website just crashes.
I created this class cause there were many parts of the program using this connection string (login page, register page, user panel page, etc), so if I want to change something in the future, this is the only string I have to change.
namespace Fatture.Data.User
{
public class DbConnection
{
public MySqlConnection ConnessioneDb()
{
MySqlConnection conn = new MySqlConnection(/*ConfigurationManager.ConnectionStrings["ConnectionStringloginDb"].ConnectionString*/);
try
{
conn.Open();
}
catch (Exception ex)
{
throw new Exception("I can't connect to the database", ex);
}
return conn;
}
}
}
Use exception handling...
var connector = new DbConnection();
try
{
var connection = connector.ConnessioneDb();
}
catch (Exception ex)
{
// show message to user: database not available
}
Though you'll have to put this in place everywhere you access the database. Instead you can also just set up error handling for your entire site.
Catch the exception...
try
{
var conn = new DbConnection().ConnessioneDb();
}
catch (Exception ex)
{
// Notify user here
}

Try inside catch to ensure finally executes

I have to process items off a queue.
Deleting items off the queue is a manual call to Queue.DeleteMessage. This needs to occurs regardless of whether or not the processing succeeds.
var queueMessage = Queue.GetMessage();
try
{
pipeline.Process(queueMessage);
}
catch (Exception ex)
{
try
{
Logger.LogException(ex);
}
catch { }
}
finally
{
Queue.DeleteMessage(queueMessage);
}
Problem:
On failure, I log the error to some data store. If this logging fails (perhaps the data store is not available), I still need the message to be deleted from the queue.
I have wrapped the LogException call in another try catch. Is this the correct way or performing thing?
Following code is enough. finally blocks execute even when exception is thrown in catch block.
var queueMessage = Queue.GetMessage();
try
{
pipeline.Process(queueMessage);
}
catch (Exception ex)
{
Logger.LogException(ex);
}
finally
{
Queue.DeleteMessage(queueMessage);//Will be executed for sure*
}
The finally block always executes, even if it throws an unhandled error (unless it end the app). So yes.

Categories