Alternative to nested Else If statements with different outcomes? - vb.net

Is there any better way of handling nested else if statements that have different outcomes?
Here is an example of one of my nested statements to explain:
If My.Computer.Network.Ping(computerName) = True Then
Call InstallVS(computerName)
If My.Computer.Network.Ping(computerName) = True Then
Call PEC(computerName)
If My.Computer.Network.Ping(computerName) = True Then
Call RemoveSoftware(computerName)
Else
Call WriteLog(computerName & " lost connectivity while attemping to remove the temp software")
End If
Else
Call WriteLog(computerName & " lost connectivity while Forcing Communication")
End If
Else
Call WriteLog(computerName & " lost connectivity while attemping to Install")
End If
I have a requirement to lots of these type of statements, some are smaller, some are a lot larger.

You can create a method called PingOrFail, which will test connectivity or throw an exception otherwise, with a given error message. Then your code flow could look something like this:
Try
PingOrFail(computerName, "attempting to install")
Call InstallVS(computerName)
PingOrFail(computerName, "forcing communications")
Call PEC(computerName)
PingOrFail(computerName, "removing temp software")
RemoveSoftware(computerName)
Catch ex As Exception
Call WriteLog (computerName & " lost connectivity while " & ex.Message)
End Try
And this is the PingOrFail method:
Public Sub PingOrFail(computerName as String, message As String)
If My.Computer.Network.Ping(computerName) = False
Throw New Exception (message)
End If
End Sub

These statements don't need to be nested, they could just raise exceptions if they fail.
Private Sub DoStuff(ByVal computerName As String)
Try
If My.Computer.Network.Ping(computerName) Then
InstallVS(computerName)
Else
Throw New Exception(computerName & " lost connectivity while attemping to Install")
End If
If My.Computer.Network.Ping(computerName) Then
PEC(computerName)
Else
Throw New Exception(computerName & " lost connectivity while Forcing Communication")
End If
If My.Computer.Network.Ping(computerName) Then
RemoveSoftware(computerName)
Else
Throw New Exception(computerName & " lost connectivity while attemping to remove the temp software")
End If
Catch ex As Exception
WriteLog(ex.Message)
End Try
End Sub

Related

Unhandled Exception in Background Worker

Hi there I am carrying out some integration testing in an application I am developing. The specific element that is causing an issue is a call to a background worker which interrogates an Oracle database. When an error is encountered in the query I want the exception detail to percolate up the call stack to the application level and at that point provide an appropriate user compatible message. In the example test there is a syntax error in the underlying SQL which results in an OraEx Exception:
Oracle.DataAccess.Client.OracleException ORA-00907: missing right parenthesis
Unfortunately the code generates the following exception:
System.Reflection.TargetInvocationException was unhandled
Message: An unhandled exception of type
'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
Additional information: Exception has been thrown by the target of an
invocation.
in the DoWork sub of the backgroundworker, despite my belief that I am handling the exception correctly. Its pretty obvious that I am missing something fundamental here, can someone suggest a solution please.
Thanks in Advance
Paul J.
Here is the code that makes the call to the background worker:
Private Sub EventSearch(ByVal mySQL As String)
Const procName As String = "EventSearch"
Try
_eventMngr = New ScadaEventManager(_CurrentDB, _userName, _myPwd)
_eventMngr.SQL = mySQL
'Set the flag and stop query tool status accordingly
_Stopped = False
uxStopQueryTool.Enabled = True
'activate the timer object to ensure that the execute query menu
'and tool remain disabled until all background processing is complete
uxBackWorkTimer.Enabled = True
_logger.SendLog(Me.Name & "." & procName & " - Scanning for data.", NLog.LogLevel.Trace)
ReviseStatus(2, "Scanning for data. Please wait...", Color.Black, True, True)
'Force the thread to sleep for half a second so the user can see the scanning state taking place
Threading.Thread.Sleep(500)
'Launch the background worker to retrieve the required data from the database
uxBWScan.RunWorkerAsync(_eventMngr)
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, My.Application.Info.ProductName)
_logger.SendLog(ex.Message & ". Thrown in module " & Me.Name.ToString & "." & procName, NLog.LogLevel.Error, ex)
Call ResetStatus()
Finally
End Try
End Sub
And here is the code executed by the background worker:
Private Sub uxBWScan_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles uxBWScan.DoWork
Const procName As String = "uxBWScan_DoWork"
Try
e.Argument.CountRecords(_queryTypeID)
e.Result = e.Argument.RecordCount
Catch NullEx As NullReferenceException
_logger.SendLog(NullEx.Message & ". Thrown in module " & Me.Name.ToString & "." & procName, NLog.LogLevel.Error, NullEx)
Throw
Catch OraEx As OracleException
_logger.SendLog(OraEx.Message & ". Thrown in module " & Me.Name.ToString & "." & procName, NLog.LogLevel.Error, OraEx)
Throw
Finally
End Try
End Sub
And here is the low level code that generates the error:
Public Sub CountRecords(ByVal queryType As Integer)
_myDataset = New DataSet
Try
_myDataset = _myScadaEventDB.CountRecords(_sqlText)
If _myDataset.Tables(0).Rows.Count > 0 Then
If queryType = Enums.QueryType.General Or queryType = Enums.QueryType.KeyPerformanceIndicators Or queryType = Enums.QueryType.TelecontroAnalysis Then
_recordCount = _myDataset.Tables(0).Rows(0).Item("RecordCount")
Else
'The query is grouped therefore count the number of records in the table
_recordCount = _myDataset.Tables(0).Rows.Count
End If
Else
_recordCount = 0
End If
Catch ex As Exception
Throw
Finally
End Try
End Sub
Ok, problem solved. Removed the try catch block from DoWork and moved my exception handling into 'RunWorkerCompleted' using e.error. Some reading of the documentation (RTFM...), highlighted the fact that using Try/Catch in the worker thread interferes with the native functionality of the BackgroundWorker. Thanks again everyone for your input.
Paul,

How do I handle NullReferenceException with my code

How do I handle this type of error or exception?
Try
If log.Trim = txtUSN.Text Then
MessageBox.Show("USN found: " & log)
Else
MessageBox.Show("USN not found: " & log)
End If
Catch ex as Exception
MessageBox.Show(ex.Message)
The message was "Object reference not set to an instance of an object."
This is the rest of the code:
Dim log As String
Dim sql As New SqlCommand
sql.Connection = MyConnection
sql.CommandText = "SELECT * FROM dbo.tblAcc WHERE USN = '" & txtUSN.Text & "' "
MyConnection.Open()
log = sql.ExecuteScalar
MyConnection.Close()
The simple answer is your trying to use an object that is nothing. If it's nothing you can't use it, hence "Object reference not set to an instance of an object."
As already mentioned in my comments above, the culprit is: log. I'm not sure where you have declared this or when your using it and how your using it, for all I know it's nothing. If you have more code that would be greatly appreciated as I can point out where it's nothing, until then here's how to get around your issue.
Try
If log IsNot Nothing Then
If log.Trim = txtUSN.Text Then
MessageBox.Show("USN found: " & log)
Else
MessageBox.Show("USN not found: " & log)
End If
Else
MessageBox.Show("Log is NOTHING!")
End If
Catch ex as Exception
MessageBox.Show(ex.Message)
End Try
**EDIT**
After you posted more code in a comment (please post code in the area, not in comment's) it seem's there are a few issue's. You have log defined as a string; when you do this set it to something like: String.Empty instead of nothing. Also you want to sse the ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database which could be an integer, long, single etc data types. In your query your selecting everything, you can't call ExecuteScalar to return that data... I would recommend looking up information about building queries and executing them, it's to long for me to get in depth with it here.
Happy Coding!
Make sure that (log) is not an empty string.
if not String.IsNullorEmpty(log) then
end if

Process Start and Errors from Slow Applications

I made an application that our company uses to launch databases and updates them on the users machine, when needed.
I am having a slight problem when it comes to launching databases and the database starts up slow. When this occurs my application throws an exception, as I assuming its awaiting some kind of response back.
As of now the error thrown is: The system cannot find the file specified
I am trying to prevent this exception logging for cases like this(Slow Application), but still allow the logging if a real error occurs while opening a database.
Current Code I am using:
Private Sub OpenApplication()
If File.Exists(LocalPathString) Then ' File Found. Open the File.
Try
Dim ps As New Process
ps = Process.Start(LocalPathString)
Catch ex As Exception
ex.Source += " | " & LocalPathString
RaiseEvent ShowError(ex)
Finally
RaiseEvent CancelIt() ' Thread Complete. Close the ActionForm
End Try
Else
If LocalPathString = vbNullString Then
RaiseEvent CancelIt() ' No file exits. Cancel thread.
Else
RaiseEvent ShowError(New Exception("Database Not Located: " & LocalPathString))
End If
End If
End Sub
StackTrace:
System.Diagnostics.Process.StartWithShellExecuteEx(startInfo As ProcessStartInfo)
App.exe: N 00912
System.Diagnostics.Process.Start()
App.exe: N 00136
System.Diagnostics.Process.Start(startInfo As ProcessStartInfo)
App.exe: N 00049
SAMi.ActionClass.OpenApplication()
App.exe: N 00117
Maybe I'm missing something, but why don't you simply omit the logging if you found that specific exception?
Catch ex As Exception
ex.Source += " | " & LocalPathString
if not ex.Message.Contains("The system cannot find the file specified") Then
RaiseEvent ShowError(ex)
end if

How to continue insert if one row fails

I have a while loop where it fetches record from csv and inserts to sql table. Now csv may contain many rows.
What I want is if one row fails just log to a file and continue with next record. I was thinking of try and catch but that will exit the program. So, any suggestions?
while (csv.readnextline)
'assign csv columns to objects
try
'insert to db
Catch ex As Exception
'write to log file
End Try
I need the above code to continue after catching an exception.
Thanks
Try and catch do not exit the program, they just control the flow of the code in case something exceptional happens.
When an exception happens in the try block, the execution continues on the first line of the (corresponding) catch block. After the execution of the catch block, the code continues on the first line after the catch, which in your case could be the End While which will continue the loop.
So an construction like this
While dr.Read
Try
InsertRowIntoDataBase()
Catch ex As Exception
LogErrorToFile(ex)
End Try
End While
should work for you.
However, this is a bad design, as it will generate and log an exception, no matter what the problem is, whether the data is invalid, or the sql server is down, or even if there is an error in your code (e.g. some lurking NullReferenceException). You should limit the handling of exception to a specific case, e.g. to a problem with the database, like this:
While dr.Read
Try
InsertRowIntoDataBase()
Catch ex As SqlClient.SqlException
LogDataBaseErrorToFile(ex)
End Try
End While
Also, if there are known possible problems with the data (e.g. a string in the csv where an integer is expected) it's better to just check that than to use an exception mechanism, something along these lines:
While dr.Read
Try
If Not IsRowValid() Then
LogInvalidDataToFile()
Continue While
End If
InsertRowIntoDataBase()
Catch ex As SqlClient.SqlException
LogDataBaseErrorToFile()
Catch ex As Exception
LogGenericErrorToFile()
End Try
End While
no it won't exit the program, depending on how/where you handle the exception. If you do something like :
Dim WrongValuedLinesList As New List(Of String)
Dim ConversionFailedList As New List(Of String)
Dim InsertionFailedList As New List(Of String)
Dim NumberOfInsertedLines As integer = 0
For Each (CurrentLine in my csv)
' 1. line processing
Try
' (process my line : split, convert, check range...)
If (I know the insertion will fail) Then
' (Store information about that wrong line, in List, log, or do nothing)
WrongValuedLinesList.Add(" This line : " & CurrentLine
& " has wrong values because...
Continue For
End If
Catch ex as exception
' (here handle the line conversion failed : store in list, or log, or do nothing ...)
' for expl :
ConversionFailedList.Add(" Conversion failed for line " & CurrentLine
& " exception details : " & ex.message " )
End Try
' 2. Line insertion
Try
'(insert my processed data into database)
NumberOfInsertedLines +=1
Catch ex as exception
' (here handle the insertion failed exception (expl : primary key might not be unique)
' : store in list, log, do nothing...)
' for example :
InsertionFailedList.Add(" Insertion failed for line " & CurrentLine
& " exception details : " & ex.message " )
End Try
Next
(Here you might wanna report how things went to your user using
your error list.)

VB.NET 1.1 Safely abort thread

I'm trying to safely kill a thread. In my button click I have:
try
dim bar as new foo()
dim mythread as New System.Threading.Thread(AddressOf bar.Start)
mythread.Start()
sleep(1000)
mythread.abort()
catch ex as Exception
msgbox ex.Message
end try
In my Class I have:
class foo
public function Start()
Try
do some stuff...
Catch tae As ThreadAbortException
Thread.ResetAbort()
Catch ex As Exception
LogData("[ ERROR ] ", "[ Start ]" & ex.Message & " line: " & Erl())
End Try
end sub
end class
When it goes to abort the thread I still get a thread abort error. What am I doing wrong?
It's really impossible to "safely" abort a thread. You should, instead, focus on having a mechanism where you can notify the thread that it should exit, and allow it to cooperatively exit (via returning from its main entry point method).