Imports System.Data
Imports System.Data.SqlClient

Partial Class _LogIn
    Inherits System.Web.UI.Page
    Public sqlConnection As SqlConnection

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim sqlString As String = "Server=localhost;" + _
                "Data Source=Susan\SQLEXPRESS;Database=CSE_DEPT;" + _
                "Integrated Security=SSPI"
        sqlConnection = New SqlConnection(sqlString)
        Application("sqlConnection") = sqlConnection
        If sqlConnection.State = ConnectionState.Open Then
            sqlConnection.Close()
        End If
        sqlConnection.Open()
        If sqlConnection.State <> ConnectionState.Open Then
            Response.Write("<script>alert('Database connection is Failed')</script>")
            Exit Sub
        End If
    End Sub

    Protected Sub cmdLogIn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdLogIn.Click
        Dim cmdString1 As String = "SELECT user_name, pass_word, faculty_id, student_id FROM LogIn "
        Dim cmdString2 As String = "WHERE (user_name LIKE @name ) AND (pass_word LIKE @word)"
        Dim cmdString As String = cmdString1 & cmdString2
        Dim paramUserName As New SqlParameter
        Dim paramPassWord As New SqlParameter
        Dim sqlCommand As New SqlCommand
        Dim sqlDataReader As SqlDataReader

        paramUserName.ParameterName = "@name"
        paramUserName.Value = txtUserName.Text
        paramPassWord.ParameterName = "@word"
        paramPassWord.Value = txtPassWord.Text
        sqlCommand.Connection = sqlConnection
        sqlCommand.CommandType = CommandType.Text
        sqlCommand.CommandText = cmdString
        sqlCommand.Parameters.Add(paramUserName)
        sqlCommand.Parameters.Add(paramPassWord)
        sqlDataReader = sqlCommand.ExecuteReader
        If sqlDataReader.HasRows = True Then
            'Response.Write("<script>alert('LogIn is successful!')</script>")
            Response.Redirect("Selection.aspx")
        Else
            Response.Write("<script>alert('No matched username/password found!')</script>")
        End If
        sqlCommand.Dispose()
        sqlCommand = Nothing
        sqlDataReader.Close()
        sqlDataReader = Nothing
    End Sub

    Protected Sub cmdCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdCancel.Click
        If sqlConnection.State = ConnectionState.Open Then
            sqlConnection.Close()
        End If
        Response.Write("<script>window.close()</script>")
    End Sub
End Class
