Shows connection is closed even if connection.open is present - Works when I remove Try Block - sql

This is the function to access the database; the connection string is perfect - There is another Function similar to this and it works fine.
Friend Shared Function AddMember(member As Object) As Task(Of Integer)
Dim connection = New SqlConnection(Configuration.ConfigurationManager.ConnectionStrings("Carrel").ConnectionString)
Dim query = New SqlCommand("INSERT INTO JSON (CATEGORY,DATA) VALUES ('MEM',#JSONString)", connection)
Try
Connection.Open()
query.Parameters.Add(New SqlParameter("#JSONString", JsonConvert.SerializeObject(member)))
Return query.ExecuteNonQueryAsync()
Catch ex As Exception
MsgBox(ex.ToString())
Throw
Finally
query.Connection.Close()
End Try
End Function

Try this:
Friend Shared Async Function AddMember(member As Object) As Task(Of Integer)
Dim cn AS New SqlConnection(Configuration.ConfigurationManager.ConnectionStrings("Carrel").ConnectionString)
Dim query As New SqlCommand("INSERT INTO JSON (CATEGORY,DATA) VALUES ('MEM',#JSONString)", cn)
Try
cn.Open()
query.Parameters.Add(New SqlParameter("#JSONString", JsonConvert.SerializeObject(member)))
Return Await query.ExecuteNonQueryAsync()
Catch ex As Exception
MsgBox(ex.ToString())
Throw
Finally
query.Connection.Close()
End Try
End Function
This should prevent the method from continuing past the ExecuteNonQueryAsync() line until the task returns, so the connection will stay open, but can still run without blocking.
It's also better practice to put the connection and command object in Using blocks, and to not worry about exceptions at this level. This is a data access method... separate that from your presentation code. Let the exception bubble up in the calling code, especially in an Async method:
Friend Shared Async Function AddMember(member As Object) As Task(Of Integer)
Using cn AS New SqlConnection(Configuration.ConfigurationManager.ConnectionStrings("Carrel").ConnectionString), _
cmd As New SqlCommand("INSERT INTO JSON (CATEGORY,DATA) VALUES ('MEM',#JSONString)", cn)
query.Parameters.Add(New SqlParameter("#JSONString", JsonConvert.SerializeObject(member)))
cn.Open()
Return Await query.ExecuteNonQueryAsync()
End Using
End Function
Just be careful, because the async code could be hiding exceptions from you now.

The problem is that, as Aman Bachas said, you're calling ExecuteNonQueryAsync which will start the operation in the background. But then your Finally block will execute and close the connection before the execute actually happens.
What you'll need to do is call the non-Async version but then do your own Async so you can close the connection after it's done.
Public Function AddMember(member As Object) As Threading.Tasks.Task(Of Integer)
Dim connection = New SqlConnection(Configuration.ConfigurationManager.ConnectionStrings("Carrel").ConnectionString)
Dim query = New SqlCommand("INSERT INTO JSON (CATEGORY,DATA) VALUES ('MEM',#JSONString)", connection)
Try
connection.Open()
query.Parameters.Add(New SqlParameter("#JSONString", JsonConvert.SerializeObject(member)))
Return Threading.Tasks.Task.Factory.StartNew(Of Integer)(Function()
Dim ret = query.ExecuteNonQuery()
connection.Close()
Return ret
End Function)
Catch ex As Exception
MsgBox(ex.ToString())
Throw
End Try
End Function
You'll probably want to add some error handling inside the task and clean this up a bit, but that should give you a starting point.

Please replace ExecuteNonQueryAsync() with the ExecuteNonQuery().

Related

In vb.net project, how to check if SQL connection is still available and end all processing?

I have a problem in a vb.net Windows Form project. My company is having network issues and is losing connection between the Windows Form application and the SQL server. When this happens, the application locks up and closes. Before any SQL commands are executed, is there a way to check if the SQL connection is even available?
I've tried using this:
If (cmd.Connection.State <> ConnectionState.Closed)
after the cmd is setup like this:
Dim cmd As SqlCommand
cmd = MSSQL_CONN.CreateCommand
but the state is often Open because the network connection fails after the SQL command was initialized.
I've tried to catch the error like this:
Private m_conn As SqlConnection
Try
m_conn = New SqlConnection(cn_str)
Call m_conn.Open()
Catch e As Exception
MessageBox.Show("Error")
If MSSQL_CONN.TransactionStarted Then
MSSQL_CONN.RollbackTransaction()
End If
End Try
but this has problems because it's trying to do a rollback for any other errors and the rollback throws an error because of the loss of connection state. This also starts a cascade into other timers and background processes that continue to run and try to connect to the SQL server.
I'm hoping there something like
If *SQL connection is even still available* Then
Call m_conn.Open()
Else
*Don't execute any other SQL on this form or any other background forms*
End If
Normally it's best to use a using statement for a connection where the connection is scoped to the method you are working with the database. Otherwise you could create the connection as needed e.g. check the connection state as on error.
Public Class DataOperations
Public Shared Async Function Connection() As Task(Of SqlConnection)
Dim cn As New SqlConnection With {.ConnectionString = "TODO"}
Try
Await cn.OpenAsync()
Return cn
Catch ex As Exception
Return New SqlConnection
End Try
End Function
End Class
Then there is locally scoped where the choice is OpenAsync or Open.
Public Shared Function GetCatagories() As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection With {.ConnectionString = "TODO"}
Using cmd As New SqlCommand With {.Connection = cn}
cmd.CommandText = "TODO"
Try
cn.Open()
dt.Load(cmd.ExecuteReader())
Catch ex As Exception
' decide on how to handle
End Try
End Using
End Using
Return dt
End Function
EDIT:
Public Shared Async Function IsServerConnected() As Task(Of Boolean)
Using cn As New SqlConnection With {.ConnectionString = ConnectionString}
Try
Await cn.OpenAsync()
Return True
Catch ex As Exception
Return False
End Try
End Using
End Function

Returning From a Function BEFORE disposing sqlconnection

I should begin by stating that I assume that the answer to this question is NO, but I wanted to ask to be sure.....If you open a sqlconnection inside of a function(with a USING block), and return from that function prior to reaching the end of the block, will that connection be disposed of properly?
For Example:
Public Function Myfunction() As Boolean
Dim ConnectionString As String = "connectionstring goes here"
Dim sql As String = "SELECT * FROM mytable"
Using connection As New SqlClient.SqlConnection(ConnectionString)
Using command As New SqlClient.SqlCommand(sql, connection)
connection.Open()
Using reader As SqlClient.SqlDataReader = command.ExecuteReader
While reader.Read
Return True
End While
End Using
End Using
End Using
Return False
End Function
Will the above connection be disposed of properly if the return true line is executed?
If you open a sqlconnection inside of a function(with a USING block), and return from that function prior to reaching the end of the block, will that connection be disposed of properly?
Yes. Absolutely. That's the beauty of a USING block. See
A Using block behaves like a Try...Finally construction in which the Try block uses the resources and the Finally block disposes of them. Because of this, the Using block guarantees disposal of the resources, no matter how you exit the block. This is true even in the case of an unhandled exception, except for a StackOverflowException
https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/using-statement

How to show error message on forms project when its already catched in library

Have some windows form with nice circural progress bar which i show user during long database function process. There is also task which calls function which inside i got query with transaction and there is catch implemented to rollback if it fails and return either true/false about state of process after finished. I didn't place there memssage box to show error as it's not adviced to store message boxes along in library projects so i would like to show this error on my task level function (in catch). However since i am catching error inside my function i am not able to show it (catch it) on the task's catch. How to accomplish that?
The only idea in my head is to instead of returning only result also return catched error message with use of Tuple like this: Tuple(Of Boolean, String). So i would be able to return two things: result and error message text. I am not so sure if this is right way to do such things. Looking for your advice.
This comes from windows forms project:
Dim pic As New CircuralWindowsForms(eCircularProgressType.Donut)
Dim tsk As Task(Of Boolean) = Task.Factory.StartNew(Of Boolean)(Function()
Dim resu = False
Try
resu = createArticle.ProcessArticle(data)
Catch sqlex As Exception
pic.Invoke(Sub() MessageBox.Show(pic, sqlex.Message))
Finally
'--Close form once done (on GUI thread)
pic.Invoke(New Action(Sub() pic.Close()))
End Try
Return resu
End Function)
'Show circural form
pic.ShowDialog()
Task.WaitAll(tsk)
if tsk.Result = true Then
...
This comes from library project:
Public Function ProcessArticle(data as Data) As Boolean
Dim result = false
Using connection As New SqlConnection(strcon)
Try
connection.Open()
Dim transaction As SqlTransaction
transaction = connection.BeginTransaction()
.....
transaction.Commit()
result=true
Catch ex As Exception
result = False
transaction.Rollback()
End Try
End Using
return result
End Function
Extended question a bit (discussion with sstan):
Public Sub DeleteAllRelated(varId As Integer)
Using con As New SqlConnection(strcon)
Dim commit As Boolean = True
con.Open()
Dim tran As SqlTransaction = con.BeginTransaction
Dim dt As New DataTable
dt = CType(New Variation_VariationAttributeDAL().GetAllByVariationId(varId), DataTable)
If dt IsNot Nothing Then
For Each row As DataRow In dt.Rows
If commit Then commit = commit And New Artikel_VariationDAL().DeleteByVariation_VariationAttribute(CInt(row(0)), tran)
Next
End If
If commit Then commit = commit And New Variation_VariationAttributeDAL().DeleteAllWhereVarId(varId, tran)
If commit Then commit = commit And Delete(varId, tran)
If commit Then commit = commit And New DALSubKategorie_Variation().Delete(varId, tran)
If commit Then
tran.Commit()
Else
tran.Rollback()
End If
End Using
End Sub
this is e.g for: If commit Then commit = commit And New DALSubKategorie_Variation().Delete(varId, tran)
Public Function Delete(varId As Integer, Optional transaction As SqlTransaction = Nothing) As Boolean
Dim result As Boolean = False
If transaction Is Nothing Then
Try
Using con As New SqlConnection(strcon)
Using cmd As New SqlCommand("DELETE FROM " & SharedData.Write.T(SharedData.Tables.SubKategorie_Variation) & " WHERE FK_Variation_ID=#FK_Variation_ID", con)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#FK_Variation_ID", varId)
con.Open()
Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
con.Close()
result = True
End Using
End Using
Catch ex as Exception
Throw
End Try
Else
Using cmd As New SqlCommand("DELETE FROM " & SharedData.Write.T(SharedData.Tables.SubKategorie_Variation) & " WHERE FK_Variation_ID=#FK_Variation_ID", transaction.Connection)
cmd.Transaction = transaction
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#FK_Variation_ID", varId)
Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
result = True
End Using
End If
Return result
End Function
You're right that it would be wrong for your library to display message boxes directly. But that doesn't mean it should swallow exceptions either. In, fact, quite the opposite: you really should let the exception bubble up to the caller, and let the caller decide what to do with it.
With that in mind, I would change the ProcessArticle function to the following:
Public Sub ProcessArticle(data as Data)
Using connection As New SqlConnection(strcon)
Try
connection.Open()
Dim transaction As SqlTransaction
transaction = connection.BeginTransaction()
' .....
transaction.Commit()
Catch ex As Exception
transaction.Rollback()
Throw 'Rethrow exception. The caller can decide what to do with it.
End Try
End Using
End Sub
Notice how the exception is still caught to enable the transaction rollback, but the exception is rethrown so that the caller can catch it. This in turn means that you no longer need to return a boolean to indicate success or failure.
EDIT
Not directly related to your question, but I would further move the code around a little bit so that I don't accidentally try to rollback a transaction before it has even begun (With you current code, ask yourself what would happen if an error occurred while trying to open the connection?):
Public Sub ProcessArticle(data as Data)
Using connection As New SqlConnection(strcon)
connection.Open()
Using transaction = connection.BeginTransaction()
Try
' do work here
transaction.Commit()
Catch ex As Exception
transaction.Rollback()
Throw 'Rethrow exception. The caller can decide what to do with it.
End Try
End Using
End Using
End Sub
EDIT 2
More on the Throw Statement:
A Throw statement with no expression can only be used in a Catch statement, in which case the statement rethrows the exception currently being handled by the Catch statement.
EDIT 3: Simplified version of your last edit
Public Sub DeleteAllRelated(varId As Integer)
Using con As New SqlConnection(strcon)
con.Open()
Using transaction = connection.BeginTransaction()
Try
Dim dt As New DataTable
dt = CType(New Variation_VariationAttributeDAL().GetAllByVariationId(varId), DataTable)
If dt IsNot Nothing Then
For Each row As DataRow In dt.Rows
New Artikel_VariationDAL().DeleteByVariation_VariationAttribute(CInt(row(0)), tran)
Next
End If
New Variation_VariationAttributeDAL().DeleteAllWhereVarId(varId, tran)
Delete(varId, tran)
New DALSubKategorie_Variation().Delete(varId, tran)
'If we made it this far without an exception, then commit.
tran.Commit()
Catch ex As Exception
tran.Rollback()
Throw 'Rethrow exception.
End Try
End Using
End Using
End Sub
Public Sub Delete(varId As Integer, Optional transaction As SqlTransaction = Nothing)
If transaction Is Nothing Then
Using con As New SqlConnection(strcon)
Using cmd As New SqlCommand("DELETE FROM " & SharedData.Write.T(SharedData.Tables.SubKategorie_Variation) & " WHERE FK_Variation_ID=#FK_Variation_ID", con)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#FK_Variation_ID", varId)
con.Open()
Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
Else
Using cmd As New SqlCommand("DELETE FROM " & SharedData.Write.T(SharedData.Tables.SubKategorie_Variation) & " WHERE FK_Variation_ID=#FK_Variation_ID", transaction.Connection)
cmd.Transaction = transaction
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#FK_Variation_ID", varId)
Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
End Using
End If
End Sub
EDIT 4: Example of exception chaining
Public Sub ProcessArticle(data as Data)
Try
' do work here
Catch ex As Exception
' If you want the original error to go up to the "upper levels"
' but with additional information, you need to throw a new
' instance of an exception with a new message that contains the additional information
' but you need to pass the original exception as a parameter to the constructor
' so that exceptions get chained together.
' If an "upper level" caller catches the chained exception,
' doing "ex.ToString" will provide all the information.
' Try it out, see how it works.
Throw New Exception("put your additional information here", ex)
End Try
End Sub

Function Return Issue?

In my VB.Net program I have found two (2) warnings shows the following messages:
Function doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used
help me where is the problem and to fix it. The following snapshot is where the warning error indicates:
The Firs Warning near 'End Function'
'Executes SQL commands to the system database
Public Function ExecSQL(ByVal sql As String)
Dim com As New MySqlCommand(sql)
Try
RefreshConnection()
com.Connection = con
com.ExecuteNonQuery()
Catch ex As Exception
Return ex
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")
End Try
End Function
The Second Waring near 'End Function'
'Get the value of an specific field in a given sql string
Public Function GetField(ByVal sql As String, ByVal field As String)
Try
RefreshConnection()
Dim com As New MySqlCommand(sql, con)
Dim dReader As MySqlDataReader = com.ExecuteReader
While dReader.Read
GetField = dReader(field).ToString
End While
dReader.Close()
Catch ex As Exception
Return ex
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")
End Try
End Function
This occurs because in the exception handler you actually return the exception object ex. You're not returning anything if no exception occurs. You could explicitly add Return Nothing just above Catch ex as Exception, but I guess from the message that VB is doing that automatically for you...
By the way: What's the point returning the exception to the caller? Put the message box into the calling method and wrap your call in Try-Catch there. A method that's obviously not meant to interact with the user shouldn't show messages at all. And then you can just pass the exception up until you end up the presentation layer.
Long story short: No message boxes in business logic. User information only in presentation layer.
After reading your second method: Things are even worse here! If the data reader has rows, you set the result of the method to the last (!) result you found (this is a WTF in itself, but another story). If an error occurs, the result is an object of type Exception, so the calling code even needs to make sure to decide whether the result of the function call is actually a field value or an exception!
This is really bad design my friend.
You asked for fixed code:
'Executes SQL commands to the system database
Public Sub ExecSQL(ByVal sql As String)
Dim com As New MySqlCommand(sql)
RefreshConnection()
com.Connection = con
com.ExecuteNonQuery()
End Sub
'Get the value of an specific field in a given sql string
Public Function GetField(ByVal sql As String, ByVal field As String)
RefreshConnection()
Dim com As New MySqlCommand(sql, con)
Dim dReader As MySqlDataReader = com.ExecuteReader
GetField = Nothing
While dReader.Read
GetField = dReader(field).ToString
End While
dReader.Close()
End Function
There are several flaws here. In the interest of brevity, I'll just post some improved code:
'Executes SQL commands to the system database
Private Function ExecSQL(ByVal sql As String, ByVal params As IEnumerable(Of MySqlParameter))
Using cn As New MySqlConnection(GetConnectionString()), _
com As New MySqlCommand(sql, cn)
For Each param As MySqlParameter in params
com.Parameters.Add(param)
Next param
cn.Open()
com.ExecuteNonQuery()
End Using
End Function
'Get the value of an specific field in a given sql string
Private Function GetField(Of T)(ByVal sql As String, ByVal params As IEnumerable(Of MySqlParameter), ByVal field As String) As T
Using cn As New MySqlConnection(GetConnectionString())
com As New MySqlCommand(sql, cn)
For Each param As MySqlParameter In params
com.Parameters.Add(param)
Next param
cn.Open()
Using rdr As MySqlDataReader = com.ExecuteReader()
While rdr.Read()
Return CType(rdr(field), T)
End While
End Using
End Using
Return Nothing
End Function

vb.net polling Sql server once a second causing timeout

I was asked to do a system that would poll one table in the database every second and if it counters a row that meets a criteria start actions to handle that.
I've done this but every now and then I get a time out exception. I have a WPF application where I have a thread that runs in background. This thread has a loop and sleeps for one second at the end of the loop. The connection to the database is opened inside "using" clause.
Below is my thread sub:
Private Sub PollDatabase()
While m_StopThread = False
Try
Dim listOfRows As List(Of DataObject) = db.GetDataObjects()
... Do something with the rows ...
Catch ex As Exception
m_log.WriteLine(ex.ToString())
End Try
Thread.Sleep(1000)
End While
End Sub
And my SQL function looks like this:
Public Function GetDataObjects() As List(Of DataObject)
Dim result As New List(Of DataObject)
Dim sb As New StringBuilder("... the sql query ...")
Using cnn = New SqlConnection(_connectionString)
cnn.Open()
Using cmd = New SqlCommand(sb.ToString(), cnn)
cmd.CommandTimeout = 0
Using DataReader As SqlDataReader = cmd.ExecuteReader()
Do While DataReader.Read()
... read the columns from table
to the dataobject ...
result.Add(DataObject)
Loop
End Using
End Using
End Using
Return result
End Function
Now what seems randomly my log has a time out exception:
System.Data.SqlClient.SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
...
at System.Data.SqlClient.SqlConnection.Open()
My questions are: is this at all save way of doing this? Or am I doing something fundamentally wrong here? And of course if anyone have a suggestion to fix this issue.
EDIT:
I tried a bit different approach with the SQL function. I'm now opening a connection once when my application starts and dumped the "using" clauses. So my function looks something like this now:
Public Function GetDataObjects() As List(Of DataObject)
Dim result As New List(Of DataObject)
Dim sb As New StringBuilder("... the sql query ...")
_sqlCmd.CommandText = sb.ToString()
Using DataReader As SqlDataReader = _sqlCmd.ExecuteReader()
Do While DataReader.Read()
... fill the list with objects ...
Loop
End Using
Return result
End Function
My log is clean form errors. So is there something wrong opening a connection to the server once in a second as I do with the using?
EDIT:
I've done a lot of testing now to identify the problem. What I discovered is that just connecting multiple times to the server doesn't cause any problems. Neither does adding a select statement after the connection. But when I actually implement a function where is the complete reader part and return my results I run into the time out problems. Here is two examples.
This isn't causing issues:
Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs)
Me.DataContext = Me
m_Thread = New Thread(AddressOf ConnectionTestFunction)
m_Thread.IsBackground = True
m_Thread.Start()
End Sub
Private Sub ConnectionTestFunction()
While m_stopThread = False
Try
m_log.WriteLine("GetData (" & m_ThreadCounter & ")")
Using cnn As SqlConnection = New SqlConnection("Data Source=server;Initial Catalog=db;Integrated Security=True;MultipleActiveResultSets=True")
cnn.Open()
Using cmd As SqlCommand = New SqlCommand("SELECT * FROM Data", cnn)
Using DataReader As SqlDataReader = cmd.ExecuteReader()
Do While DataReader.Read()
Loop
End Using
End Using
End Using
Catch ex As Exception
m_log.WriteLine(ex.ToString())
End Try
m_ThreadCounter += 1
Thread.Sleep(1000)
End While
End Sub
This is causing timeout errors:
Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs)
Me.DataContext = Me
m_Thread = New Thread(AddressOf ConnectionTestFunction)
m_Thread.IsBackground = True
m_Thread.Start()
End Sub
Private Sub ConnectionTestFunction()
While m_stopThread = False
Try
m_log.WriteLine("GetData (" & m_ThreadCounter & ")")
Dim datarows As List(Of Data) = Me.GetData()
Catch ex As Exception
m_log.WriteLine(ex.ToString())
End Try
m_ThreadCounter += 1
Thread.Sleep(1000)
End While
End Sub
Private Function GetData() As List(Of Data)
Dim result As New List(Of Data)
Using cnn As SqlConnection = New SqlConnection("Data Source=server;Initial Catalog=db;Integrated Security=True;MultipleActiveResultSets=True")
cnn.Open()
Using cmd As SqlCommand = New SqlCommand("SELECT * FROM Data", cnn)
Using DataReader As SqlDataReader = cmd.ExecuteReader()
Do While DataReader.Read()
Dim d As New Data()
d.DataId = DataReader("DataId")
... etc fields about 10 of them ...
result.Add(d)
Loop
End Using
End Using
End Using
Return result
End Function
I'm really happy if anyone have any thoughts about this... I have to admit I'm really confused now.
Probably, your code is taking longer to complete than the default time-out value for the connection is. Try specifying the time-out when you create your Sql Connection. Make sure that it's longer than the time your code needs to complete.
This approach doesn't seem very good.. Instead of pooling, why not react when new data comes? You can use a trigger or SqlDependency?
http://dotnet.dzone.com/articles/c-sqldependency-monitoring