0

I wanna create a txt file that stores the Username, Password, Date & Time, and User Type when "Log In" button is pressed. But all I know is how to create a txt file. Can anyone help me? Here's my code for my Log In button:

Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
    Dim username As String = ""
    Dim password As String = ""
    Dim cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=D:\Library Management System\LMS_Database.accdb")

    Dim cmd As OleDbCommand = New OleDbCommand("SELECT ID_Number FROM Users WHERE ID_Number = '" & txtUsername.Text & "' AND ID_Number = '" & txtPassword.Text & "'", cn)
    cn.Open()
    Dim dr As OleDbDataReader = cmd.ExecuteReader()
    If (dr.Read() = True And cboUserType.Text = "Student") Then
        MsgBox("Welcome!", MsgBoxStyle.OkOnly, "Successfully logged in.")
        frmViewBooks.Show()
        txtUsername.Clear()
        txtPassword.Clear()
        cboUserType.SelectedIndex = -1
        Me.Hide()
    Else
        If (txtUsername.Text = "admin" And txtPassword.Text = "ckclibraryadmin" And cboUserType.Text = "Administrator") Then
            MsgBox("Welcome, admin!", MsgBoxStyle.OkOnly, "Successfully logged in.")
            frmAdminWindow.Show()
            txtUsername.Clear()
            txtPassword.Clear()
            cboUserType.SelectedIndex = -1
            Me.Hide()
        Else
            MsgBox("Your username or password is invalid. Please try again.", MsgBoxStyle.OkOnly, "Login failed.")
            txtUsername.Clear()
            txtPassword.Clear()
            cboUserType.SelectedIndex = -1
        End If
    End If
End Sub

I'd be getting the Date and Time value from my timer.

Private Sub frmLogIn_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    tmrLogIn.Start()
End Sub

Private Sub tmrLogIn_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrLogIn.Tick
    lblTime.Text = DateTime.Now.ToString()
End Sub

Thank you!

Sunil
  • 3,404
  • 10
  • 23
  • 31
  • 1
    There seems to be nothing in that code related to creating or writing to a text file. Writing passwords to a text file is not a good idea anyway. You still need to learn about Parameters - your code will crash on a great many names. You also need to read [ask] and take the [tour] - this is not a tutorial site – Ňɏssa Pøngjǣrdenlarp Jan 27 '18 at 15:12
  • If you want to store them in a text file then you should hash the password. – Chillzy Jan 27 '18 at 16:03

2 Answers2

1

There are a few things that I'd like to point out to maybe help you later on down the road. Data object generally implement iDisposable, it is a good idea to either wrap them in Using statements or dispose of them manually. Also, it is generally a good idea to wrap any database code into a Try/Catch exception handler because something can go wrong at any point you're trying to access outside data. Also, it is always a good idea to parameterize your query. Finally, you are only wanting to validate that a row is returned from your SQL statement, so your SQL statement should instead return the number of rows returned and then you can use the ExecuteScalar to get that one value returned.

With all of that out of the way, all you would need to do is append a line to a text file using the IO.File.AppendAllLines method using the data you already have if the login was validated.

Here is an example of implementing everything I suggested:

'Declare the object to return
Dim count As Integer = -1

'Declare the connection object
Dim con As OleDbConnection

'Wrap code in Try/Catch
Try
    'Set the connection object to a new instance
    con = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=D:\Library Management System\LMS_Database.accdb")

    'Create a new instance of the command object
    'TODO: If [Username] and [Password] are not valid columns, then change them
    Using cmd As OleDbCommand = New OleDbCommand("SELECT Count([ID_Number]) FROM [Users] WHERE [Username] = @username AND [Password] = @password", con)
        'Parameterize the query
        With cmd.Parameters
          .AddWithValue("@username", txtUsername.Text)
          .AddWithValue("@password", txtPassword.Text)
        End With

        'Open the connection
        con.Open()

        'Use ExecuteScalar to return a single value
        count = Convert.ToInt32(cmd.ExecuteScalar())

        'Close the connection
        con.Close()
    End Using

    If count > 0 Then
      'Append the data to the text file
      'TODO: Change myfilehere.txt to the desired file name and location
      IO.File.AppendAllLines("myfilehere.txt", String.Join(",", {txtUsername.Text, txtPassword.Text, DateTime.Now, cboUserType.Text}))

      'Check if it is a student or admin
      If cboUserType.Text = "Student" Then
        'Inform the user of the successfull login
        MessageBox.Show("Welcome!", "Login Successfull", MessageBoxButtons.OK)
        frmViewBooks.Show()
      ElseIf cboUserType.Text = "Administrator" Then
        'Inform the admin of the successfull login
        MessageBox.Show("Welcome, admin!", "Login Successfull", MessageBoxButtons.OK)
        frmAdminWindow.Show()
      End If

      'Reset and hide the form
      txtUsername.Clear()
      txtPassword.Clear()
      cboUserType.SelectedIndex = -1
      Me.Hi
    Else
      'Inform the user of the invalid login
      MessageBox.Show("Invalid username and/or password. Please try again.", "Invalid Login", MessageBoxButtons.OK)
    End If
Catch ex As Exception
    'Display the error
    Console.WriteLine(ex.Message)
Finally
    'Check if the connection object was initialized
    If con IsNot Nothing Then
        If con.State = ConnectionState.Open Then
            'Close the connection if it was left open(exception thrown)
            con.Close()
        End If

        'Dispose of the connection object
        con.Dispose()
    End If
End Try
David
  • 5,877
  • 3
  • 23
  • 40
0

Your goal can be achieved in many ways.For example,you can create an access/sql/mysql database to store the required information.But if u want to use a textfile instead,you can store Username,password and other details on seperate lines.Then you can read each line from the text file and use it the way you want.So,which one u prefer? a database or text file? leave a comment and i'lll add the codes/instructions depending on your choice

Software Dev
  • 5,368
  • 5
  • 22
  • 45