Question : catching and handling SQL deadlocks from vb.net

I'm using vb.net 2005 and SQL 2005. Very occasionally I am getting a SQL deadlock - "Transaction (Process ID 258) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction."

- how do I check for the deadlock exception in my catch block?
- I am handling the transaction from .NET so I do a trans.commit or trans.rollback. However, in some situations SQL does the rollback itself - in deadlock situations for example. How can I check that my transaction is still 'active' before I attempt to rollback?

Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
Try
            cn.startUPConnection()
            Using tran As SqlTransaction = 						cn.appConnection.BeginTransaction(IsolationLevel.ReadCommitted)	
                Try
                    
                    If objtransMasterList.IsDirty Then
                        Dim objTransMaster As SQLTransMaster
                        For Each objTransMaster In objtransMasterList
                            If objTransMaster.IsNew Then
                                Dim cmd As New SqlCommand
                                cmd.CommandText = SQLInsertStoredProc
                                cmd.Connection = cn.appConnection
                                cmd.Transaction = tran
                                cmd.CommandType = CommandType.StoredProcedure
                                saveTransMasterParamsFromObj(cmd, CMDTYPES.INSERT, objTransMaster)
      
                                cmd.ExecuteNonQuery()
                            End If
                        Next
                    End If
                    tran.Commit()
                Catch a As Exception
                    tran.Rollback()
                    success = False
                    objSQLErrorList.processError(a)
                    unLockIt()
                    GoTo finally_Renamed
                End Try
            End Using
 
        Catch b As Exception
            success = False
            objSQLErrorList.processError(b)
            unLockIt()
        Finally
            If Not cn.appConnection Is Nothing Then
                If cn.appConnection.State <> ConnectionState.Closed Then cn.CloseConnection()
            End If
        End Try

Answer : catching and handling SQL deadlocks from vb.net

Is the tran.rollback() throwing an exception when there is nothing to roll back? if thats the case, put it inside a try/catch block and ignore the error. If there's nothing to rollback (ie the trans.commit executed sucessfully or sql server rolls back automatically like for deadlocks) then it won't roll anything back.
Random Solutions  
 
programming4us programming4us