VB.net 'System.Collections.Generic.KeyNotFoundException' exception - mysql

Here is my code:
Imports System.IO
Imports MySql.Data.MySqlClient
Public Class F_login
Dim strServer As String = "localhost"
Dim strDB As String = "lab_utilization"
Dim strUser As String = "root"
Dim strPw As String = ""
Dim cs As String = "Server=$($strServer);Port=3306;Database=$($strDB);Uid=$($strUser);Pwd=$($strPw);"
Dim con As New MySqlConnection(cs)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim id As Integer = uid.Text
Dim pswd As New MySqlCommand("Select Password from authentication where id = " & id & "", con)
pswd.ExecuteNonQuery()
Dim mysqladapter As New MySqlDataAdapter(pswd)
Dim dt As New DataTable
mysqladapter.Fill(dt)
dg.DataSource = dt
Dim psd As String = dg.Rows(0).Cells(0).Value
If pswd1.Text = psd Then
Me.Visible = False
F_Main_screen.Show()
Else
MessageBox.Show("Invalid ID or Password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Sub
Private Sub F_login_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con.ConnectionString = cs
con.Open()
End Sub
End Class
The following exception occurs on con.Open():
An unhandled exception of type System.Collections.Generic.KeyNotFoundException' occurred in MySql.Data.dll
Additional information: Keyword 'address' not found.
Any assistance will be appreciated, thank you.

I don't think your syntax for string interpolation is correct.
Try changing your connection string to:
`Dim cs As String = "Server=${strServer};Port=3306;Database=${strDB};Uid=${strUser};Pwd=${strPw};"

Related

Reference required to assembly 'System.Data.Common', containing the type 'DBConnection'

I'm making a program in VB with MySQL. For some reason, I got an error where all of my references had a yellow triangle, but I have since fixed that by reinstalling them on NuGet. Now I have 39 errors which I didn't have before, and I haven't edited the code since then.
Here are the errors:
errors
That isn't all of the errors, but the rest are a lot of duplicates. Now here's my form1 code.
Imports MaterialSkin
Imports MySql.Data.MySqlClient
Imports System.Net
Imports System.Text
Imports System.Data
Public Class Form1
Private Sub LoginBtn_Click(sender As Object, e As EventArgs) Handles LoginBtn.Click
Dim address As String
address = "http://ipv4bot.whatismyipaddress.com"
Dim client As WebClient = New WebClient()
Dim reply As String = client.DownloadString(address)
Dim connString As String = "Database=aquarius;Data Source=localhost;User Id=root;Password=asd"
Dim conn As New MySqlConnection(connString)
Dim Query As String
Dim Query2 As String
Dim reader As MySqlDataReader
Try
conn.Open()
Query = "SELECT * FROM login WHERE username = ?UserName AND password = ?Password AND buyer = ?Buyer"
Dim cmd As New MySqlCommand(Query, conn)
cmd.Parameters.Add(New MySqlParameter("?UserName", MaterialSingleLineTextField1.Text))
cmd.Parameters.Add(New MySqlParameter("?Password", MaterialSingleLineTextField2.Text))
cmd.Parameters.Add(New MySqlParameter("?Buyer", "true"))
cmd.Connection = conn
reader = cmd.ExecuteReader
If reader.HasRows() Then
conn.Close()
MessageBox.Show("Thanks for buying Aquarius", "Welcome")
conn.Open()
Query2 = "INSERT INTO logs (ip, user, time) VALUES (?Ip, ?User, ?Time)"
Dim cmd2 As New MySqlCommand(Query2, conn)
cmd2.Parameters.Add(New MySqlParameter("?Ip", reply.ToString))
cmd2.Parameters.Add(New MySqlParameter("?User", Environment.UserName))
cmd2.Parameters.Add(New MySqlParameter("?Time", System.DateTime.Now.ToString()))
cmd2.ExecuteNonQuery()
conn.Close()
Form2.Show()
Me.Close()
Else
MessageBox.Show("Your password is incorrect or you are not whitelisted.", "Sad")
End If
Catch ex As Exception
MessageBox.Show(ex.ToString, "Error")
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim SkinManager As MaterialSkinManager = MaterialSkinManager.Instance
SkinManager.AddFormToManage(Me)
SkinManager.Theme = MaterialSkinManager.Themes.DARK
SkinManager.ColorScheme = New ColorScheme(Primary.LightBlue500, Primary.LightBlue600, Primary.LightBlue700, Accent.LightBlue200, TextShade.WHITE)
End Sub
Private Sub MaterialRaisedButton1_Click(sender As Object, e As EventArgs) Handles MaterialRaisedButton1.Click
Dim connString As String = "Database=aquarius;Data Source=localhost;User Id=root;Password=asd"
Dim conn As New MySqlConnection(connString)
Dim Query As String
Try
conn.Open()
Query = "INSERT INTO login (username, password, buyer) VALUES (?UserName, ?Password, ?Buyer)"
Dim cmd As New MySqlCommand(Query, conn)
cmd.Parameters.Add(New MySqlParameter("?UserName", MaterialSingleLineTextField1.Text))
cmd.Parameters.Add(New MySqlParameter("?Password", MaterialSingleLineTextField2.Text))
cmd.Parameters.Add(New MySqlParameter("?Buyer", "false"))
cmd.Connection = conn
cmd.ExecuteNonQuery()
conn.Close()
MessageBox.Show("Done!", ":)")
Catch ex As Exception
MessageBox.Show(ex.ToString, "Error")
End Try
End Sub
End Class

I am always getting fingerprint not verified

Anytime I scan a fingerprint for verification I get the message "Fingerprint not verified" even though I have already enrolled that fingerprint into the database. Here is the code for capture when the form loads
Here is the code for capture when the form loads
Private Sub Me_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Init()
StartCapture()
Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
Dim sql As String
conn.ConnectionString = "**** "
conn.Open()
sql = ("SELECT * FROM new_case_file")
cmd.Connection = conn
cmd.CommandText = sql
Dim rdr As MySqlDataReader = cmd.ExecuteReader()
While (rdr.Read())
Dim MemStream As IO.MemoryStream
Dim fpBytes As Byte()
fpBytes = rdr("FingerPrint")
MemStream = New IO.MemoryStream(fpBytes)
Dim templa8 As DPFP.Template = New DPFP.Template()
templa8.DeSerialize(MemStream)
Dim serializedTemplate As Byte() = MemStream.ToArray
Dim tmpObj As New AppData
Dim FPList As List(Of AppData) = New List(Of AppData)
'tmpObj.No = rdr("No").ToString()
'tmpObj.Template = templa8
'FPList.Add(tmpObj)
End While
conn.Close()
End Sub
Here is the code for verification. When l click on the button it should verify, because l called the sub verifyControl_Commplete in the button click sub.
Private Sub verifyControl_OnComplete(ByVal Control As Object, ByVal FeatureSet As DPFP.FeatureSet, ByRef EventHandlerStatus As
DPFP.Gui.EventHandlerStatus) Handles verifyControl.OnComplete
Dim printFound As Boolean = False
'Dim printFound As Boolean = True
'Dim printFound As Boolean = False
Dim VerifiedFPData = New AppData
Dim FPList As List(Of AppData) = New List(Of AppData)
Try
For Each FPData As AppData In FPList
Dim tmplateData As New DPFP.Template
'tmplateData = FPData.Template
Dim compareTo As New DPFP.FeatureSet
compareTo = FeatureSet
Dim ver As New DPFP.Verification.Verification()
Dim res As New DPFP.Verification.Verification.Result()
If Not tmplateData Is Nothing Then
ver.Verify(FeatureSet, tmplateData, res)
If res.Verified Then
EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Success
printFound = True
VerifiedFPData = FPData
Exit For
End If
End If
Next
Catch ex As Exception
MessageBox.Show("Error")
End Try
If printFound Then
MsgBox("Verified")
Else
EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Failure
MsgBox("Not Verified")
End If
End Sub
Private Sub btnverifyfp_Click(sender As Object, e As EventArgs) Handles btnverifyfp.Click
verifyControl_OnComplete(Nothing, Nothing, Nothing)
End Sub
This is the code l used in saving the fingerprint
Dim fingerprintData As MemoryStream = New MemoryStream
Enroller.Template.Serialize(fingerprintData)
Dim serializedTemplate As Byte() = fingerprintData.ToArray()
Dim bytes() As Byte = serializedTemplate
Try this:
'THIS NEEDS TO BE AT THE CLASS-LEVEL, AS A MEMBER
Private FPList As New List(Of AppData)
Private Sub Me_Load(ByVal sender As System.Object, ByVal e AsSystem.EventArgs)
Handles MyBase.Load
Init()
StartCapture()
Dim sql As String = "SELECT * FROM new_case_file"
Using conn As New MySqlConnection("**** "), _
cmd As New MySqlCommand(sql, conn)
conn.Open()
Using rdr As MySqlDataReader = cmd.ExecuteReader()
FPList.Clear()
While (rdr.Read())
Dim tmpObj As New AppData
tmpObj.No = rdr("No").ToString()
Dim fpBytes As Byte() = rdr("FingerPrint")
Using MemStream As New IO.MemoryStream(fpBytes)
Dim templa8 As New DPFP.Template()
templa8.DeSerialize(MemStream)
End Using
tmpObj.Template = templa8
FPList.Add(tmpObj)
End While
rdr.Close()
End Using
End Using
End Sub
And now other code later can use that same FPList variable. If you find yourself writing New List(Of AppData) anywhere else, you're doing something wrong.
The AppData class should look something like this:
Public Class AppData
Public Property No As String
Public Property Template As DFFP.Template
End Class
And finally, the verify code:
Private Sub verifyControl_OnComplete(ByVal Control As Object, ByVal FeatureSet As DPFP.FeatureSet,
ByRef EventHandlerStatus As DPFP.Gui.EventHandlerStatus)
Handles verifyControl.OnComplete
Try
Dim ver As New DPFP.Verification.Verification()
Dim res As New DPFP.Verification.Verification.Result()
For Each FPData As AppData In FPList
If FPData.Template Is Nothing Then Continue
ver.Verify(FeatureSet, FPData.Template, res)
If res.Verified Then
EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Success
MsgBox("Verified")
Return
End If
Next FPDAta
Catch ex As Exception
MessageBox.Show("Error")
End Try
EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Failure
MsgBox("Not Verified")
End Sub
Again... we don't have access to your API documentation, test data, or equipment. That means we're blind trying to help you here. There's probably some things wrong with this, and you'll have to be able to troubleshoot and debug.

how to avoid error: "CommandText property has not been initialized properly"?

database is in the sqlYog,
when i run this program i am getting the error:
CommandText property has not been initialized properly..?
please help me
Imports MySql.Data.MySqlClient
Imports System.Data
Partial Class login
Inherits System.Web.UI.Page
Public dbconn As New MySqlConnection
Public sql As String
Public dbcomm As New MySqlCommand
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
dbconn = New MySqlConnection("data source= localhost; user id=root; password=search; database=bookstore;")
dbconn.Open()
dbcomm.Connection = dbconn
End Sub
Protected Sub btn_login_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_login.Click
Try
dbcomm = New MySqlCommand(sql, dbconn)
sql = "select * from bookstore.lib_user where username=#username and password=#password"
dbcomm.Parameters.AddWithValue("#username", txt_username.Text)
dbcomm.Parameters.AddWithValue("#password", txt_password.Text)
Dim dbadpt As New MySqlDataAdapter(dbcomm)
Dim dt As New DataTable()
dbadpt.Fill(dt)
If dt.Rows.Count > 0 Then
MsgBox("login is suceesfull")
Else
Literal1.Text = "invalid login"
End If
Catch ex As Exception
MsgBox("read this error: " + ex.Message)
End Try
End Sub
End Class
Please change the sequence of lines.
First set the query text then call the command constructor.
sql = "select * from bookstore.lib_user where username=#username and password=#password"
dbcomm = New MySqlCommand(sql, dbconn)
As per your code sql is empty when assigning to your MySqlCommand, You need to set the sql value first then assign it to your MySqlCommand object .
sql = "select * from bookstore.lib_user where username=#username and password=#password"
dbcomm = New MySqlCommand(sql, dbconn)

MySqlConnection is not defined

Im new in vb.net and mysql.
I got confused when I am defining Dim SQLConnection As MySqlConnection = New MySqlConnection.
And it said that the New "MySqlConnection" is not defined but I made sure that I have imported namespace needed or anything but i still have an error and i cant figure out whats the problem.
This is my code:
Imports MySql.Data.MySqlClient
Public Class EditInfo
Dim bednumber As String = ""
Dim patient_name As String = ""
Dim patient_age As String = ""
Dim date_of_confinement As String = ""
Dim type_of_sickness As String = ""
Dim type_of_IV_fluid As String = ""
Dim number_of_bottles As String = ""
Dim drop_rate As String = ""
Dim ServerString As String = "Server=localhost; database=patientinfo;user id=root;password=root" 'connection to phpmyadmin database
Dim SQLConnection As MySqlConnection = New MySqlConnection
Private Sub PatientInfoBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PatientInfoBindingNavigatorSaveItem.Click
Me.Validate()
Me.PatientInfoBindingSource.EndEdit()
Me.PatientInfoTableAdapter.Update(Me.PatientInfoDBDataSet.PatientInfo)
End Sub
Any help would be appreciated. Thanks! I got confused sorry XD
Try:
Replace
Dim SQLConnection As MySqlConnection = New MySqlConnection
by
Dim SQLConnection As New MySqlConnection()
Other point, you may use String.Empty to set value for String instead of "".
HTH.

Telerik Dock is duplicating boxes and "_breaking_" the webpage, how can I fix the problem?

Here is the Code:
VB:
Imports System.Web.Script.Serialization
Partial Class MyLanding
Inherits System.Web.UI.Page
Private LoginClass As New LoginClass
Private _dockStateCleared As Boolean = False
Private _conn As New SqlConnection(ConfigurationManager.ConnectionStrings("MidwestPartsConnectionString").ConnectionString)
Private ReadOnly Property CurrentDockStates() As List(Of DockState)
Get
'Get saved state string from the database - set it to dockState variable for example
Dim dockStatesFromDB As String = ""
_conn.Open()
Dim command As New SqlCommand("SELECT JavascriptStr FROM SysProperties WHERE (UserID = #UserID)", _conn)
command.Parameters.Add("#UserID", SqlDbType.UniqueIdentifier).Value = Me.LoginClass.ReturnUserID()
Try
dockStatesFromDB = command.ExecuteScalar().ToString()
_conn.Close()
Catch ex As Exception
_conn.Close()
Me.CreateSavedLayout("")
End Try
Dim _currentDockStates As New List(Of DockState)()
Dim stringStates As String() = dockStatesFromDB.Split("|"c)
For Each stringState As String In stringStates
If stringState.Trim() <> String.Empty Then
_currentDockStates.Add(DockState.Deserialize(stringState))
End If
Next
Return _currentDockStates
End Get
End Property
Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
If Not Page.IsPostBack Then
If CurrentDockStates.Count = 0 Then
Me.LoadItems()
End If
End If
End Sub
Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Init
Dim i As Integer = 0
While i < CurrentDockStates.Count
If CurrentDockStates(i).Closed = False Then
Dim dock As RadDock = CreateRadDockFromState(CurrentDockStates(i))
dlColumnOne.Controls.Add(dock)
CreateSaveStateTrigger(dock)
LoadUserControl(dock)
End If
System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
End While
End Sub
Protected Sub dlColumnOne_LoadDockLayout(ByVal sender As Object, ByVal e As DockLayoutEventArgs)
For Each state As DockState In CurrentDockStates
e.Positions(state.UniqueName) = state.DockZoneID
e.Indices(state.UniqueName) = state.Index
Next
End Sub
Protected Sub dlColumnOne_SaveDockLayout(ByVal sender As Object, ByVal e As DockLayoutEventArgs)
Dim stateList As List(Of DockState) = dlColumnOne.GetRegisteredDocksState()
Dim serializedList As New StringBuilder()
Dim i As Integer = 0
While i < stateList.Count
serializedList.Append(stateList(i).ToString())
serializedList.Append("|")
System.Math.Max(System.Threading.Interlocked.Increment(i), i - 1)
End While
Dim dockState As String = serializedList.ToString()
If dockState.Trim() <> [String].Empty Then
_conn.Open()
Dim command As New SqlCommand([String].Format("update sysproperties set javascriptstr = '{0}' Where UserID = #UserID ", dockState), _conn)
command.Parameters.Add("#UserID", SqlDbType.UniqueIdentifier).Value = Me.LoginClass.ReturnUserID()
command.ExecuteNonQuery()
_conn.Close()
End If
End Sub
Private Function CreateRadDockFromState(ByVal state As DockState) As RadDock
Dim dock As New RadDock()
dock.DockMode = DockMode.Docked
dock.UniqueName = state.UniqueName
dock.ID = String.Format("RadDock{0}", dock.UniqueName)
dock.ApplyState(state)
dock.Commands.Add(New DockCloseCommand())
dock.Commands.Add(New DockExpandCollapseCommand())
Return dock
End Function
Private Function CreateRadDock(ByVal DockTitle As String) As RadDock
Dim docksCount As Integer = CurrentDockStates.Count
Dim dock As New RadDock
dock.DockMode = DockMode.Docked
Dim UniqueName As String = Guid.NewGuid().ToString()
UniqueName = UniqueName.Replace("-", "")
dock.UniqueName = UniqueName
dock.ID = String.Format("RadDock{0}", UniqueName)
dock.Title = DockTitle
dock.Width = Unit.Pixel(400)
dock.Commands.Add(New DockCloseCommand())
dock.Commands.Add(New DockExpandCollapseCommand())
Return dock
End Function
Private Sub LoadItems()
Dim DocksDataTable As DataTable = Me.ReturnReports()
For i = 0 To DocksDataTable.Rows.Count() - 1
Dim dock As RadDock = Me.CreateRadDock(DocksDataTable.Rows(i).Item("ReportTitle").ToString())
Dim dz As RadDockZone = Me.dzColumnOne
Dim dl As RadDockLayout = Me.dlColumnOne
dz.Controls.Add(dock)
Me.CreateSaveStateTrigger(dock)
dock.Tag = DocksDataTable.Rows(i).Item("ReportPath")
Me.LoadUserControl(dock)
Next
End Sub
Public Function ReturnReports() As DataTable
Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("MidwestPartsConnectionString").ConnectionString)
Dim Query As String = "SELECT Reports.ReportPath, Reports.ReportTitle, UserReports.UserID FROM UserReports INNER JOIN Reports ON UserReports.ReportID = Reports.ReportID WHERE (UserReports.UserID = #UserID)"
Dim adapter As New SqlDataAdapter
adapter.SelectCommand = New SqlCommand(Query, connection)
adapter.SelectCommand.Parameters.Add("#UserID", SqlDbType.UniqueIdentifier).Value = Me.LoginClass.ReturnUserID()
Dim table1 As New DataTable
connection.Open()
Try
adapter.Fill(table1)
Finally
connection.Close()
End Try
Return table1
End Function
Private Function ReturnLayout() As DataTable
Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("MidwestPartsConnectionString").ConnectionString)
Dim Query As String = "select * from sysproperties"
Dim adapter As New SqlDataAdapter
adapter.SelectCommand = New SqlCommand(Query, connection)
adapter.SelectCommand.Parameters.Add("#UserPropertiesID", SqlDbType.Int).Value = 1
Dim table1 As New DataTable
connection.Open()
Try
adapter.Fill(table1)
Finally
connection.Close()
End Try
Return table1
End Function
Private Sub LoadUserControl(ByVal dock As RadDock)
If String.IsNullOrEmpty(dock.Tag) Then
Return
End If
Dim usercontrol As Control = LoadControl(dock.Tag)
dock.ContentContainer.Controls.Add(usercontrol)
End Sub
Private Sub CreateSaveStateTrigger(ByVal dock As RadDock)
dock.AutoPostBack = True
dock.CommandsAutoPostBack = True
Dim saveStateTrigger As New AsyncPostBackTrigger()
saveStateTrigger.ControlID = dock.ID
saveStateTrigger.EventName = "DockPositionChanged"
UpdatePanel1.Triggers.Add(saveStateTrigger)
saveStateTrigger = New AsyncPostBackTrigger()
saveStateTrigger.ControlID = dock.ID
saveStateTrigger.EventName = "Command"
UpdatePanel1.Triggers.Add(saveStateTrigger)
End Sub
Private Sub CreateSavedLayout(ByVal JavascriptStr As String)
Dim sqlConn As New SqlConnection(ConfigurationManager.ConnectionStrings("MidwestPartsConnectionString").ConnectionString)
Dim strSqlInsert As String = "INSERT INTO SysProperties(UserID, JavascriptStr) VALUES (#UserID, #JavascriptStr)"
strSqlInsert += "; SELECT SCOPE_IDENTITY() ;"
Dim sqlCmd As New SqlCommand(strSqlInsert, sqlConn)
With sqlCmd.Parameters
.Add("#JavascriptStr", SqlDbType.Text).Value = JavascriptStr
.Add("#UserID", SqlDbType.UniqueIdentifier).Value = Me.LoginClass.ReturnUserID()
End With
sqlCmd.Connection.Open()
sqlCmd.ExecuteScalar()
sqlCmd.Connection.Close()
End Sub
Protected Sub btnAddReports_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddReports.Click
Try
Response.Redirect("~/MyUserAccount/SelectedReports.aspx", False)
Catch ex As Exception
End Try
End Sub
End Class
Your could looks fine. Possible reasons for this problem include the following:
Dragging the Dock control very quickly causes an ajax conflict, and an error is shown. To avoid this from happening you could show an AjaxLoading panel during the process of an ajax request (search/ask in the telerik forums for a sample showing how to do this). Additionally you should make sure the UpdatePanels on your site are configured as in the following online demo: http://demos.telerik.com/aspnet-ajax/dock/examples/myportal/defaultcs.aspx.
The error is a result of a ViewState problem. This telerik forum thread provides a possible solution: www.telerik.com/community/forums/aspnet-ajax/docking/failed-to-load-view-state-error-when-moving-dynamically-created-widgets-around-the-raddocklayout.aspx