Option Strict On
Imports System
Imports System.Web.UI.WebControls
Imports System.ComponentModel
Imports BaseClasses
Imports BaseClasses.Utils
Imports BaseClasses.Web.UI.WebControls
        
Imports AuditTrail.Business
Imports AuditTrail.Data
        
Namespace AuditTrail.UI

#Region "Code customizations"
    ' Each page class is defined in a hierarchy sub-classed from the
    ' Page class of Microsoft .NET Framework. The hierarchy is as follows:
    '
    '    System.Web.UI.Page   (Microsoft .NET Framework class)
    '     BaseClasses.Web.UI.BasePage    (Base Classes.  Source code included)
    '      BaseApplicationPage    (Application wide BasePage class.  You can make app wide page customizations here.)
    '        ShowOrder_DetailsTablePage    (Code-behind class. Created once. Never overwritten)
    '
    ' All code customizations can be done in the code-behind class.  Since the
    ' code-behind class is created once, and never overwritten, you can be
    ' assured that all of your customizations are preserved.
    '
    ' The code-behind class is the lowest class in the hierarchy.  This
    ' means that can can override any functionality provided by any
    ' of the parent classes.
    '
    ' The BaseApplicationPage class (defined in <AppFolder>\Shared\BaseApplicationPage.vb)
    ' allows you to modify the behavior of the System.Web.UI.Page
    ' or BaseClasses.Web.UI.BasePage across the entire application.
    '
    ' The table and record controls included in this control will have their code behind classes
    ' generated in <AppFolder>\App_Code\${ControlSafeClassDirectory}\ShowOrder_DetailsTablePage.Controls.vb
    ' Customizations made to these table and record controls will be added to this class.
#End Region
    ' Code-behind class for the SignIn_Control user control.

    Partial Class SignIn_Control
        Inherits BaseApplicationUserControl

#Region "Section 1: Place your customizations here."
        ' LoadData reads database data and assigns it to UI controls.
        ' Customize by adding code before or after the call to LoadData_Base()
        ' or replace the call to LoadData_Base().
        Public Sub LoadData()
            LoadData_Base()
        End Sub

        ' Write out override methods for the page events


#End Region

#Region "Section 2: Do not modify this section."

        'signInState is a class to store values of cookies in the session state. It is used by SignIn_Control, 
        'SignOut.ascx.vb(cs) and SignIn_Control.Controls.vb(cs)
        Public signInState As SignInState
        ' Handles MyBase.Init.  If you need to, you can add additional Init handlers in Section 1.
        Protected Overridable Sub Page_InitializeEventHandlers(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Init
            ' Register the Event handler for any Events.

        End Sub

        ' Handles MyBase.Load.  If you need to, you can add additional Load handlers in Section 1.
        ' Read database data and put into the UI controls.
        Protected Overridable Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            ' Load data only when displaying the page for the first time
            Me.signInState = New SignInState
            If (Not Me.IsPostBack) Then
                Me.CookieInit()

                ' Read the data for all controls on the page.
                ' To change the behavior, override the DataBind method for the individual
                ' record or table UI controls.
                Me.LoadData()
            End If

        End Sub

        ' Load data from database into UI controls. 
        ' Modify LoadData in Section 1 above to customize.  Or override DataBind() in
        ' the individual table and record controls to customize.
        Public Sub LoadData_Base()
            Try
                ' Load data only when displaying the page for the first time
                If (Not Me.IsPostBack) Then

                    ' Must start a transaction before performing database operations
                    DbUtils.StartTransaction()

                    ' Load data for each record and table UI control.
                    ' Ordering is important because child controls get 
                    ' their parent ids from their parent UI controls.


                End If

            Catch ex As Exception
                ' An error has occured so display an error message.
                Utils.RegisterJScriptAlert(Me, "Page_Load_Error_Message", ex.Message)
            Finally
                If Not Me.IsPostBack Then
                    ' End database transaction
                    DbUtils.EndTransaction()
                End If
            End Try
        End Sub

        Public Overridable Sub Login(ByVal redirectUrl As String)
            Me.SignInControl.Login(redirectUrl)
        End Sub

        'Performs the login
        Public Overridable Sub Login(ByVal bRedirectOnSuccess As Boolean)
            Me.SignInControl.Login(bRedirectOnSuccess)
        End Sub

        'Sets cookies when login succeeded
        Private Sub MySetCookie(ByVal sender As Object, ByVal e As System.EventArgs) Handles SignInControl.LoginSucceeded
            If Me.signInState Is Nothing Then
                Me.signInState = New SignInState
            End If
            Dim CheckCrypto As Crypto = New Crypto(Crypto.Providers.DES)
            Dim key As String = BaseClasses.Configuration.ApplicationSettings.Current.CookieEncryptionKey
            If (Me.signInState.IsUNToRemember) Then
                Dim uNameEncrypted As String = CheckCrypto.Encrypt(Me.UserName.Text, key, System.Text.Encoding.Unicode, False)
                BaseClasses.Utils.NetUtils.SetCookie(NetUtils.CookieUserName(), uNameEncrypted)
            Else
                BaseClasses.Utils.NetUtils.SetCookie(NetUtils.CookieUserName(), "")
            End If
            If (Me.signInState.IsPassToRemember) Then
                If (Me.Password.Text <> "**********" And Me.Password.Text.Trim <> "") Then
                    Me.signInState.Password = Me.Password.Text
                End If
                Dim passwordEncrypted As String = CheckCrypto.Encrypt(Me.signInState.Password, key, System.Text.Encoding.Unicode, False)
                BaseClasses.Utils.NetUtils.SetCookie(NetUtils.CookiePassword(), passwordEncrypted)
            Else
                BaseClasses.Utils.NetUtils.SetCookie(NetUtils.CookiePassword(), "")
            End If
            BaseClasses.Utils.NetUtils.SetCookie(NetUtils.CookieRememberName(), Me.signInState.IsUNToRemember.ToString())
            BaseClasses.Utils.NetUtils.SetCookie(NetUtils.CookieRememberPassword(), Me.signInState.IsPassToRemember.ToString())
            Me.signInState.IsAutoLogin = True
        End Sub

        'Resets AutoLogin when login failed
        Private Sub ResetAutoLogin(ByVal sender As Object, ByVal e As System.EventArgs) Handles SignInControl.LoginFailed
            If Me.signInState Is Nothing Then
                Me.signInState = New SignInState
            End If
            Me.signInState.IsAutoLogin = False
            If (Not Me.signInState.IsUNToRemember) Then
                BaseClasses.Utils.NetUtils.SetCookie(NetUtils.CookieUserName(), "")
                BaseClasses.Utils.NetUtils.SetCookie(NetUtils.CookieRememberName(), Me.signInState.IsUNToRemember.ToString())
            End If
            If (Not Me.signInState.IsPassToRemember) Then
                BaseClasses.Utils.NetUtils.SetCookie(NetUtils.CookiePassword(), "")
                BaseClasses.Utils.NetUtils.SetCookie(NetUtils.CookieRememberPassword(), Me.signInState.IsPassToRemember.ToString())
            End If
        End Sub

        'sets names to their current values before page loads. Need to do that because checkboxes trigger PostBack event and 
        'values of textboxes would not be remembered otherwise
        Private Sub SignIn_Control_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.PreRender
            If Me.signInState Is Nothing Then
                Me.signInState = New SignInState
            End If

            If (Me.signInState.IsUNToRemember) Then
                If (Me.signInState.UserName <> "") Then
                    Me.CheckBoxUN.Checked = Me.signInState.IsUNToRemember
                    Me.UserName.Text = Me.signInState.UserName
                End If
            End If
            If (Me.signInState.Password <> "") Then
                Me.CheckBoxPass.Checked = Me.signInState.IsPassToRemember
                If (Me.Password.Text <> "**********" And Me.Password.Text.Trim <> "") Then
                    Me.signInState.Password = Me.Password.Text
                Else
                    Me.Password.Text = Me.signInState.Password
                End If
                Me.signInState.LoginPassword = Me.signInState.Password
                Password.Attributes.Add("value", "**********")
            ElseIf Me.Password.Text = "" Then
                Password.Attributes.Add("value", "")
                Me.signInState.LoginPassword = ""
            Else
                Me.signInState.LoginPassword = ""
            End If

        End Sub
        Public Sub CheckBoxUN_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBoxUN.CheckedChanged
            If Me.signInState Is Nothing Then
                Me.signInState = New SignInState
            End If
            If (Me.CheckBoxUN.Checked = True) Then
                Me.signInState.IsUNToRemember = True
                If (Me.Password.Text <> "**********") Then
                    Me.signInState.Password = Me.Password.Text
                End If
            Else
                Me.signInState.IsUNToRemember = False
                Me.signInState.UserName = ""
                If (Me.Password.Text <> "**********" And Me.Password.Text.Trim <> "") Then
                    Me.signInState.Password = Me.Password.Text
                End If
            End If
        End Sub

        Public Sub CheckBoxPass_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBoxPass.CheckedChanged
            If Me.signInState Is Nothing Then
                Me.signInState = New SignInState
            End If
            If (Me.CheckBoxPass.Checked = True) Then
                Me.signInState.IsPassToRemember = True
                If (Me.Password.Text <> "**********") Then
                    Me.signInState.Password = Me.Password.Text
                End If
            Else
                Me.signInState.IsPassToRemember = False
                If (Me.Password.Text <> "**********" And Me.Password.Text.Trim <> "") Then
                    Me.signInState.Password = Me.Password.Text
                End If
            End If
        End Sub

        Private Sub CheckBoxAutoLogin_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBoxAutoLogin.CheckedChanged
            Dim key As String = BaseClasses.Configuration.ApplicationSettings.Current.CookieEncryptionKey
            Dim isAutoLogin As Boolean = Me.CheckBoxAutoLogin.Checked
            BaseClasses.Utils.NetUtils.SetCookie(NetUtils.CookieAutoLogin(), isAutoLogin.ToString())
        End Sub

        'CookieInit initializes all cookie values.
        Private Sub CookieInit()
            If Me.signInState Is Nothing Then
                Me.signInState = New SignInState
            End If
            Me.UserName.TabIndex = 1
            Me.Password.TabIndex = 2
            Me.CheckBoxUN.TabIndex = 3
            Me.CheckBoxPass.TabIndex = 4
            Me.CheckBoxAutoLogin.TabIndex = 5
            Me.CheckBoxPass.AutoPostBack = True
            Me.CheckBoxUN.AutoPostBack = True
            Dim CheckCrypto As Crypto = New Crypto(Crypto.Providers.DES)
            Dim key As String = BaseClasses.Configuration.ApplicationSettings.Current.CookieEncryptionKey

            'isCancelled is set to true when cancel button is pressed
            Me.signInState.IsCancelled = False
            Me.signInState.UserName = (BaseClasses.Utils.NetUtils.GetCookie(NetUtils.CookieUserName()))

            'OriginalUserName and other Original... members of signInState keep original values which are used when 
            'Cancel button is pressed to set all cookies to their original values. That is necessary to do because
            'cookie are being modified when checkboxes are triggered.
            Me.signInState.OriginalUserName = Me.signInState.UserName
            If (Not (Me.signInState.UserName Is Nothing)) AndAlso Me.signInState.UserName.Trim <> "" Then
                Me.signInState.UserName = CheckCrypto.Decrypt(Me.signInState.UserName, key, System.Text.Encoding.Unicode, False)
            Else
                Me.signInState.UserName = ""
            End If
            Me.signInState.Password = (BaseClasses.Utils.NetUtils.GetCookie(NetUtils.CookiePassword()))
            Me.signInState.OriginalPassword = Me.signInState.Password
            If (Not (Me.signInState.Password Is Nothing)) AndAlso Me.signInState.Password.Trim <> "" Then
                Me.signInState.Password = CheckCrypto.Decrypt(Me.signInState.Password, key, System.Text.Encoding.Unicode, False)
            Else
                Me.signInState.Password = ""
            End If
            Dim rUser As String = (BaseClasses.Utils.NetUtils.GetCookie(NetUtils.CookieRememberName()))
            Me.signInState.OriginalRememberUser = rUser

            'Need to check if check boxes are set to visible in Application Generation Options. If not - do not show them and
            'set to false their values
            If StringUtils.InvariantLCase(BaseClasses.Configuration.ApplicationSettings.Current.ShowRememberUserCheckBox) = "false" Then
                Me.CheckBoxUN.Visible = False
                Me.CheckBoxUN.Enabled = False
                Me.CheckBoxUNLbl.Visible = False
                Me.CheckBoxUNLbl.Enabled = False
                Me.signInState.IsUNToRemember = False
            Else
                If (Not (rUser Is Nothing)) AndAlso (rUser.ToLower() = "true") Then
                    Me.signInState.IsUNToRemember = True
                Else
                    Me.signInState.IsUNToRemember = False
                End If

            End If

            Dim rPassword As String = (BaseClasses.Utils.NetUtils.GetCookie(NetUtils.CookieRememberPassword()))
            Me.signInState.OriginalRememberPassword = rPassword
            If StringUtils.InvariantLCase(BaseClasses.Configuration.ApplicationSettings.Current.ShowRememberPasswordCheckBox) = "false" Then

                Me.CheckBoxPass.Enabled = False
                Me.CheckBoxPass.Visible = False
                Me.CheckBoxPassLbl.Visible = False
                Me.CheckBoxPassLbl.Enabled = False
                Me.signInState.IsPassToRemember = False
            Else
                If Not (rPassword Is Nothing) AndAlso (rPassword.ToLower() = "true") Then
                    Me.signInState.IsPassToRemember = True
                Else
                    Me.signInState.IsPassToRemember = False
                End If
            End If

            If (Me.signInState.IsUNToRemember) Then
                If (Me.signInState.UserName <> "") Then
                    Me.CheckBoxUN.Checked = Me.signInState.IsUNToRemember
                    Me.UserName.Text = Me.signInState.UserName
                End If
            End If
            If (Me.signInState.Password <> "") Then
                Me.CheckBoxPass.Checked = Me.signInState.IsPassToRemember
                If (Me.Password.Text <> "**********" And Me.Password.Text.Trim <> "") Then
                    Me.signInState.Password = Me.Password.Text
                Else
                    Me.Password.Text = Me.signInState.Password
                End If
                Me.signInState.LoginPassword = Me.signInState.Password
                Password.Attributes.Add("value", "**********")
            ElseIf Me.Password.Text = "" Then
                Password.Attributes.Add("value", "")
                Me.signInState.LoginPassword = ""
            Else
                Me.signInState.LoginPassword = ""
            End If

            Dim isAutoLogin As String = BaseClasses.Utils.NetUtils.GetCookie(NetUtils.CookieAutoLogin())
            If StringUtils.InvariantLCase(BaseClasses.Configuration.ApplicationSettings.Current.ShowAutoSignInCheckBox) = "false" Then
                Me.CheckBoxAutoLogin.Visible = False
                Me.CheckBoxAutoLoginLbl.Visible = False
                Me.CheckBoxAutoLoginLbl.Enabled = False
                Me.CheckBoxAutoLogin.Enabled = False
                Me.signInState.IsAutoLogin = False
            End If

            'Get value of automatically login cookie, if not set AND security used is Active Directory, than use
            'default value which is True to allow user be automatically signed in with his current credentials
            If (isAutoLogin Is Nothing Or isAutoLogin = "") Then
                Select Case BaseClasses.Configuration.ApplicationSettings.Current.AuthenticationType
                    Case BaseClasses.Configuration.SecurityConstants.ActiveDirectorySecurity
                        BaseClasses.Utils.NetUtils.SetCookie(NetUtils.CookieAutoLogin(), "True")
                        isAutoLogin = "True"
                    Case BaseClasses.Configuration.SecurityConstants.ProprietorySecurity
                        BaseClasses.Utils.NetUtils.SetCookie(NetUtils.CookieAutoLogin(), "False")
                        isAutoLogin = "False"
                    Case BaseClasses.Configuration.SecurityConstants.None
                        BaseClasses.Utils.NetUtils.SetCookie(NetUtils.CookieAutoLogin(), "False")
                        isAutoLogin = "False"
                End Select
            End If

            If (isAutoLogin.ToLower = "true" And Me.signInState.IsAutoLogin) Then
                Me.CheckBoxAutoLogin.Checked = True
                If ((Not Me.signInState.IsUNToRemember) Or (Not Me.signInState.IsPassToRemember)) Then
                    Me.UserName.Text = ""
                    Password.Attributes.Add("value", "")
                    Me.signInState.LoginPassword = ""
                End If
                Me.Login(True)
            Else
                Me.CheckBoxAutoLogin.Checked = False
            End If

        End Sub

        Public Sub OnCloseWindow(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Unload
            If Me.signInState Is Nothing Then
                Me.signInState = New SignInState
            End If
            'Check if Cancel button clicked. If not and any "remember" box is unchecked, clear content
            If (Not Me.signInState.IsCancelled) Then
                If (Not Me.signInState.IsUNToRemember) Then
                    BaseClasses.Utils.NetUtils.SetCookie(NetUtils.CookieRememberName(), Boolean.FalseString)
                    BaseClasses.Utils.NetUtils.SetCookie(NetUtils.CookieUserName(), "")
                End If
                If (Not Me.signInState.IsPassToRemember) Then
                    BaseClasses.Utils.NetUtils.SetCookie(NetUtils.CookieRememberPassword(), Boolean.FalseString)
                    BaseClasses.Utils.NetUtils.SetCookie(NetUtils.CookiePassword(), "")
                End If
            End If
        End Sub
#End Region

    End Class

End Namespace