Do something with returned value - vb.net

I have written a function that tells you its function itselfs as you read it:
Public Function TestConnect()
Dim verbinding As MySqlConnection
Dim errStatus As String
verbinding = New MySqlConnection()
verbinding.ConnectionString = "server=" & vardbHost & "; port=" & vardbPort & "; uid=" & vardbUser & "; pwd=" & vardbPass & "; database=" & vardbName & ";"
Try
verbinding.Open()
verbinding.Close()
errStatus = 0
Catch myerror As MySqlException
verbinding.Dispose()
verbinding.Close()
errStatus = 1
End Try
Return errStatus
End Function
Now I call this function in my main form and I thought that if I used Try and then catch the 1 or 0 then I could do something with it. (eg. Display a form with the error message) but that does not seem to work and I could not find anything on Google that applies to my problem.
Could anybody explain to me why I am so dumb and how I could better understand how to handle a returned value?

The function will be returning your value, but you need to get that assign that returned value to a variable, and then make use of it in your Calling method, eg:
Dim errStatus As Integer
errStatus = SQLHook.TestConnect()
If errStatus = 1 Then
'Show the error form
End If
Or more briefly, just test the returned value directly:
If SQLHook.TestConnect()= 1 Then
'Show the error form
End If
You should also really sort out the variable typing in your function:
Public Function TestConnect() as Boolean
Dim errStatus As Boolean
Try
errStatus = True
Catch myerror As MySqlException
errStatus = False
End Try
Return errStatus
End Function
or even more simply, don't bother with the variable:
Public Function TestConnect() as Boolean
Try
...
Return True
Catch myerror As MySqlException
...
Return False
End Try
End Function

Not entirely sure I understand the question, but do you mean something like this?
Public Function TestConnect() As Int32
...
Dim errStatus As Int32
...

Dim returnCode as Int32 = SQLHook.TestConnect()
MessageBox.show(
If(returnCode = 1, "OK", "Error"), "AppName", MessageBoxButtons.OK,
If(returnCode = 1, MessageBoxIcon.Information, MessageBoxIcon.Error)
)

Related

Function start doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used

can you help its say's (Function 'Start' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.)
Private Function Start() As Object
Dim thr As Integer = TextBox4.Text
Dim Threading As Integer = Nothing
If CheckBox1.Checked = True Then
Threading = thr + 300
Else
Threading = thr
End If
While Not stopp
Try
Try
Dim i As String = Geting("https://i.instagram.com/api/v1/users/search?q=" & TextBox5.Text & "&access_token=" & Guid.NewGuid.ToString.ToUpper & "/")
If i.Contains("""username"": """ & TextBox5.Text & """") Or Nothing Then
intt += 1
Me.Invoke(Sub() TextBox3.Text = intt)
Else
If ChangeUserName(TextBox5.Text) Then
Me.Invoke(Sub() Label1.Text = "username claimed " & TextBox5.Text)
stopp = True
End If
End If
Catch ex2 As Exception
End Try
Thread.Sleep(Threading)
Catch ex As Exception
End Try
End While
End Function
You probably don't need to return a value from your function. Change
Private Function Start() As Object
into
Private Sub Start()
As a side note, your error handling is bad.
Try
(Do something)
Catch Exception
End Try
should never be used. It prevents you from seeing when something goes wrong (even if your code has a flaw).

Formatting 45.22.30 in VB.NET [duplicate]

Under keypress event, I have a function validating the entered characters, this is my code.
Public Function vNum2(val As Object)
Dim result As Boolean = False
Dim allowedChars As String = "0123456789." & vbBack
Try
If allowedChars.IndexOf(val) = -1 Then
result = True
End If
Catch ex As Exception
MsgBox("Error 1010xVNum2: " & ex.Message)
End Try
Return result
End Function
How do i validate a decimal when I entered more than 2 dots in decimal? When I press another dot, the textbox will not receive the character.
E.g: -> correct entry 45.23 receive the first dot.
-> validating entry 45.2.3 will not receive the next dot.
Try this :
Public Function vNum2(val As Object)
Dim result As Boolean = False
Try
'Dim allowedChars As String = "42.2.3"
Dim allowedChars As String = val.ToString()
'Bellow line will count how many dots are in string, if there one or none, result will be True
If allowedChars.Where(Function(dots) dots = ".").Count < 2 Then result = True
Catch ex As Exception
MsgBox("Error 1010xVNum2: " & ex.Message)
End Try
Return result
End Function

How to dispay data from q to textbox on VB.net

this is stored procedure
this is Function for SelectOne
Public Function One(Id As Integer) As Object Implements IStudents.One
Try
Return db.SP_SelectOneStudent(Id).ToArray
Catch ex As Exception
Return False
End Try
End Function
Dim q = student.One(StudentID)
Assuming you want to show every field in the variable q into a TextBox:
...
Dim StringToShow as String = ""
For Each StringToAdd as String In q
StringToShow &= StringToAdd & " "
Next
YourTextBox.Text = StringToShow
...

Error - The transaction is either not associated with the current connection or has been completed

Having this error in my web app.
The transaction is either not associated with the current connection or has been completed.
#Region "Database Queries"
Private Shared oSqlConnection As SqlConnection
Private Shared oSqlDataAdapter As SqlDataAdapter
Private Shared oSqlCommand As SqlCommand
Private Shared oSqlTransaction As SqlTransaction
Private Shared _strCommand As String
Public Shared Property strCommand() As String
Get
Return _strCommand
End Get
Set(ByVal value As String)
If Not InTransaction Then RollBack_Transaction()
_strCommand = "SET DATEFORMAT mdy " & vbCrLf & value
DbQuery()
End Set
End Property
Protected Shared Sub DbQuery()
'Try
If Not InTransaction Then
RollBack_Transaction()
oSqlCommand = New SqlCommand(_strCommand, oSqlConnection)
Else
oSqlCommand = oSqlConnection.CreateCommand
If _InTransaction_Initial Then
oSqlConnection.Open()
oSqlTransaction = oSqlConnection.BeginTransaction(IsolationLevel.ReadCommitted)
_InTransaction_Initial = False
End If
oSqlCommand.Transaction = oSqlTransaction
oSqlCommand.CommandText = _strCommand
oSqlCommand.CommandTimeout = 0
End If
oSqlDataAdapter = New SqlDataAdapter(oSqlCommand)
Ds = New DataSet
oSqlDataAdapter.Fill(Ds) '**<- - - The error occurs here**'
'Catch ex As Exception
' SetMessage(ex)
' ' MsgBox("Server: " & ServerName & vbCrLf & "User Id: " & SqlID & vbCrLf & "Password: " & SqlPassword & vbCrLf & "Database: " & MainDb)
'End Try
'oSqlConnection.Close()
End Sub
Private Shared _InTransaction_Initial As Boolean = False
Private Shared InTransaction As Boolean
Public Shared Sub StartTransaction()
_InTransaction_Initial = True
InTransaction = True
End Sub
Public Shared Sub RollBack_Transaction()
Try
oSqlTransaction.Rollback()
Catch ex As Exception
End Try
Try
oSqlConnection.Close()
Catch ex As Exception
End Try
InTransaction = False
End Sub
Public Shared Sub Commit_Transaction()
Try
oSqlTransaction.Commit()
Catch ex As Exception
End Try
Try
oSqlConnection.Close()
Catch ex As Exception
End Try
InTransaction = False
End Sub
Function dsCount() As Long
Return Ds.Tables(0).Rows.Count
End Function
Please see the Bold text in the code.
Hope to hear positive response from you.
Regards,
It error happens because you have used Shared member variables.
You can uses shared functions, but you should avoid shared variables or members at all.
Don't "save" any information in shared context. These are available in application scope and that may be the same for different requests from different users.
Running data access operations in shared (static) functions should be no problem.
But having shared members will cause integrity and concurrency problems making the application unstable
placing these as variables inside methods
oSqlConnection As SqlConnection
oSqlDataAdapter As SqlDataAdapter
oSqlCommand As SqlCommand
oSqlTransaction As SqlTransaction
will solve the problem.

Timeoutexception on TCP not handled

I took this code from a website since VS 2010 doesn't support the timeout for the TCP connections:
Private Function ConnectWithTimeout() As Boolean
Dim ar As IAsyncResult = TCPClient.BeginConnect(IPAddress, TCPPort, Nothing, Nothing)
Dim wh As System.Threading.WaitHandle = ar.AsyncWaitHandle
Try
If Not ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), False) Then
TCPClient.Close()
TCPClient = New System.Net.Sockets.TcpClient
Throw New TimeoutException()
End If
Catch ex As Exception
ThrowError("Timeout on connecting to " & IPAddress & " at port " & TCPPort & ".")
Return False
Finally
wh.Close()
End Try
Return True
End Function
And it works fine, but everytime, it gives me this on the debug output:
"A first chance exception of type 'System.TimeoutException' occurred in"
Even if I'm catching all the exceptions. Is there a way to get rid of this exception message as it is handled?
I've tried this:
Dim connectDone As New System.Threading.AutoResetEvent(False)
TCPClient.BeginConnect(IPAddress, TCPPort, New AsyncCallback(Sub(ar As IAsyncResult)
TCPClient.EndConnect(ar)
connectDone.Set()
End Sub), TCPClient)
'client.BeginConnect("127.0.0.1", 80, new AsyncCallback(delegate( IAsyncResult ar ) { client.EndConnect( ar ); connectDone.Set(); }), client);
If Not connectDone.WaitOne(2000) Then
Debug.WriteLine("TIMEOUT")
Return False
End If
Return True
But it gives me InvalidOperationException on the beginconnect line:
BeginConnect cannot be called while another asynchronous operation is in progress on the same Socket.
Private Function ConnectWithTimeout() As Boolean
Dim ar As IAsyncResult
Dim wh As System.Threading.WaitHandle
Try
ar = TCPClient.BeginConnect(IPAddress, TCPPort, Nothing, Nothing)
wh = ar.AsyncWaitHandle
Cath ex as Exception
'Code to catch exception
End Try
Try
If Not ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(2), False) Then
TCPClient.Close()
TCPClient = New System.Net.Sockets.TcpClient
Throw New TimeoutException()
End If
Catch ex As Exception
ThrowError("Timeout on connecting to " & IPAddress & " at port " & TCPPort & ".")
Return False
Finally
wh.Close()
End Try
Return True
End Function