ชุมชนคนรักภาษาเบสิค - Visual Basic Community

 ลืมรหัสผ่าน
 ลงทะเบียน
ค้นหา
ดู: 189|ตอบกลับ: 0

[VB.NET] โปรแกรมการจัดเก็บข้อมูลรหัสผ่าน CRUD Full Version

[คัดลอกลิงก์]

319

กระทู้

511

โพสต์

6436

เครดิต

ผู้ดูแลระบบ

ทองก้อน ทับทิมกรอบ

Rank: 9Rank: 9Rank: 9

เครดิต
6436





โค้ดชุดนี้ก็ต่อมาจากในตอนที่แล้ว โค้ดการเก็บข้อมูลรหัสผ่านด้วยการเข้ารหัสแบบ Long Binary (CRUD) โดยใช้ไฟล์ฐานข้อมูล MS Access ในการจัดเก็บข้อมูล ... หากไม่นับโค้ดใน การเข้ารหัส/ถอดรหัสด้วย Rijndael (AES) Algorithm มันเป็นการเขียนโปรแกรมแบบ CRUD (Create / Read / Update / Delete) ขั้นพื้นฐานสำหรับ Windows Form ในสายภาษา VB.NET หรือ C# เพราะเป็นการติดต่อกับตารางข้อมูล (Table) เดี่ยวๆ โดยไม่มีการเชื่อมความสัมพันธ์ใดๆกันระหว่างตาราง ...

สำหรับ Full Version นี้ แอดมินเพิ่มเติมความปลอดภัยในการใช้โปรแกรมเพิ่มเข้ามา คือจะต้องใส่รหัสผ่านก่อน (ค่า Default คือ admin) และสามารถแก้ไขรหัสผ่านได้ด้วย ...

มาดูโค้ดต้นฉบับกันเถอะ ฟอร์มหลัก (frmPassCodeFull.vb)
  1. Imports System.Data.OleDb
  2. Imports MaterialSkin

  3. Public Class frmPassCodeFull
  4.     '// Add new or Edit data.
  5.     Dim blnNewData As Boolean = False   '// Edit mode.
  6.     Dim PK As Long  '// เก็บค่า Primary Key ทั้งการเพิ่มและแก้ไขข้อมูล

  7.     ' / ------------------------------------------------------------------------------------------------
  8.     ' / S T A R T ... H E R E
  9.     ' / ------------------------------------------------------------------------------------------------
  10.     Private Sub frmPassCodeFull_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  11.         '// Login เข้าสู่ระบบก่อน
  12.         Call frmLogin.ShowDialog()
  13.         '// blnLogin ถูกประกาศไว้ใน modDataBase.vb
  14.         If Not blnLogin Then Me.Close()

  15.         '// Initialize MaterialSkin .Net Framework 4.0
  16.         Dim SkinManager As MaterialSkinManager = MaterialSkinManager.Instance
  17.         SkinManager.AddFormToManage(Me)
  18.         SkinManager.Theme = MaterialSkinManager.Themes.LIGHT
  19.         '//SkinManager.ColorScheme = New MaterialSkin.ColorScheme(Primary.Amber500, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE)
  20.         'SkinManager.ColorScheme = New MaterialSkin.ColorScheme(Primary.Green600, Primary.Green700, Primary.Green200, Accent.Red100, TextShade.WHITE)
  21.         '//
  22.         With cmbColorTheme
  23.             .Items.Add("Default")
  24.             .Items.Add("Orange")
  25.             .Items.Add("Green")
  26.             .Items.Add("Light Blue")
  27.             .Items.Add("Cyan")
  28.             .Items.Add("Gray")
  29.         End With
  30.         cmbColorTheme.SelectedIndex = 2

  31.         '// ตั้งค่าขนาดของฟอร์มแบบ Run Time
  32.         Me.Size = New Size(1020, 720)
  33.         '// คำนวณตำแหน่งที่กึ่งกลางของหน้าจอ
  34.         Me.Location = New Point((Screen.PrimaryScreen.WorkingArea.Width - Me.Width) \ 2,
  35.         (Screen.PrimaryScreen.WorkingArea.Height - Me.Height) \ 2)

  36.         '// โหลดข้อมูลลงตารางกริด
  37.         dgvData.DataSource = RetrieveData()
  38.         Call SetupDataGridView(dgvData)
  39.         lblRecordCount.Text = "[Total: " & dgvData.Rows.Count & " Record.]"
  40.         '// เริ่มโหมดว่างเปล่าเพื่อทำรายการใหม่ หรือเลือกรายการขึ้นมาแก้ไข
  41.         Call NewMode()
  42.     End Sub

  43.     ' / ------------------------------------------------------------------------------------------------
  44.     ' / Add New Mode
  45.     ' / ------------------------------------------------------------------------------------------------
  46.     Private Sub NewMode()
  47.         '// Clear all TextBox.
  48.         For Each c In GroupBox1.Controls
  49.             If TypeOf c Is TextBox Then
  50.                 DirectCast(c, TextBox).Clear()
  51.                 DirectCast(c, TextBox).Enabled = False
  52.             End If
  53.             If TypeOf c Is DateTimePicker Then DirectCast(c, DateTimePicker).Enabled = False
  54.         Next
  55.         itemAdd.Enabled = True
  56.         itemSave.Enabled = False
  57.         itemDelete.Enabled = True
  58.         itemDelete.Text = "DELETE DATA"
  59.     End Sub

  60.     ' / ------------------------------------------------------------------------------------------------
  61.     ' / Edit Data Mode
  62.     ' / ------------------------------------------------------------------------------------------------
  63.     Private Sub EditMode()
  64.         '// Clear all TextBox
  65.         For Each c In GroupBox1.Controls
  66.             If TypeOf c Is TextBox Then
  67.                 DirectCast(c, TextBox).Enabled = True
  68.             End If
  69.             If TypeOf c Is DateTimePicker Then DirectCast(c, DateTimePicker).Enabled = True
  70.         Next
  71.         itemAdd.Enabled = False
  72.         itemSave.Enabled = True
  73.         itemDelete.Enabled = True
  74.         itemDelete.Text = "CANCEL"
  75.     End Sub

  76.     ' / ------------------------------------------------------------------------------------------------
  77.     ' / Add new data.
  78.     ' / ------------------------------------------------------------------------------------------------
  79.     Private Sub itemAdd_Click(sender As System.Object, e As System.EventArgs) Handles itemAdd.Click
  80.         blnNewData = True
  81.         Call EditMode()
  82.         txtUrl.Focus()
  83.     End Sub

  84.     ' / ------------------------------------------------------------------------------------------------
  85.     ' / Save Data.
  86.     ' / ------------------------------------------------------------------------------------------------
  87.     Private Sub itemSave_Click(sender As System.Object, e As System.EventArgs) Handles itemSave.Click
  88.         If txtUrl.Text = "" Or txtUrl.Text.Trim.Length = 0 Then
  89.             MessageBox.Show("Please enter Url or Name.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  90.             txtUrl.Focus()
  91.             Return
  92.         End If
  93.         If txtLogin.Text = "" Or txtLogin.Text.Trim.Length = 0 Then
  94.             MessageBox.Show("Please enter Login Name.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  95.             txtLogin.Focus()
  96.             Return
  97.         End If
  98.         If txtPassword.Text = "" Or txtPassword.Text.Trim.Length = 0 Then
  99.             MessageBox.Show("Please enter Password.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  100.             txtPassword.Focus()
  101.             Return
  102.         End If
  103.         '// Details Class in modDataBase.vb
  104.         '// กำหนดค่าให้กับตัวแปร เพื่อส่งออกไปทำการบันทึกข้อมูล
  105.         Dim result As New Details
  106.         With result
  107.             .PK = PK
  108.             .Login = txtLogin.Text
  109.             .Encrypted = txtPassword.Text
  110.             .Url = txtUrl.Text
  111.             .Email = txtEmail.Text
  112.             .Phone = txtPhone.Text
  113.             .DateModified = dtpDateModified.Value
  114.         End With
  115.         '// blnNewData = True คือการเพิ่มข้อมูล
  116.         If blnNewData Then
  117.             '// หาค่า Primary Key จาก SetupNewPK อยู่ใน modDataBase.vb
  118.             result.PK = SetupNewPK("SELECT MAX(UserData.PK) AS MaxPK FROM UserData")
  119.             '// ส่งค่า blnNewData = True บอกว่าเป็นการเพิ่มข้อมูลใหม่ และค่าของ Control บนฟอร์มไปด้วย
  120.             Call SaveData(blnNewData, result)
  121.             Call NewMode()

  122.             '// การแก้ไขข้อมูล
  123.         Else
  124.             'blnNewData = False
  125.             '// ส่งค่า blnNewData = False บอกว่าเป็นการแก้ไขข้อมูล และส่งค่าของ Control บนฟอร์มไปด้วย
  126.             Call SaveData(blnNewData, result)
  127.             Call NewMode()
  128.         End If
  129.         '// Refresh data.
  130.         Call btnRefresh_Click(sender, e)
  131.     End Sub

  132.     ' / ------------------------------------------------------------------------------------------------
  133.     ' / DELETE DATA
  134.     ' / ------------------------------------------------------------------------------------------------
  135.     Private Sub itemDelete_Click(sender As System.Object, e As System.EventArgs) Handles itemDelete.Click
  136.         If itemDelete.Text = "DELETE DATA" Then
  137.             '// เช็คก่อนว่ามีรายแถวอยู่หรือไม่ หรือมีการคลิ๊กเลือกแถวรายการหรือเปล่า
  138.             If dgvData.RowCount = 0 Or dgvData.CurrentRow Is Nothing Then Exit Sub
  139.             Dim Url As String = dgvData.Item(1, dgvData.CurrentRow.Index).Value
  140.             '// ถามยืนยันการลบข้อมูล
  141.             Dim Result As Byte = MessageBox.Show("Are you sure you want to delete the data?" & vbCrLf & "URL/Name: " & Url, "Confirm Deletion", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
  142.             If Result = DialogResult.Yes Then
  143.                 '// Receive Primary Key value to confirm the deletion.
  144.                 PK = dgvData.Item(0, dgvData.CurrentRow.Index).Value
  145.                 '// ลบข้อมูล (modDataBase.vb)
  146.                 Call DeleteData(PK)
  147.                 '// ทำการแสดงผลรายการใหม่
  148.                 Call btnRefresh_Click(sender, e)
  149.                 Call NewMode()
  150.             End If
  151.         ElseIf itemDelete.Text = "CANCEL" Then
  152.             '// เริ่มโหมดว่างเปล่าเพื่อทำรายการใหม่ หรือเลือกรายการขึ้นมาแก้ไข
  153.             Call NewMode()
  154.         End If
  155.     End Sub

  156.     ' / ------------------------------------------------------------------------------------------------
  157.     ' / แสดงผลข้อมูลทั้งหมด
  158.     ' / ------------------------------------------------------------------------------------------------
  159.     Private Sub btnRefresh_Click(sender As System.Object, e As System.EventArgs) Handles btnRefresh.Click
  160.         dgvData.DataSource = RetrieveData()
  161.         lblRecordCount.Text = "[Total: " & dgvData.Rows.Count & " Record.]"
  162.     End Sub

  163.     ' / ------------------------------------------------------------------------------------------------
  164.     ' / การค้นหาข้อมูล
  165.     ' / ------------------------------------------------------------------------------------------------
  166.     Private Sub txtSearch_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtSearch.KeyPress
  167.         '// Undesirable characters for the database ex.  ', * or %
  168.         txtSearch.Text = txtSearch.Text.Replace("'", "").Replace("*", "").Replace("%", "")
  169.         If Trim(txtSearch.Text) = "" Or Len(Trim(txtSearch.Text)) = 0 Then Exit Sub
  170.         '// RetrieveData(True) It means searching for information.
  171.         If e.KeyChar = Chr(13) Then '// Press Enter
  172.             '// No beep.
  173.             e.Handled = True
  174.             '//
  175.             dgvData.DataSource = RetrieveData(True, txtSearch.Text)
  176.             lblRecordCount.Text = "[Total: " & dgvData.Rows.Count & " Record.]"
  177.             txtSearch.Clear()
  178.         End If
  179.     End Sub

  180.     ' / ------------------------------------------------------------------------------------------------
  181.     ' / ดับเบิ้ลคิ๊กเมาส์ในตารางกริด จากนั้นค้นหา Primary Key เพื่อนำข้อมูลไปแสดงผล
  182.     ' / ------------------------------------------------------------------------------------------------
  183.     Private Sub dgvData_CellDoubleClick(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvData.CellDoubleClick
  184.         If e.RowIndex >= 0 Then
  185.             '// เก็บค่านี้เอาไว้เพื่อใช้ในการอ้างอิงตอนที่ทำการอัพเดตข้อมูล
  186.             PK = CInt(dgvData.Rows(e.RowIndex).Cells("PK").Value)
  187.             blnNewData = False    '// กำหนดให้เป็นการแก้ไขข้อมูล
  188.             '// ส่งค่า PK เพื่อเป็นคีย์ไปทำการค้นข้อมูล แล้วคืนข้อมูลกลับมาในรูปแบบ Class
  189.             '// Class Details อยู่ใน modDataBase.vb
  190.             Dim result As Details = RetrieveDetails(PK)
  191.             txtLogin.Text = result.Login
  192.             txtPassword.Text = result.Encrypted
  193.             txtUrl.Text = result.Url
  194.             txtEmail.Text = result.Email
  195.             txtPhone.Text = result.Phone
  196.             dtpDateModified.Text = Format(result.DateModified, "dd/MM/yyyy")
  197.             '// โหมดในการแก้ไข
  198.             Call EditMode()
  199.             txtUrl.Focus()
  200.         End If
  201.     End Sub

  202.     '// เปลี่ยนรหัสผ่าน
  203.     Private Sub btnChangePassword_Click(sender As System.Object, e As System.EventArgs) Handles btnChangePassword.Click
  204.         blnChangePassword = True
  205.         frmLogin.ShowDialog()
  206.     End Sub

  207.     '// Function to handle the KeyPress event for TextBox controls.
  208.     Private Sub TextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtLogin.KeyPress, txtPassword.KeyPress, txtUrl.KeyPress, txtEmail.KeyPress, txtPhone.KeyPress
  209.         If e.KeyChar = ChrW(Keys.Enter) Then
  210.             e.Handled = True '// Prevent the Enter key from adding a new line in the TextBox.
  211.             SendKeys.Send("{TAB}") '// Send the TAB key to move to the next control.
  212.         End If
  213.     End Sub

  214.     Private Sub dtpDateModified_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles dtpDateModified.KeyDown
  215.         If e.KeyCode = Keys.Enter Then
  216.             e.Handled = True
  217.             SendKeys.Send("{TAB}")
  218.         End If
  219.     End Sub

  220.     '// Select Color Theme
  221.     Private Sub cmbColorTheme_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbColorTheme.SelectedIndexChanged
  222.         Select Case cmbColorTheme.SelectedIndex
  223.             Case 0
  224.                 SkinManager.ColorScheme = New MaterialSkin.ColorScheme(Primary.BlueGrey800, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE)
  225.             Case 1
  226.                 SkinManager.ColorScheme = New MaterialSkin.ColorScheme(Primary.Amber500, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE)
  227.             Case 2
  228.                 SkinManager.ColorScheme = New MaterialSkin.ColorScheme(Primary.Green600, Primary.Green700, Primary.Green200, Accent.Red100, TextShade.WHITE)
  229.             Case 3
  230.                 SkinManager.ColorScheme = New MaterialSkin.ColorScheme(Primary.LightBlue600, Primary.LightBlue700, Primary.Green200, Accent.LightGreen700, TextShade.WHITE)
  231.             Case 4
  232.                 SkinManager.ColorScheme = New MaterialSkin.ColorScheme(Primary.Cyan500, Primary.Cyan700, Primary.Cyan100, Accent.Blue100, TextShade.WHITE)
  233.             Case 5
  234.                 SkinManager.ColorScheme = New MaterialSkin.ColorScheme(Primary.Grey600, Primary.Grey700, Primary.Grey100, Accent.LightGreen200, TextShade.WHITE)
  235.         End Select
  236.     End Sub

  237.     Private Sub frmPassCodeFull_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  238.         Me.Dispose()
  239.         GC.SuppressFinalize(Me)
  240.         End
  241.     End Sub

  242.     Private Sub itemExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
  243.         Me.Close()
  244.     End Sub

  245. End Class
คัดลอกไปที่คลิปบอร์ด


โค้ดในการป้อนรหัสผ่านก่อนเข้าใช้โปรแกรม (frmLogin.vb)
  1. Imports MaterialSkin

  2. Public Class frmLogin

  3.     ' / ------------------------------------------------------------------------------------------------
  4.     ' / S T A R T ... H E R E
  5.     ' / ------------------------------------------------------------------------------------------------
  6.     Private Sub frmLogin_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  7.         '// รหัสผ่านเริ่มต้น
  8.         'txtPassword.Text = "admin"
  9.         chkShowPass.Checked = True
  10.         Me.MaximizeBox = False
  11.         Me.MinimizeBox = False
  12.         '// ปรับระยะของฟอร์มใหม่
  13.         '// การเข้าสู่ระบบ
  14.         If Not blnChangePassword Then
  15.             Me.MinimumSize = New Point(413, 355)
  16.             Me.MaximumSize = New Point(413, 355)
  17.             btnLogin.Location = New Point(146, 288)
  18.             btnExit.Location = New Point(217, 288)
  19.             btnLogin.Text = "Login"
  20.             lblPassword.Text = "PASSWORD"
  21.             lblNewPassword.Visible = False
  22.             txtNewPassword.Visible = False
  23.             '// การเปลี่ยนรหัสผ่าน
  24.         Else
  25.             Me.MinimumSize = New Point(413, 390)
  26.             Me.MaximumSize = New Point(413, 390)
  27.             btnLogin.Location = New Point(146, 341)
  28.             btnExit.Location = New Point(217, 341)
  29.             btnLogin.Text = "Save"
  30.             lblPassword.Text = "OLD PASSWORD"
  31.             lblNewPassword.Visible = True
  32.             txtNewPassword.Visible = True
  33.             Me.Text = "CHANGE PASSWORD"
  34.             lblLogin.Text = "Change Password"
  35.         End If
  36.         '//
  37.     End Sub

  38.     ' / ------------------------------------------------------------------------------------------------
  39.     ' / ตรวจสอบรหัสผ่าน
  40.     ' / ------------------------------------------------------------------------------------------------
  41.     Private Sub btnLogin_Click(sender As System.Object, e As System.EventArgs) Handles btnLogin.Click
  42.         '// เป็นการ Login เข้าสู่โปรแกรม
  43.         If Not blnChangePassword Then
  44.             '// เรียกไปฟังค์ชั่น CheckPassword ใน modDataBase.vb เพื่อตรวจสอบรหัสผ่านของ Admin
  45.             If CheckPassword(txtPassword.Text) Then
  46.                 '// Redirect to admin main form.
  47.                 blnLogin = True
  48.                 frmPassCodeFull.Show()
  49.                 Me.Close()
  50.             Else
  51.                 MessageBox.Show("Login failed. Please check your credentials.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  52.                 txtPassword.Focus()
  53.                 Return
  54.             End If

  55.             '// เปลี่ยนรหัสผ่าน Admin
  56.         Else
  57.             '// เรียกไปฟังค์ชั่น CheckPassword ใน modDataBase.vb เพื่อตรวจสอบรหัสผ่านของ Admin
  58.             If Not CheckPassword(txtPassword.Text) Then
  59.                 MessageBox.Show("The old password is incorrect.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Error)
  60.                 txtPassword.Focus()
  61.                 Return
  62.             End If
  63.             '// ยังไม่ได้ป้อนรหัสผ่านใหม่
  64.             If txtNewPassword.Text.Trim = String.Empty Or txtNewPassword.Text.Trim.Length = 0 Then
  65.                 MessageBox.Show("Please enter a new password.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Error)
  66.                 txtNewPassword.Focus()
  67.                 Return
  68.             End If
  69.             '// ทำการบันทึกรหัสผ่านใหม่
  70.             Call SavePassword(txtNewPassword.Text)
  71.             Me.Close()
  72.         End If
  73.     End Sub

  74.     '// แสดงรหัสผ่าน
  75.     Private Sub chkShowPass_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles chkShowPass.CheckedChanged
  76.         If chkShowPass.Checked Then
  77.             txtPassword.UseSystemPasswordChar = False
  78.             txtNewPassword.UseSystemPasswordChar = False
  79.         Else
  80.             txtPassword.UseSystemPasswordChar = True
  81.             txtNewPassword.UseSystemPasswordChar = True
  82.         End If
  83.         txtPassword.Focus()
  84.     End Sub

  85.     '// Function to handle the KeyPress event for TextBox controls.
  86.     Private Sub TextBox_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtPassword.KeyPress, txtNewPassword.KeyPress
  87.         If e.KeyChar = ChrW(Keys.Enter) Then
  88.             e.Handled = True '// Prevent the Enter key from adding a new line in the TextBox.
  89.             SendKeys.Send("{TAB}") '// Send the TAB key to move to the next control.
  90.         End If
  91.     End Sub

  92.     Private Sub btnExit_Click(sender As System.Object, e As System.EventArgs) Handles btnExit.Click
  93.         Me.Close()
  94.     End Sub

  95.     Private Sub frmLogin_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
  96.         Me.Dispose()
  97.         GC.SuppressFinalize(Me)
  98.     End Sub

  99. End Class
คัดลอกไปที่คลิปบอร์ด


โค้ดในส่วนของการติดต่อกับฐานข้อมูล (modDataBase.vb)
  1. Imports System.Data.OleDb

  2. Module modDataBase
  3.     Dim ConnString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & MyPath(Application.StartupPath) & "\PassCodeBook.accdb;"

  4.     Public blnLogin As Boolean = False  '// ส่งค่าแจ้งการ Login
  5.     Public blnChangePassword As Boolean = False '// แจ้งการเปลี่ยนรหัสผ่าน
  6.     ' / ------------------------------------------------------------------------------------------------
  7.     '// การใช้ Key และ IV
  8.     '// Key ควรมีขนาด 16, 24 หรือ 32 bytes เพื่อความปลอดภัย
  9.     '// IV (Initialization Vector) ควรมีขนาด 16 bytes สำหรับการเข้ารหัส AES
  10.     Dim key As String = "1234567890123456" '// Key 16 bytes
  11.     Dim iv As String = "6543210987654321"  '// IV 16 bytes
  12.     ' / ------------------------------------------------------------------------------------------------

  13.     Public Class Details
  14.         '// Auto Implemented Properties for Data Fields.
  15.         Public Property PK As Integer
  16.         Public Property Login As String
  17.         Public Property Encrypted As String
  18.         Public Property Url As String
  19.         Public Property Email As String
  20.         Public Property Phone As String
  21.         Public Property DateModified As Date
  22.     End Class

  23.     ' / ------------------------------------------------------------------------------------------------
  24.     '// Save data to MS Access database.
  25.     ' / ------------------------------------------------------------------------------------------------
  26.     Sub SaveData(newdata As Boolean, details As Details)
  27.         Dim sql As String
  28.         Try
  29.             Using Conn As New OleDbConnection(ConnString)
  30.                 Conn.Open()
  31.                 '// การเพิ่มข้อมูลใหม่
  32.                 If newdata Then
  33.                     sql = "INSERT INTO UserData (PK, url, Login, Encrypted, email, phone, DateModified) VALUES (@PK, @Url, @Email, @Phone, @Login, @Encrypted, @DateModified)"

  34.                     '// การแก้ไข
  35.                 Else
  36.                     '// Update the record if it exists.
  37.                     sql = "UPDATE UserData SET PK = @PK, url = @Url, Login = @Login, Encrypted = @Encrypted, email = @Email, Phone = @Phone, DateModified = @DateModified WHERE PK = @PK"
  38.                 End If
  39.                 '// Update.
  40.                 Using Cmd As New OleDbCommand(sql, Conn)
  41.                     With Cmd.Parameters
  42.                         .AddWithValue("@PK", details.PK)
  43.                         .AddWithValue("@url", details.Url)
  44.                         .AddWithValue("@login", details.Login)
  45.                         '// การเข้ารหัสด้วย Rijndael (AES) (modEncryption.vb)
  46.                         .AddWithValue("@Encrypted", EncryptPassword(details.Encrypted, key, iv))
  47.                         .AddWithValue("@email", details.Email)
  48.                         .AddWithValue("@phone", details.Phone)
  49.                         .AddWithValue("@DateModified", Format(details.DateModified, "dd/MM/yyyy"))
  50.                     End With
  51.                     Cmd.ExecuteNonQuery()
  52.                 End Using
  53.                 MessageBox.Show("UPDATE COMPLETE.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
  54.             End Using
  55.         Catch ex As Exception
  56.             MessageBox.Show("UPDATE NOT SUCCESSFUL!", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  57.         End Try
  58.     End Sub

  59.     ' / ------------------------------------------------------------------------------------------------
  60.     '// Retrieve data from MS Access database and display in DataGridView.
  61.     '// blnSearch = True คือการค้นหาข้อมูล โดยรับค่า SearchValue เป็นคีย์เวิร์ดใช้ในการค้นหา
  62.     '// blnSearch = False ก็จะแสดงผลข้อมูลออกมาทั้งหมด
  63.     '// ทั้ง 2 ค่าเป็น Optional คือหากไม่ระบุการส่งค่ามา ก็ให้มีค่าเป็น False หรือแสดงผลข้อมูลออกมาทั้งหมด
  64.     ' / ------------------------------------------------------------------------------------------------
  65.     Function RetrieveData(Optional ByVal blnSearch As Boolean = False, Optional ByVal SearchValue As String = "") As DataTable
  66.         Using Conn As New OleDbConnection(ConnString)
  67.             Conn.Open()
  68.             Dim sql As String = "SELECT PK, url, login, Encrypted, email, phone, DateModified FROM UserData"
  69.             If blnSearch Then
  70.                 sql &= " WHERE url LIKE @SearchValue OR email LIKE @SearchValue OR phone LIKE @SearchValue OR login LIKE @SearchValue"
  71.             End If
  72.             sql &= " ORDER BY PK"
  73.             '//
  74.             Using cmd As New OleDbCommand(sql, Conn)
  75.                 If blnSearch Then cmd.Parameters.AddWithValue("@SearchValue", "%" & SearchValue & "%")
  76.                 '//
  77.                 Using reader As OleDbDataReader = cmd.ExecuteReader()
  78.                     Dim dt As New DataTable()
  79.                     With dt.Columns
  80.                         .Add("PK", GetType(Integer))
  81.                         .Add("URL", GetType(String))
  82.                         .Add("Login", GetType(String))
  83.                         '.Add("Encrypted", GetType(String))
  84.                         .Add("Email", GetType(String))
  85.                         .Add("Phone", GetType(String))
  86.                         .Add("DateModified", GetType(Date))
  87.                     End With
  88.                     While reader.Read()
  89.                         '// มีการเข้ารหัสของรหัสผ่านเอาไว้ตอนแสดงผลในตารางกริด
  90.                         Dim EncryptedData As Byte() = DirectCast(reader("Encrypted"), Byte())
  91.                         '// เพิ่มรายการแถวข้อมูลเข้าไปใน DataTable
  92.                         dt.Rows.Add(reader("PK"), reader("url"), reader("login"), reader("email"), reader("phone"), reader("DateModified"))
  93.                     End While
  94.                     Return dt
  95.                 End Using
  96.             End Using
  97.         End Using
  98.     End Function

  99.     ' / ------------------------------------------------------------------------------------------------
  100.     ' / คืนค่าข้อมูลจากตารางกริดไปแสดงผลลงใน Control
  101.     ' / ------------------------------------------------------------------------------------------------
  102.     Public Function RetrieveDetails(PK As Integer) As Details
  103.         '// Class Details เพื่อคืนค่ากลับไปแสดงผลในฟอร์ม
  104.         Dim result As New Details()
  105.         Try
  106.             Using Conn As New OleDbConnection(ConnString)
  107.                 Conn.Open()
  108.                 Using cmd As New OleDbCommand("SELECT url, login, Encrypted, email, phone, DateModified FROM UserData WHERE PK = @PK", Conn)
  109.                     cmd.Parameters.AddWithValue("@PK", PK)
  110.                     Using reader As OleDbDataReader = cmd.ExecuteReader()
  111.                         If reader.Read() Then
  112.                             result.Url = reader("url").ToString()
  113.                             result.Login = reader("login").ToString()
  114.                             '// ถอดรหัสออกมาเพื่อให้เห็น Password แบบ Plain Text.
  115.                             result.Encrypted = DecryptPassword(DirectCast(reader("Encrypted"), Byte()), key, iv)
  116.                             result.Email = reader("email").ToString()
  117.                             result.Phone = reader("phone").ToString()
  118.                             result.DateModified = reader("DateModified").ToString()
  119.                             Return (result)
  120.                         End If
  121.                     End Using
  122.                 End Using
  123.             End Using
  124.         Catch ex As Exception
  125.             MessageBox.Show("Error: " & ex.Message, "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  126.         End Try
  127.         Return result '// Return the initialized structure if no data is found.
  128.     End Function

  129.     ' / ------------------------------------------------------------------------------------------------
  130.     ' / DELETE DATA
  131.     ' / ------------------------------------------------------------------------------------------------
  132.     Public Sub DeleteData(PK As Integer)
  133.         Try
  134.             Using Conn As New OleDbConnection(ConnString)
  135.                 Conn.Open()
  136.                 Dim sql As String = "DELETE FROM UserData WHERE PK = @PK"
  137.                 Using cmd As New OleDbCommand(sql, Conn)
  138.                     cmd.Parameters.AddWithValue("@PK", PK)
  139.                     Try
  140.                         cmd.ExecuteNonQuery()
  141.                         MessageBox.Show("DELETE COMPLETE.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
  142.                     Catch ex As Exception
  143.                         MessageBox.Show("Error: " & ex.Message)
  144.                     End Try
  145.                 End Using
  146.             End Using
  147.         Catch ex As Exception
  148.             MessageBox.Show("Error: " & ex.Message, "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  149.         End Try
  150.     End Sub

  151.     ' / ------------------------------------------------------------------------------------------------
  152.     ' / Function to find and create the new Primary Key not to duplicate.
  153.     ' / ------------------------------------------------------------------------------------------------
  154.     Function SetupNewPK(ByVal sql As String) As Integer
  155.         Using Conn As New OleDbConnection(ConnString)
  156.             Conn.Open()
  157.             Using cmd As New OleDbCommand(sql, Conn)
  158.                 '/ Check if the information is available. And return it back
  159.                 If IsDBNull(cmd.ExecuteScalar) Then
  160.                     '// Start at 1
  161.                     SetupNewPK = 1
  162.                 Else
  163.                     SetupNewPK = cmd.ExecuteScalar + 1
  164.                 End If
  165.             End Using
  166.         End Using
  167.     End Function

  168.     ' / ------------------------------------------------------------------------------------------------
  169.     ' / Function to check password for login system.
  170.     ' / ------------------------------------------------------------------------------------------------
  171.     Public Function CheckPassword(password As String) As Boolean
  172.         CheckPassword = False
  173.         Using Conn As New OleDbConnection(ConnString)
  174.             Conn.Open()
  175.             '// มีข้อมูลสำหรับ Admin อยู่แค่รายการเดียว
  176.             Using Cmd As New OleDbCommand("SELECT TOP 1 * FROM AdminData ", Conn)
  177.                 Using reader As OleDbDataReader = Cmd.ExecuteReader()
  178.                     If reader.Read() Then
  179.                         '// ถอดรหัสผ่านแล้วนำค่ามาเปรียบเทียบกับค่าที่ป้อนเข้าไป
  180.                         If password = DecryptPassword(DirectCast(reader("Encrypted"), Byte()), key, iv) Then Return True
  181.                     Else
  182.                         Return False ' ไม่พบข้อมูลผู้ใช้
  183.                     End If
  184.                 End Using
  185.             End Using
  186.         End Using
  187.     End Function

  188.     ' / ------------------------------------------------------------------------------------------------
  189.     '// Save new Admin Password.
  190.     ' / ------------------------------------------------------------------------------------------------
  191.     Sub SavePassword(ByVal NewPassword As String)
  192.         Try
  193.             Using Conn As New OleDbConnection(ConnString)
  194.                 Conn.Open()
  195.                 '// Update the record if it exists.
  196.                 Dim sql As String = "UPDATE AdminData SET PK = @PK, Encrypted = @Encrypted WHERE PK = @PK"
  197.                 '// Update.
  198.                 Using Cmd As New OleDbCommand(Sql, Conn)
  199.                     With Cmd.Parameters
  200.                         .AddWithValue("@PK", 1)
  201.                         '// การเข้ารหัสด้วย Rijndael (AES) (modEncryption.vb)
  202.                         .AddWithValue("@Encrypted", EncryptPassword(NewPassword, key, iv))
  203.                     End With
  204.                     Cmd.ExecuteNonQuery()
  205.                 End Using
  206.                 MessageBox.Show("UPDATE COMPLETE.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
  207.             End Using
  208.         Catch ex As Exception
  209.             MessageBox.Show("UPDATE NOT SUCCESSFUL!", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Warning)
  210.         End Try
  211.     End Sub
  212. End Module
คัดลอกไปที่คลิปบอร์ด

โค้ดในส่วนของการเข้ารหัส/ถอดรหัส (modEncryption.vb)
  1. Imports System.Security.Cryptography
  2. Imports System.Text
  3. Imports System.IO

  4. Module modEncryption

  5.     '// Rijndael (AES) ในการเข้ารหัสข้อมูล (Encryption) โดยการใช้ Key และ IV (Initialization Vector).
  6.     Public Function EncryptPassword(password As String, key As String, iv As String) As Byte()
  7.         Dim aes As New RijndaelManaged()
  8.         aes.Key = Encoding.UTF8.GetBytes(key)
  9.         aes.IV = Encoding.UTF8.GetBytes(iv)
  10.         aes.Padding = PaddingMode.PKCS7
  11.         aes.Mode = CipherMode.CBC

  12.         Dim encryptor As ICryptoTransform = aes.CreateEncryptor(aes.Key, aes.IV)

  13.         Using ms As New MemoryStream()
  14.             Using cs As New CryptoStream(ms, encryptor, CryptoStreamMode.Write)
  15.                 Using sw As New StreamWriter(cs)
  16.                     sw.Write(password)
  17.                 End Using
  18.             End Using
  19.             Return ms.ToArray()
  20.         End Using
  21.     End Function

  22.     '// Rijndael (AES) ในการถอดรหัสข้อมูล (Decryption)
  23.     Public Function DecryptPassword(encryptedPassword As Byte(), key As String, iv As String) As String
  24.         Dim aes As New RijndaelManaged()
  25.         aes.Key = Encoding.UTF8.GetBytes(key)
  26.         aes.IV = Encoding.UTF8.GetBytes(iv)
  27.         aes.Padding = PaddingMode.PKCS7
  28.         aes.Mode = CipherMode.CBC

  29.         Dim decryptor As ICryptoTransform = aes.CreateDecryptor(aes.Key, aes.IV)

  30.         Using ms As New MemoryStream(encryptedPassword)
  31.             Using cs As New CryptoStream(ms, decryptor, CryptoStreamMode.Read)
  32.                 Using sr As New StreamReader(cs)
  33.                     Return sr.ReadToEnd()
  34.                 End Using
  35.             End Using
  36.         End Using
  37.     End Function
  38. End Module
คัดลอกไปที่คลิปบอร์ด


โค้ดในส่วนของฟังค์ชั่น (modFunction.vb)
  1. Module modFunction
  2.     Function MyPath(ByVal AppPath As String) As String
  3.         '/ Return Value
  4.         MyPath = AppPath.ToLower.Replace("\bin\debug", "").Replace("\bin\release", "").Replace("\bin\x86\debug", "").Replace("\bin\x86\release", "")
  5.         '// If not found folder then put the \ (BackSlash) at the end.
  6.         If Microsoft.VisualBasic.Right(MyPath, 1) <> Chr(92) Then MyPath = MyPath & Chr(92)
  7.     End Function

  8.     ' / --------------------------------------------------------------------------------
  9.     '// Initialize DataGridView @Run Time
  10.     Public Sub SetupDataGridView(DGV As DataGridView)
  11.         With DGV
  12.             .RowHeadersVisible = False
  13.             .AllowUserToAddRows = False
  14.             .AllowUserToDeleteRows = False
  15.             .AllowUserToResizeRows = False
  16.             .MultiSelect = False
  17.             .SelectionMode = DataGridViewSelectionMode.FullRowSelect
  18.             .ReadOnly = True
  19.             .Font = New Font("Tahoma", 11, FontStyle.Regular)
  20.             .RowTemplate.Height = 28
  21.             .RowTemplate.Resizable = DataGridViewTriState.False
  22.             .Columns(0).Visible = False '// Primary Key
  23.             '// Autosize Column
  24.             .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
  25.             '// Even-Odd Color
  26.             .AlternatingRowsDefaultCellStyle.BackColor = Color.AliceBlue
  27.             '// COLUMN HEADER
  28.             '// Adjust Header Styles
  29.             With .ColumnHeadersDefaultCellStyle
  30.                 .BackColor = Color.Navy
  31.                 .ForeColor = Color.Black ' Color.White
  32.                 .Font = New Font("Tahoma", 11, FontStyle.Bold)
  33.             End With
  34.             '// Before you can adjust the height of the row.
  35.             .ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing
  36.             .ColumnHeadersHeight = 30
  37.             '// Accept color background changes.
  38.             .EnableHeadersVisualStyles = False
  39.             For iCol = 0 To DGV.Columns.Count - 1
  40.                 '// Calculates odd and even numbers. If any integer divide by 2, then answer 1 is odd number.
  41.                 If iCol Mod 2 = 0 Then
  42.                     DGV.Columns(iCol).HeaderCell.Style.BackColor = Color.Gold
  43.                     '// Integer divide by 2, then answer 1 is Even number.
  44.                 Else
  45.                     DGV.Columns(iCol).HeaderCell.Style.BackColor = Color.Orange
  46.                 End If
  47.             Next
  48.         End With
  49.     End Sub

  50. End Module
คัดลอกไปที่คลิปบอร์ด

ดาวน์โหลดโค้ดต้นฉบับ VB.NET (2010) ได้ที่นี่ ...

ขออภัย! โพสต์นี้มีไฟล์แนบหรือรูปภาพที่ไม่ได้รับอนุญาตให้คุณเข้าถึง

คุณจำเป็นต้อง ลงชื่อเข้าใช้ เพื่อดาวน์โหลดหรือดูไฟล์แนบนี้ คุณยังไม่มีบัญชีใช่ไหม? ลงทะเบียน

x
สิ่งที่ดีกว่าการให้ คือการให้แบบไม่มีที่สิ้นสุด
ขออภัย! คุณไม่ได้รับสิทธิ์ในการดำเนินการในส่วนนี้ กรุณาเลือกอย่างใดอย่างหนึ่ง ลงชื่อเข้าใช้ | ลงทะเบียน

รายละเอียดเครดิต

ข้อความล้วน|อุปกรณ์พกพา|ประวัติการแบน|G2GNet.com  

GMT+7, 2024-9-21 09:50 , Processed in 0.103844 second(s), 5 queries , File On.

Powered by Discuz! X3.4, Rev.62

Copyright © 2001-2020 Tencent Cloud.

ตอบกระทู้ ขึ้นไปด้านบน ไปที่หน้ารายการกระทู้