thongkorn โพสต์ 2024-1-11 13:29:40

[VB.NET] การทำ Login เข้าสู่ระบบของ Google Sheets

http://www.g2gsoft.com/webboard/images/VBNet/googlesheetlogin.png

http://www.g2gsoft.com/webboard/images/VBNet/googlesheetreference.png
Add References ...


http://www.g2gsoft.com/webboard/images/VBNet/googlesheetcredential.png
Youtube แสดงวิธีการขั้นตอนในการรับไฟล์ Credentials ... หรือ Google API ซึ่งจะอยู่ในรูปแบบของ JSON


ํYoutube แสดงวิธีการกำหนดสิทธิการเข้าถึง Google Sheets ...

ตัวอย่าง Google Sheets ซึ่งตอนนี้แอดมินได้เปิดให้เป็นแบบ Editor เพื่อให้ได้ลองทำการเขียนอ่านข้อมูลได้ ...


พื้นฐานของการใช้งาน List (Of Object)
...


มาดูโค้ดฉบับเต็มกันเถอะ ...
Imports Google.Apis.Sheets.v4
Imports Google.Apis.Sheets.v4.Data

Public Class frmLogin

    Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
      If Trim(txtUsername.Text.Trim.Length) = 0 Then
            MessageBox.Show("Enter your Username.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            txtUsername.Focus()
            Return
      ElseIf Trim(txtPassword.Text.trim.Length) = 0 Then
            MessageBox.Show("Enter your Password.", "Report status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            txtPassword.Focus()
            Return
      End If
      '// If Login Successful then Close Form Login.
      If LoginSystem() Then Me.Close()
    End Sub

    ' / --------------------------------------------------------------------------------
    Private Function LoginSystem() As Boolean
      LoginSystem = False
      '// Define Sheet Name.
      Dim SheetName As String = "UserData"
      '// Range A1:B1 is Column Header.
      Dim range As String = SheetName + "!A2:B100"    '// Select range column A is UserName and column B is Password.
      '// Initialize Google Sheets API.
      Call Credentials()
      '// Read data from the specified range.
      Dim request As SpreadsheetsResource.ValuesResource.GetRequest = Service.Spreadsheets.Values.Get(SpreadsheetId, range)
      Dim response As ValueRange = request.Execute()
      '// Process the data.
      If response IsNot Nothing AndAlso response.Values IsNot Nothing Then
            For Each row As List(Of Object) In response.Values
                If row(0).ToString() = txtUsername.Text.Trim AndAlso row(1).ToString() = txtPassword.Text.Trim Then
                  '// Login Successful.
                  MessageBox.Show("Login successful!", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Information)
                  Return True
                End If
            Next
            '// Login failed.
            MessageBox.Show("Invalid username or password.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            'Return False
      Else
            MessageBox.Show("No data found.", "Report Status", MessageBoxButtons.OK, MessageBoxIcon.Warning)
      End If
      '//
    End Function

    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
      Me.Close()
      Me.Dispose()
      Application.Exit()
    End Sub

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

    Private Sub frmLogin_Load(sender As Object, e As System.EventArgs) Handles Me.Load
      '//
    End Sub

    Private Sub txtUsername_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtUsername.KeyPress
      If Asc(e.KeyChar) = 13 Then
            e.Handled = True
            SendKeys.Send("{TAB}")
      End If
    End Sub

    Private Sub txtPassword_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtPassword.KeyPress
      If Asc(e.KeyChar) = 13 Then
            e.Handled = True
            SendKeys.Send("{TAB}")
      End If
    End Sub
End Class

โมดูลในการกำหนดค่าที่สำคัญของ Google Sheets เช่น SpreadSheetID, Application Name และไฟล์ Credentials
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Services
Imports Google.Apis.Sheets.v4

Module modCredentials
    Public Service As SheetsService
    Public SpreadsheetId As String = "1nBOWl-PDGwYng6IOifi6bhoLfvamTn-45CWtn5t59qs"
    Public ApplicationName = "SampleSheet" '// Same as Filename.
    '// JSON credential file path.
    Public CredentialFilePath As String = MyPath(Application.StartupPath) & "credentials\GoogleSheet.json"

    ' / ------------------------------------------------------------------------------------------------
    ' / Initialize Google Sheets API.
    ' / ------------------------------------------------------------------------------------------------
    Public Sub Credentials()
      '// Load credentials from JSON file
      Dim credential = GoogleCredential.FromFile(CredentialFilePath).CreateScoped(SheetsService.Scope.Spreadsheets)
      '// Create Google Sheets API service
      Service = New SheetsService(New BaseClientService.Initializer() With {
            .HttpClientInitializer = credential,
            .ApplicationName = ApplicationName
      })
    End Sub
End Module

ดาวน์โหลดโค้ดฉบับเต็ม VB.NET (2017) ได้จากที่นี่ ...
หน้า: [1]
ดูในรูปแบบกติ: [VB.NET] การทำ Login เข้าสู่ระบบของ Google Sheets