I am getting following error:
Arithmetic operation resulted in an overflow
on the code below:
Public Function DoEncode(ByVal aPassword As String, ByVal aPassword2 As String) As String
Dim ascii As New ASCIIEncoding()
Dim b As Byte() = ascii.GetBytes(aPassword)
Dim b2 As Byte() = ascii.GetBytes(aPassword2)
Dim iDiff As UInt32 = b2(0) - b(0)
For i As Integer = 0 To b.Length - 1
b(i) += CByte(iDiff)
Next
Return ascii.GetString(b)
End Function
I have used the function in my login form:
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
If UsernameTextBox.Text.Trim() = "" Then
MessageBox.Show("Please enter your user id", "User ID", MessageBoxButtons.OK, MessageBoxIcon.[Stop])
Return
End If
If PasswordTextBox.Text.Trim() = "" Then
MessageBox.Show("Please enter your password", "User ID", MessageBoxButtons.OK, MessageBoxIcon.[Stop])
Return
End If
If O.AppMan.DoLogin(UsernameTextBox.Text, PasswordTextBox.Text) Then
DialogResult = System.Windows.Forms.DialogResult.OK
End If
End Sub
Upper code is used in:
Public Class TApplicationManager
Public Class O
Public Shared AppMan As New TApplicationManager()
End Class
Public Function DoEncode(ByVal aPassword As String, ByVal aPassword2 As String) As String
Dim ascii As New ASCIIEncoding()
Dim b As Byte() = ascii.GetBytes(aPassword)
Dim b2 As Byte() = ascii.GetBytes(aPassword2)
Dim iDiff As UInt32 = b2(0) - b(0)
For i As Integer = 0 To b.Length - 1
b(i) += CByte(iDiff)
Next
Return ascii.GetString(b)
End Function
Public Function DoLogin(ByVal strUser As String, ByVal strPwd As String) As Boolean
Dim dtbUser As New DataTable()
Dim dtbUserCare As New DataTable()
Dim UserName As String
Dim UserPass As String
Dim cnn As New MySqlConnection(My.Settings.sys_dbConnectionString)
Dim strLoginCare As String = "SELECT * FROM tblusers where Username = '" + strUser + "'"
Dim daUser As New MySqlDataAdapter(strLoginCare, cnn)
dtbUser.Clear()
daUser.Fill(dtbUser)
If dtbUser.Rows.Count = 0 Then
MessageBox.Show("User does not exist", "User status", MessageBoxButtons.OK, MessageBoxIcon.[Stop])
Return False
End If
Dim drwUser As DataRow = dtbUser.Rows(0)
UserPass = drwUser("Password").ToString()
UserName = drwUser("Username").ToString()
Dim daUserCare As New MySqlDataAdapter(strLoginCare, cnn)
dtbUserCare.Clear()
daUserCare.Fill(dtbUserCare)
If dtbUserCare.Rows.Count = 0 Then
MessageBox.Show("Invalid user id", "User status", MessageBoxButtons.OK, MessageBoxIcon.[Stop])
Return False
End If
Dim drwUserCare As DataRow = dtbUserCare.Rows(0)
If drwUserCare("Password").ToString() <> DoEncode(strPwd, drwUserCare("Password").ToString()) Then
MessageBox.Show("Invalid password. Please try again", "User status", MessageBoxButtons.OK, MessageBoxIcon.[Stop])
Return False
End If
If drwUserCare("status").ToString() <> "Y" Then
MessageBox.Show("User is not active", "User status", MessageBoxButtons.OK, MessageBoxIcon.[Stop])
Return False
End If
UserPass = drwUserCare("Password").ToString()
UserName = drwUserCare("Username").ToString()
Return True
End Function
End Class
Why am I getting this error?
Ok I'm going to take a stab it's this:
Dim iDiff As UInt32 = b2(0) - b(0)
For i As Integer = 0 To b.Length - 1
b(i) += CByte(iDiff)
Next
A) Uint32 can't be negative - and you are performing a subtraction between two bytes.
B) You are then casting that subtracted value to a Byte - bytes can't be negative, and from memory will throw this exception if you attempt to do so.
I don't actually understand what you're attempting to do in the above loop.
EDIT
As per your comment about this code working in c#, but not in VB, my answer still applies. The conversion is failing, because of either negative numbers or greater than 255.
c# does not automatically check for overflow errors where VB does.
You can disable this behaviour although changing the code to not overflow would be better in my opinion. You may get unexpected results.
See: https://msdn.microsoft.com/en-us/library/aa716336(v=vs.60).aspx
You can disable it by:
Project properties, enable Configuration Properties => Optimizations
=> Remove Integer Overflow Checks.
The same behaviour can be implemented in c# by wrapping the conversion / calculation in a 'checked' block.
Related
My application would parse straight from the source and worked fine. However, since the original source of information was not always available, I decided to store it into a MySQL database. I store the JSON string in a table and then extract it later. However, I am now receiving the titled error message. I believe somehow, the string is being truncated but I do not understand why. Below is my code. My question: How do I stop the titled error?
to write the string to the database
Dim strUpdate As String = rrm.returnLeagueItems()
If String.Compare(strUpdate, strError) = 0 Then
rm.updateDynamicQuery("rgo_manager", {"manager", "region"}, {strUpdate, rrm.strRegion}, {"manager_name"}, {"items"})
End If
To pull the JSON request
Private Function returnJSONRequest(ByVal strWebAddress As String) As String
Try
Dim strReturnArray As String() = {}
Dim wrWebResponse As WebResponse
Dim wrWebRequest As WebRequest = HttpWebRequest.Create(strWebAddress)
wrWebResponse = wrWebRequest.GetResponse()
Dim srStreamReader As New StreamReader(wrWebResponse.GetResponseStream)
Dim strReturn As String = srStreamReader.ReadToEnd()
wrWebResponse.Dispose()
srStreamReader.Dispose()
Console.WriteLine("Success: " + strWebAddress)
Return strReturn
Catch ex As Exception
Console.WriteLine("Failure: " + strWebAddress)
Return "IAmError"
End Try
End Function
JSON object
Public Class RGOLeagueItemManager
Inherits RGOLeagueObjectManager
Public Property league_container As LeagueItemContainer
Public Sub New()
league_container = JsonConvert.DeserializeObject(Of LeagueContainer)(System.Text.Encoding.UTF8.GetString(rm.returnDBQueryAsDataTable("SELECT manager FROM rgo_manager WHERE manager_name = 'items';").Rows(0).Item(0)))
End Sub
End Class
rm is simply my remote manager to access my database.
rrm is the class that contains all the JSON requests to the server where all the web addresses are stored but only the returnJSONRequest is important. I would highly prefer not to have to "chunk" the data either. If I could load all the information, I should be able to do so with MySQL. The field is a BLOB.
Edit: Here is the rm code since it appears the string is being truncated upon entry into the database but is the full size in the query parameter.
Public Sub updateDynamicQuery(ByVal strTable As String, ByVal strSetParameters As String(), ByVal strSetValues As String(), ByVal strWhereParameters As String(), ByVal strWhereValues As String())
Dim strQuery As String = "UPDATE " + strTable + " SET "
Dim intSetCount As Integer = strSetParameters.Length() - 1
For i = 0 To intSetCount
strQuery += strSetParameters(i) + " = #setparameter" + i.ToString()
If i < intSetCount Then
strQuery += ", "
End If
Next
strQuery += returnWhereClause(strWhereParameters)
strQuery += ";"
Console.WriteLine(strQuery)
Dim cmd As New MySqlCommand(strQuery, league_champion)
Dim intParameterCount As Integer = strWhereParameters.Length() - 1
For k = 0 To intParameterCount
cmd.Parameters.AddWithValue("#parameter" + k.ToString, strWhereValues(k))
Console.WriteLine(strWhereValues(k))
Next
For i = 0 To intSetCount
cmd.Parameters.AddWithValue("#setparameter" + i.ToString, strSetValues(i))
Console.WriteLine(strSetValues(i))
Next
executeQuery(cmd)
End Sub
Public Sub executeQuery(ByVal cmd As MySqlCommand)
Try
connection.Open()
cmd.ExecuteNonQuery()
Console.WriteLine("Query success: " + cmd.CommandText)
Catch ex As Exception
Console.WriteLine("Query failed: " + cmd.CommandText + "//" + ex.Message)
End Try
connection.Close()
End Sub
I don't know what's the real problem since there are no error being reported. So what I want these codes to do is insert a transaction record to the database but there is nothing being returned. Here are the codes that related to this:
MainForm
Private Sub PayButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PayButton.Click
Dim payment As New Payment
payment.Show()
AddHandler payment.PaymentEvent, AddressOf paymentSuccess
payment.PaymentAmount = TransactionTotal
End Sub
Public Sub paymentSuccess(ByVal sender As Object, ByVal e As Payment.PaymentMadeEventArgs)
mydbcon = New MySqlConnection
mydbcon.ConnectionString = "server=localhost;userid=root;password=;database=sdudb"
Dim reader As MySqlDataReader
Try
mydbcon.Open()
Dim Query As String
Query = "select * from inventory"
COMMAND = New MySqlCommand(Query, mydbcon)
reader = COMMAND.ExecuteReader()
While reader.Read
Dim itId As Integer = reader.GetString("itemid")
Dim itName As String = reader.GetString("itemname")
If e.PaymentSuccess = True Then
paymentSuccessQuery(itId, itName)
End If
End While
reader.Close()
mydbcon.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub paymentSuccessQuery(ByVal itemid, ByVal itemname)
mydbcon = New MySqlConnection
mydbcon.ConnectionString = "server=localhost;userid=root;password=;database=sdudb"
Dim reader As MySqlDataReader
Try
mydbcon.Open()
Dim Query As String
Query = "INSERT INTO transaction (itemid, itemname) VALUES('" & itemid & "', '" & itemname & "')"
COMMAND = New MySqlCommand(Query, mydbcon)
reader = COMMAND.ExecuteReader()
If reader.Read Then
MessageBox.Show("Unable to save transaction!")
Else
MessageBox.Show("Transaction Saved!")
End If
reader.Close()
mydbcon.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Transactionform
Public Class Payment
Public Delegate Sub PaymentMadeEvent(ByVal sender As Object, ByVal e As PaymentMadeEventArgs)
Public Event PaymentEvent As PaymentMadeEvent
Private _paymentAmount As Decimal
Public Property PaymentAmount As Decimal
Get
Return _paymentAmount
End Get
Set(ByVal value As Decimal)
_paymentAmount = value
AmountBox.Text = String.Format("{0:c}", _paymentAmount)
End Set
End Property
Private Sub PayButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PayButton.Click
Dim total As Decimal = 0
Try
total = Decimal.Parse(AmountBox.Text.TrimStart("₱")) - Decimal.Parse(PaymentBox.Text)
Catch
MessageBox.Show("Error Occured, please enter a valid amount!")
Return
End Try
If (total > 0) Then
AmountBox.Text = total.ToString()
Else
MessageBox.Show("Please give " + String.Format("{0:c}", -total))
RaiseEvent PaymentEvent(Me, New PaymentMadeEventArgs() With {.PaymentSuccess = True})
End If
End Sub
Public Class PaymentMadeEventArgs
Inherits EventArgs
Private _paymentSuccess As Boolean
Public Property PaymentSuccess As Boolean
Get
Return _paymentSuccess
End Get
Set(ByVal value As Boolean)
_paymentSuccess = value
End Set
End Property
End Class
End Class
ExecuteReader executes the command (the insert) but it has been built to return the rows extracted by a SELECT command.
Calling Read to discover if your INSERT has been successful is meaningless in this context.
You should call ExecuteNonQuery, catch the return value, and if it is not equal to zero, then you have inserted the record.
Private Sub paymentSuccessQuery(ByVal itemid, ByVal itemname)
Using mydbcon = New MySqlConnection("server=localhost;userid=root;password=;database=sdudb"
Try
mydbcon.Open()
Dim Query As String
Query = "INSERT INTO transaction (itemid, itemname) " & _
"VALUES(#id, #name)"
Using COMMAND = New MySqlCommand(Query, mydbcon)
COMMAND.Parameters.Add("#id", MySqlDbType.VarChar).Value = itemid
COMMAND.Parameters.Add("#name", MySqlDbType.VarChar).Value = itemname
Dim rowsAdded = COMMAND.ExecuteNonQuery()
if rowsAdded = 0 Then
MessageBox.Show("Unable to save transaction!")
Else
MessageBox.Show("Transaction Saved!")
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
Notice also the I have changed your code to use the appropriate Using statement around the disposable objects like the connection and the command and, of utmost importante, I have changed your query to use a more safe parameterized query approach (not sure about the MySqlDbType for the ID parameter, it seems to be an integer but in your original query you put it between single quotes like a string)
I have a problem in my vb.net code, I have a login form that is connected to a mysql database. It can already check if the user is in the database, now the next thing to do is to get the name, access level and userId from the database according to the logged in account, I have store it in a module that holds a global variable.
This is my code.
Module pubvars
Public Gplev As String
Public Gname As String
Public GuserId As Integer
End Module
Then I will use this variables on other forms, in the first session of logging in the variables was read correctly,but when I logged out, then login with a new user account, the variable passed was not updated, which is supposedly changed as a new account was logged in.
Here is the code where I declare the variables.
Dim search1 As MySqlCommand = New MySqlCommand("SELECT * FROM `login` WHERE login.username = '" & TextBox1.Text & "' AND login.password = '" & TextBox2.Text & "'", con)
con.Open()
Dim dr As MySqlDataReader = search1.ExecuteReader
Dim userFound As Boolean = False
While dr.Read
userFound = True
pubvars.Gname = dr("name").ToString
pubvars.Gplev = dr("permission_level").ToString
pubvars.GuserId = dr("userId").ToString
End While
If userFound = True Then
main_menu.Show()
Me.Hide()
Else
MsgBox("Sorry, username or password not found", MsgBoxStyle.OkOnly, "Invalid Login")
TextBox1.Text = ""
TextBox2.Text = ""
End If
And here is the code where I used the variables in the second form.
Private Sub main_menu_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Label3.Text = pubvars.Gname
If pubvars.Gplev = "2" Then
Button8.Enabled = False
Button8.Visible = False
ElseIf pubvars.Gplev = "3" Then
Button8.Enabled = False
Button8.Visible = False
ElseIf pubvars.Gplev = "4" Then
Button8.Enabled = False
Button8.Visible = False
End If
End Sub
For logout I have the following code.Is this right or it is not enough for logout?
Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click
pubvars.Gname = ""
pubvars.Gplev = "0"
login.Show()
Me.Hide()
End Sub
Move the login var assignment logic from Load event to Activated event. The Load event gets executed only once, when you load a Form for the first time.
The Activated event happens every time you display the form .Show(). If you move the code from Load event to Activated, you should fix the issue.
I'm looking for code that will help me check a particular column in MySQL and return its value if it already exists.
I'm working on ForgotPassword module, so when the user clicks "Forgot Password", a form appears that will ask the user to input his/her username. Once he's/she's done, it will check the system to see if the entered username exists.
I found some code here on Stack Overflow:
Private Sub btnCheckUser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheckUser.Click
If IsUserExist(userName:=True) Then
MsgBox("user exists")
Else
MsgBox("user does not exists")
End If
End Sub
Private Function IsUserExist(ByVal userName As String) As Boolean
Dim query As String
Dim returnValue As Boolean = False
query = "SELECT username FROM dbase.tblusers WHERE username = #username "
Using conn As New MySqlConnection("server=localhost; userid=root; password=root; database=dbase")
Using cmd As New MySqlCommand()
With cmd
.Connection = conn
.CommandText = query
.CommandType = CommandType.Text
.Parameters.AddWithValue("#username", txtUsername.Text)
End With
Try
conn.Open()
If CInt(cmd.ExecuteScalar()) > 0 Then
returnValue = True
End If
Catch ex As MySqlException
MsgBox(ex.Message)
returnValue = False
Finally
conn.Close()
End Try
End Using
End Using
Return returnValue
End Function
But this code gives me an error Conversion from string "username" to type 'Integer' is not valid at If CInt(cmd.ExecuteScalar()) > 0 Then.
MySqlCommand.ExecuteScalar returns the first column of the first row returned by your query. This means (for your actual query) a NULL (if the username doesn't exist) or a string with the same username passed as parameter for the where condition. In any case not an integer.
So you just need to check if the object returned is null(Nothing in VB.NET).
Dim result = cmd.ExecuteScalar()
if result IsNot Nothing then
... user exists....
Another approach at your problem could be getting back a COUNT of the number of rows that contains your username
query = "SELECT COUNT(*) FROM dbase.tblusers WHERE username = #username"
and then, the conversion to an integer of the return value of ExecuteScalar, will work
Finally, about the syntax If IsUserExist(userName:=True) Then.
This probably works just because you have the Option Strict configuration of your project set to Off.
With this configuration the boolean value True is automatically converted in the datatype expected by the parameter in IsUserExist. So this function receives the parameter username equals to the literal string "True". Not really useful when you try to search some real username in your table.
It seems that you need to get that value somewhere in your buttonclick code, probably from a TextBox.
Private Sub btnCheckUser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheckUser.Click
Dim userName = txtUsername.Text
If IsUserExist(userName) Then
MsgBox("user exists")
Else
MsgBox("user does not exists")
End If
End Sub
Of course, now you should use the variable userName received in IsUserExist to intialize the parameter
With cmd
.Parameters.AddWithValue("#username", userName)
....
Private Sub btnCheckUser_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheckUser.Click
If IsUserExist(txtUsername.Text) Then #Use value from textbox on your form, use '#' for comments
MsgBox("user exists")
Else
MsgBox("user does not exists")
End If
End Sub
Private Function IsUserExist(ByVal userName As String) As Boolean
Dim query As String
Dim returnValue As Boolean = False
query = "SELECT username FROM dbase.tblusers WHERE username = #username "
Using conn As New MySqlConnection("server=localhost; userid=root; password=root; database=dbase")
Using cmd As New MySqlCommand()
With cmd
.Connection = conn
.CommandText = query
.CommandType = CommandType.Text
.Parameters.AddWithValue("#username", userName) # I think here should user value from function's parameter, not from textbox
End With
Try
conn.Open()
If CInt(cmd.ExecuteScalar()) > 0 Then
returnValue = True
End If
Catch ex As MySqlException
MsgBox(ex.Message)
returnValue = False
Finally
conn.Close()
End Try
End Using
End Using
Return returnValue
End Function
I have checked Google, and the suggested answers here, but have had no luck unfortunately.
The last thing I need to do is have an email read the rateNbr variable into the email body, but it just comes up empty.
I tried to make Public Function FuncRateCheckFile read as Public Function FuncRateCheckFile(ByVal rateNbr As String), to try and enable it to be called outside the function, but this then breaks the function when it is called elsewhere. :(
Here is the code, with comments as to where I am referring:
Public Function FuncRateCheckFile()
Dim blnContinue As Boolean
Dim strLine As String
Dim strSearchFor, strSearchWrd, LineCount, objFSO, objTextFile, arrLines
Dim dteNow As Date
Dim newDate As String
'//==============================================================================================
'// DECLARED
Dim rateNbr As String
'//==============================================================================================
FuncRateCheckFile = False
blnContinue = True
If blnContinue Then
Const ForReading = 1
'Get todays date and reformat it
dteNow = DateValue(Now)
newDate = Format(dteNow, "dd/MM/yy")
strSearchWrd = newDate
'Read the whole file
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile(m_RateCheckFile, ForReading)
LineCount = 0
Do Until objTextFile.AtEndOfStream
strLine = objTextFile.ReadLine()
If InStr(strLine, strSearchWrd) <> 0 Then
arrLines = Split(strLine, vbCrLf)
LineCount = LineCount + 1
End If
Loop
'Log a message to state how many lines have todays day, and if there are none, log an error
If LineCount <> 0 Then
'//==============================================================================================
'// "rateNbr" IS WHAT I AM TRYING TO GET TO PUT IN THE EMAIL
LogMessage "Rate file date is correct"
rateNbr = "Number of rates for " & newDate & " in the file recieved on " & newDate & " is " & LineCount
LogMessage rateNbr
EmailAdvice2
objTextFile.Close
'//==============================================================================================
Else
blnContinue = False
LogError "Failed to retrieve Current Rate date, please check rate file.."
EmailAdvice
objTextFile.Close
End If
End If
FuncRateCheckFile = blnContinue
LogMessage "Completed Check Rate file"
End Function
Private Function EmailAdvice2()
Dim strSMTPFrom As String
Dim strSMTPTo As String
Dim strSMTPRelay As String
Dim strTextBody As String
Dim strSubject As String
Dim oMessage As Object
'//==============================================================================================
'// DECLARED AGAIN
Dim rateNbr As String
'//==============================================================================================
Set oMessage = CreateObject("CDO.Message")
strSMTPFrom = "no-reply#work.com.au"
strSMTPTo = "me#work.com.au"
strSMTPRelay = "smtp.relay.com"
'//==============================================================================================
'// THIS MAKES THE TEXT BODY BLANK, BUT THE EMAIL STILL SENDS
strTextBody = rateNbr
'//==============================================================================================
strSubject = "Todays rates"
'strAttachment = "full UNC path of file"
oMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
oMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strSMTPRelay
oMessage.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
oMessage.Configuration.Fields.Update
oMessage.Subject = strSubject
oMessage.From = strSMTPFrom
oMessage.To = strSMTPTo
oMessage.textbody = strTextBody
'oMessage.AddAttachment strAttachment
oMessage.Send
End Function
I am positive that it is blank because I have declared rateNbr under EmailAdvice2() and then not given it anything to fill the variable with. But I don't know how to make it call the variable under FuncRateCheckFile().
Thanks to all for any assistance.
As Plutonix stated, this is a scope issue.
Move the declaration of your 'rateNbr' variable out to class level, and remove the local declarations inside your functions:
Dim rateNbr As String ' <-- out at class level it will be accessible from both functions
Public Function FuncRateCheckFile()
...
' REMOVE both the decalarations of "rateNbr" that are INSIDE your functions
...
End Function
Private Function EmailAdvice2()
...
' REMOVE both the decalarations of "rateNbr" that are INSIDE your functions
...
End Function