I have a registration form and I want to encrypt the password using whatever encryption is available, I'm using vb.net 2008 and MySQL as database, I searched through online and found some encrypting code but I have no idea how to connect it to my registration form. here is my registration code and the encryption code i found online (at the top part)
Imports MySql.Data.MySqlClient
Imports System.Security
Imports System.Security.Cryptography
Public Class user
Public Function AES_Encrypt(ByVal input As String, ByVal pass As String) As String
Dim AES As New System.Security.Cryptography.RijndaelManaged
Dim Hash_AES As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim encrypted As String = ""
Try
Dim hash(31) As Byte
Dim temp As Byte() = Hash_AES.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(pass))
Array.Copy(temp, 0, hash, 0, 16)
Array.Copy(temp, 0, hash, 15, 16)
AES.Key = hash
AES.Mode = Security.Cryptography.CipherMode.ECB
Dim DESEncrypter As System.Security.Cryptography.ICryptoTransform = AES.CreateEncryptor
Dim Buffer As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(input)
encrypted = Convert.ToBase64String(DESEncrypter.TransformFinalBlock(Buffer, 0, Buffer.Length))
Return encrypted
Catch ex As Exception
End Try
End Function
Private Sub BCreateAcount_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BCreateAcount.Click
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString = "server = localhost;username= root;password= a;database= database"
Try
conn.Open()
Catch mali As MySqlException
MsgBox("connot establish connection")
End Try
Dim myCommand As New MySqlCommand
Dim myReader As MySqlDataReader
myCommand.Connection = conn
myCommand.CommandText = "insert into user values('" + txtUserName.Text + "','" + txtNewPassword.Text + "')"
Call calldaw()
If txtUserName.Text = "" Or txtNewPassword.Text = "" Or txtConfirmPassword.Text = "" Then
MsgBox("Please enter username and password", MsgBoxStyle.Information, "Inventory System")
ElseIf txtConfirmPassword.Text = txtNewPassword.Text Then
MsgBox("Account Created", MsgBoxStyle.Information, "Inventory System")
myReader = myCommand.ExecuteReader()
txtUserName.Text = ""
txtNewPassword.Text = ""
txtConfirmPassword.Text = ""
Else
MsgBox("Password did not match", MsgBoxStyle.Critical, "Inventory System")
txtConfirmPassword.Text = ""
txtNewPassword.Text = ""
txtUserName.Text = ""
End If
End Sub
Private Sub calldaw()
Dim conn As MySqlConnection
conn = New MySqlConnection
conn.ConnectionString = "server = localhost;username= root;password= a;database= database"
Try
conn.Open()
Catch mali As MySqlException
MsgBox("connot establish connection")
End Try
Dim myData As MySqlDataAdapter
Dim reason As String = " Create Account "
Dim tao As String = "admin"
myData = New MySqlDataAdapter
Dim sqlsql = "insert into daily_log values('" + tao + "','" + Date1.Text + "','" + reason + "','" + Time1.Text + "')"
Dim ssql = "Select * from user"
Dim myCommand As New MySqlCommand
myCommand.Connection = conn
myCommand.CommandText = sqlsql
Dim myReader As MySqlDataReader
myReader = myCommand.ExecuteReader
End Sub
Private Sub BBack_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BBack.Click
Me.Close()
End Sub
Private Sub user_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Date1.Text = Date.Today.Date
Dim Date2 As Date = Date1.Text
Date1.Text = Format(Date2, "yyyy-MM-dd")
Time1.Text = TimeOfDay
End Sub
End Class
any help will do, thanks.
You have to call the AES_Encrypt function before executing the INSERT statement in order to pass the encrypted password to database.
Dim myCommand As New MySqlCommand
Dim myReader As MySqlDataReader
myCommand.Connection = conn
myCommand.CommandText = "insert into user values('" + txtUserName.Text + "','" + AES_Encrypt(txtNewPassword.Text,txtNewPassword.Text) + "')"
Call calldaw()
Related
This is my code for read data from EXCEL file using ODBC driver and write in MySql Database.
Public Class WebForm3
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim MySqlCmd = New SqlCommand()
' Dim dialog As New System.Windows.Forms.OpenFileDialog()
'Dim dialog As New OpenFileDialog()
'dialog.Filter = "Excel files |*.xls;*.xlsx"
'dialog.InitialDirectory = "C:\"
'dialog.Title = "Select file for import"
'If dialog.ShowDialog() = DialogResult.OK Then
Try
Dim dt As DataTable
Dim buff0 As String
Dim buff1 As String
Dim buff2 As String
dt = ImportExceltoDatatable("C:\\Book1.xls")
For i = 0 To dt.Rows.Count - 1
buff0 = dt.Rows(i)(0)
buff1 = dt.Rows(i)(1)
buff2 = dt.Rows(i)(2)
Dim connStr As String = "server=localhost;user=root;database=ajaxsamples;port=3306;password=innoera;"
Dim connMysql As MySqlConnection = New MySqlConnection(connStr)
Dim sql As String = "INSERT INTO ajaxsamples.customers VALUES('" & buff0 & "','" & buff1 & "','" & buff2 & "')"
Dim cmd As MySqlCommand = New MySqlCommand(sql, connMysql)
cmd.ExecuteNonQuery()
cmd.Dispose()
connMysql.Close()
Next
Catch ex As Exception
MsgBox(Err.Description, MsgBoxStyle.Critical)
End Try
'End If
End Sub
Public Shared Function ImportExceltoDatatable(filepath As String) As DataTable
' string sqlquery= "Select * From [SheetName$] Where YourCondition";
Dim dt As New DataTable
Try
Dim ds As New DataSet()
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & filepath & ";Extended Properties=""Excel 12.0;HDR=YES;"""
Dim con As New OleDbConnection(constring & "")
con.Open()
Dim myTableName = con.GetSchema("Tables").Rows(0)("TABLE_NAME")
Dim sqlquery As String = String.Format("SELECT * FROM [{0}]", myTableName)
'Dim myTableName = con.GetSchema("Tables").Rows(0)("TABLE_NAME")
'Dim sqlquery As String = String.Format("SELECT * FROM Sheet1$") ' "Select * From " & myTableName
Dim da As New OleDbDataAdapter(sqlquery, con)
da.Fill(ds)
dt = ds.Tables(0)
Return dt
Catch ex As Exception
MsgBox(Err.Description, MsgBoxStyle.Critical)
Return dt
End Try
End Function
End Class
I got this error,
"Connection must be valid and open "
whats wrong in code? I am newbie for VB. Any help would be appreciated.
You forgot to open your connection.
Try
connMysql = New MySqlConnection
connMysql.ConnectionString = connStr
connMysql.Open() 'You forgot to open your connection
sql = "SELECT * FROM users"
cmd = New MySqlCommand(sql, connMysql)
cmd.ExecuteNonQuery()
cmd.Dispose()
Catch ex As Exception
'your error code here
Finally
connMysql.Close() 'close your connection
End Try
I have a form in which data gets insert. There are some checkboxlist. CheckboxList binds with table in db. Now after selecting items it should enter selected values in db table but it inserts empty strings.
I have two checkboxlist (products, payment) Payment works fine. problem is in products.
VB code
Private Sub list_business_hospital_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.PopulateProducts()
Me.PopulatePayments()
End Sub
Private Sub PopulateProducts()
productsList.Items.Clear()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "select * from chemistsProducts"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("productName").ToString()
item.Value = sdr("productName").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
productsList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
productsList.Items.Insert(0, New ListItem("All", "All"))
End Sub
Private Sub PopulatePayments()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "select * from payment"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("paymentName").ToString()
item.Value = sdr("paymentID").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
ListPayment.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
ListPayment.Items.Insert(0, New ListItem("All", "All"))
End Sub
Private Sub save_Click(sender As Object, e As EventArgs) Handles save.Click
Dim selectedProducts As String = String.Empty
For Each chk As ListItem In productsList.Items
If chk.Selected = True Then
selectedProducts &= "<li>" + chk.Text + "</li>"
End If
Next
Dim payments As String = String.Empty
For Each chk As ListItem In ListPayment.Items
If chk.Selected = True Then
payments &= "<li>" + chk.Text + "</li>"
End If
Next
Try
Dim str1 As String = "INSERT INTO chemists (`products`, `payment`) values ('" + selectedProducts + "', '" + payments + "')"
Dim str2 As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
con.Open()
str2 = command.ExecuteReader
con.Close()
Response.Redirect("business-added.aspx")
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Here Payment gets inserted what I have selected. Problem is in selectedProducts
Try below in page load,
If Not IsPostBack Then
Me.PopulateProducts()
Me.PopulatePayments()
End If
I'm almost done with a trial program where I add, edit and delete stuff from my MySQL database.
But I can't seem to make the delete button to work.
Here's my code for the Delete Button:
If IDNo = Nothing Then
MsgBox("Please choose an item to delete.", MsgBoxStyle.Exclamation)
Else
Dim sqlQuery As String = "DELETE FROM tbl_adbms_test WHERE IDNo='" & IDNo & "'"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("Successfully deleted an item.", MsgBoxStyle.Information)
Me.LoadPeople()
End If
The ERROR
http://stivigan.us.to/images/delete_error.jpg
And here's the rest of my Main Form.
Imports MySql.Data.MySqlClient
Public Class frm_main
Public sConnection As New MySqlConnection
Public IDNo As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD = loadedro; DATABASE = adbms_test_db"
End If
LoadPeople()
End Sub
Public Sub LoadPeople()
Dim sqlQuery As String = "SELECT * FROM tbl_adbms_test"
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim TABLE As New DataTable
Dim i As Integer
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(TABLE)
End With
list_view_people.Items.Clear()
For i = 0 To TABLE.Rows.Count - 1
With list_view_people
.Items.Add(TABLE.Rows(i)("IDNo"))
With .Items(.Items.Count - 1).SubItems
.Add(TABLE.Rows(i)("LastName"))
.Add(TABLE.Rows(i)("FirstName"))
End With
End With
Next
End Sub
Private Sub btn_save_Click(sender As Object, e As EventArgs) Handles btn_add.Click
frm_add.ShowDialog()
End Sub
Private Sub btn_modify_Click(sender As Object, e As EventArgs) Handles btn_modify.Click
If IDNo = Nothing Then
MsgBox("Please choose a record to modify.", MsgBoxStyle.Exclamation)
Else
Dim sqlQuery As String = "SELECT LastName, FirstName FROM tbl_adbms_test WHERE IDNo='" & list_view_people.SelectedItems(0).Text & "'"
Dim sqlAdapter As New MySqlDataAdapter
Dim sqlCommand As New MySqlCommand
Dim sqlTable As New DataTable
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
End With
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(sqlTable)
End With
frm_modify.IDNo = list_view_people.SelectedItems(0).Text
frm_modify.LastName = sqlTable.Rows(0)("LastName")
frm_modify.FirstName = sqlTable.Rows(0)("FirstName")
frm_modify.ShowDialog()
End If
End Sub
Private Sub list_view_people_MouseClick(sender As Object, e As MouseEventArgs) Handles list_view_people.MouseClick
IDNo = list_view_people.SelectedItems(0).Text
End Sub
Private Sub btn_delete_Click(sender As Object, e As EventArgs) Handles btn_delete.Click
If IDNo = Nothing Then
MsgBox("Please choose an item to delete.", MsgBoxStyle.Exclamation)
Else
Dim sqlQuery As String = "DELETE FROM tbl_adbms_test WHERE IDNo='" & IDNo & "'"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("Successfully deleted an item.", MsgBoxStyle.Information)
Me.LoadPeople()
End If
End Sub
End Class
Add Form
Public Class frm_add
Public sConnection As New MySqlConnection
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD = loadedro; DATABASE = adbms_test_db"
End If
End Sub
Private Sub btn_save_Click(sender As Object, e As EventArgs) Handles btn_save.Click
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD = loadedro; DATABASE = adbms_test_db"
sConnection.Open()
End If
Dim sqlQuery As String = "INSERT INTO tbl_adbms_test(IDNo,LastName,FirstName) VALUES(NULL,'" & txt_last_name.Text & "','" & txt_first_name.Text & "')"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("The data was saved.", MsgBoxStyle.Information)
Dispose()
Close()
frm_main.LoadPeople()
End Sub
End Class
Edit Form
Imports MySql.Data.MySqlClient
Public Class frm_modify
Friend IDNo As Integer
Friend LastName As String
Friend FirstName As String
Public sConnection As New MySqlConnection
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
txt_last_name.Text = LastName
txt_first_name.Text = FirstName
End Sub
Private Sub btn_update_Click(sender As Object, e As EventArgs) Handles btn_update.Click
If sConnection.State = ConnectionState.Closed Then
sConnection.ConnectionString = "SERVER = localhost; USERID = root; PASSWORD = loadedro; DATABASE = adbms_test_db"
sConnection.Open()
End If
Dim sqlQuery As String = "UPDATE tbl_adbms_test SET LastName='" & txt_last_name.Text & "', FirstName='" & txt_first_name.Text & "' WHERE IDNo='" & IDNo & "'"
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.ExecuteNonQuery()
End With
MsgBox("Record updated successfully.", MsgBoxStyle.Information)
Dispose()
Close()
frm_main.LoadPeople()
End Sub
End Class
Thanks in advance. :)
You don't have the connection open before executing the Delete command.
This is a common scenario when you keep a global connection object around in your code.
You gain nothing and there are always situations in which you end with the connection in a wrong state
You could write
Dim sqlQuery As String = "DELETE FROM tbl_adbms_test WHERE IDNo=#id"
if sConnection.ConnectionState = ConnectionState.Closed Then
sConnection.Open
End If
Dim sqlCommand As New MySqlCommand
With sqlCommand
.CommandText = sqlQuery
.Connection = sConnection
.Parameters.AddWithValue("#id", IDNo)
.ExecuteNonQuery()
End With
but I really suggest to remove your usage of the global connection object and replace it with a local MySqlConnection that will be created just when you use it and closed/destroyed after the usage. This is the intended usage of the Using Statement
Dim sqlQuery As String = "DELETE FROM tbl_adbms_test WHERE IDNo=#id"
Using con = new MySqlConnection(connstring)
Using cmd = new MySqlCommand(sqlQuery, con)
con.Open
With cmd
.Parameters.AddWithValue("#id", IDNo)
.ExecuteNonQuery()
End With
End Using
End Using
Notice also that I have removed the string concatenation in your sqlQuery and used a safer parameterized approach (albeit in this scenario and if the ListView is not editable there are no real risk of sql injection)
I'm working on simple project to figure out how databases work.
I created mysql base on my host and used this code to connect to it
Private mysql_host = "myhost"
Private mysql_user = "myuser"
Private mysql_pass = "mypw"
Private mysql_db = "mydb"
Private SQLConnect As String = "Server=" + mysql_host + ";" + "User Id=" + mysql_user + ";" + "Password=" + mysql_pass + ";" + "Database=" + mysql_db
Private SQLConnection As New MySqlConnection
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
sqlConnection.ConnectionString = SQLConnect
Try
If sqlConnection.State = ConnectionState.Closed Then
sqlConnection.Open()
MsgBox("Connected")
Else
sqlConnection.Close()
MsgBox("Not Connected")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
After that i used this code to add record into database.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim SQLStatement As String = "INSERT into tCodes(Code) VALUES ('" & TextBox1.Text & "')"
Dim cmd As New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
MsgBox("Added")
End Sub
On the other form i want to check if record exist in database. How to do that .
I tried with code
Dim SQLStatement As String = "SELECT * From tCodes WHERE Code '" & TextBox1.Text & "'")
For read . Me using this
Private host As String = "host" 'Host DB
Private user As String = "user" 'User DB
Private pass As String = "pass" 'Pass DB
Private base As String = "base" 'Base
Private conn As String = "Database=" & base & ";Data Source=" & host & ";User Id=" & _
user & ";Password=" & pass 'Connection
Private Connection As New MySqlConnection(conn) 'Connection
Private readData As MySqlDataReader 'Data Reader
Private adaptsData As New MySqlDataAdapter 'Data Adapter
Private command As New MySqlCommand 'command
Private ds As New DataSet 'DataSet
After
Public Function __select(Optinal table as String = "tCodes") As String
Try
Connection.Open()
Dim query As String = "SELECT * FROM " & table
command.CommandText = query
command.Connection = conexiune
adaptsData.SelectCommand = comanda
adaptsData.Fill(ds, tabla)
Dim newvalue As String = ds.Tables(tabla).Rows(0).Item(item)
ds.Dispose()
ds.Clear()
Connection.Close()
Return newvalue
Catch ex As Exception
ds.Dispose()
ds.Clear()
conexiune.Close()
msgbox(ex.message)
End Try
End Function
Dim conn As MySqlConnection
Dim sqlquery = "SELECT * FROM tCodes WHERE Code = '" + txtCode.Text + "'"
Dim myCommand As New MySqlCommand()
myCommand.Connection = conn
myCommand.CommandText = sqlquery
'start query
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader()
'see if user exists
If myData.HasRows = 0 Then
MsgBox("Kod je nevazeci")
conn.Close()
Else
MsgBox("Kod je vazeci")
End If
That was the solution of this problem
This code is now working. i want to save an image in database please help me how i can work on this
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
OpenFileDialog1.ShowDialog()
TextBox1.Text = OpenFileDialog1.FileName
CaptionTextBox.Text = OpenFileDialog1.SafeFileName
' ImagePictureBox.Image = image.FromFile(TextBox1.Text)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
updateRecord("insert into uploadimages(caption,image) values('" + CaptionTextBox.Text + "', '#ImagePictureBox' )")
End Sub
Imports MySql.Data.MySqlClient
Imports System.Drawing.Imaging
Dim cn As New MySqlConnection
Dim con As New MySqlConnection
Dim cmd As New MySqlCommand
Dim dr As MySqlDataReader
Dim da As MySqlDataAdapter
Dim dt As New DataTable
Dim abc As String
private sub from1()
cn.ConnectionString = "Server=localhost; user id=root; password=; database = school"
cmd.Connection = cn
cn.Open()
end sub
Private Sub images()
Dim arrImage() As Byte
Dim strImage As String
Dim myMs As New IO.MemoryStream
If Not IsNothing(Me.PictureBox5.Image) Then
Me.PictureBox5.Image.Save(myMs, Me.PictureBox5.Image.RawFormat)
arrImage = myMs.GetBuffer
strImage = "1000"
Else
arrImage = Nothing
strImage = "NULL"
End If
cmd.CommandText = "INSERT INTO admision(name, photo) VALUES('" & Me.TextBox1.Text & "'," & _
strImage & ")"
If strImage = "1000" Then
cmd.Parameters.Add(strImage, MySqlDbType.Blob).Value = arrImage
End If
MsgBox("Data save successfully!")
clear()
cmd.ExecuteNonQuery()
cn.Close()
End Sub