Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Collections
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.IO
Imports ModCommon
Partial Class Admin_reference_master
    Inherits System.Web.UI.Page
    Shared Search As Boolean
    
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            ' Dim con As New SqlConnection(System.Configuration.ConfigurationManager.AppSettings("ConnectionString"))
            ''If Session("AdminID") = Nothing Then
            '    Response.Redirect("AdminLogin.aspx")
            'End If
            If Session("AdminID") Is Nothing Then
                Response.Redirect("AdminLogin.aspx?sesn=expire")
                Exit Sub
            End If
            If (Not IsPostBack) Then        'If IsPostBack is false then
                If Session("AdminID") = Nothing Then
                    Response.Redirect("AdminLogin.aspx")
                End If
                ClearFields()               'Clear the TextFields
                UnLockTextBox(False)        'Unlock (Enable) TextFields
                g_Company = Session("g_Company").ToString
                g_FinYear = Session("g_FinYear").ToString()
                FillGrid("")                  'Fills the DatagGrid with All Records
                Call CancelClickVisible(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
                Search = False              'Default Value for Search Mode

                Call CheckRights(Me, Session("g_User"), "Bank Master")
            End If
            txtrefCode.MaxLength = 25 : txtrefName.MaxLength = 200
            'txtrefName.Attributes.Add("onblur", "return CheckNull('txtrefName');")
            'txtrefName.Attributes.Add("onkeypress", "return BlockNumericValue(event);")
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")
        End Try
        lblerror.Text = ""
    End Sub
    Protected Sub ClearFields()
        Try
            txtkid.Text = ""
            txtrefCode.Text = ""                           'Assign Null to the TextField
            txtrefName.Text = ""                           'Assign Null to the TextField
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")     'Display the Error Message
        End Try
    End Sub
    Protected Sub UnLockTextBox(ByVal Action As Boolean)
        Try

            txtrefName.Enabled = Action                    'Enable / Disable the TextField
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")     'Display the Error Message
        End Try
    End Sub
    Public Sub ShowMessage(ByVal strValue As String)
        lblError.Visible = True
        lblError.Text = strValue
    End Sub
    Protected Sub FillGrid(ByVal PTN As String)
        Try

            Dim qry As String                                   'Define a String Variable for Query
            Dim con As New SqlConnection                        'Define connection variable for connecting to SQL-Server
            con.ConnectionString = System.Configuration.ConfigurationManager.AppSettings("ConnectionString")    'Read the ConnectionString from web.config File
            con.Open()                                          'Open the Connection
            gvRef.Columns(1).Visible = True
            If Trim(PTN) = "" Then
                qry = "select distinct ReferenceM_Kid, ReferenceM_Code, ReferenceM_Name FROM  Reference_Master where ReferenceM_isdeleted='0' and ReferenceM_companyId='" & g_Company & "'"
            Else
                qry = "select distinct ReferenceM_Kid, ReferenceM_Code, ReferenceM_Name FROM  Reference_Master where ReferenceM_isdeleted='0' and ReferenceM_companyId='" & g_Company & "' and ReferenceM_name like '" & Trim(PTN) & "%'"
            End If
            Dim cmd As New SqlCommand(qry, con)                 'Define command variable to execute the query
            'Dim dr As SqlDataReader                             'Define DataReader variable for storing the output of the query
            'dr = cmd.ExecuteReader                              'Assign the output of query to DataReader variable
            Dim dt As New DataTable
            dt = ReturnDataTable(qry)
            gvRef.DataSource = dt                          'Set the DataReader Variable as DataSource for the Grid
            gvRef.DataBind()                               'Bind the Data to the Grid
            gvRef.Columns(1).Visible = False
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")     'Display the Error Message
        End Try
    End Sub

    Protected Sub BtnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnAdd.Click

        Try
            'If CBool(Session("Add_Flag").ToString) = False Then
            '    CreateMessageAlert(Me, "You Do Not Have Access Right To Add New Record !", "StrKeyVal")  'Display the Message 
            '    Exit Sub
            'End If
            ClearFields()                                       'Clears the TextFields
            UnLockTextBox(True)                                 'Enable the TextFields
            Call AddClickVisible(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
            txtrefName.Focus()
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")     'Display the Error Message
        End Try

    End Sub


    Protected Sub BtnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSave.Click
        Try
            GenerateBankCode()
            If txtrefCode.Text.Trim = "" Then
                CreateMessageAlert(Me, "The reference code can not be blank.", "strkeyval")
                Exit Sub
            ElseIf txtrefName.Text.Trim = "" Then
                CreateMessageAlert(Me, "The reference name can not be blank.", "strkeyval")
                Exit Sub
            Else

                If IsAlreadyPresent("select count(*) from Reference_master where ReferenceM_Code='" & txtrefCode.Text.Trim & "' and ReferenceM_Isdeleted='0' and company_code='" & g_Company & "'") Then
                    CreateMessageAlert(Me, " Reference Code Already Present.", "StrKeyVal")      'Display the Message
                    Exit Sub
                End If
                If IsAlreadyPresent("select count(*) from Reference_master where ReferenceM_Name='" & txtrefName.Text.Trim & "' and ReferenceM_Isdeleted='0' and company_code='" & g_Company & "'") Then
                    CreateMessageAlert(Me, " Reference Name Already Present.", "StrKeyVal")      'Display the Message
                    Exit Sub
                End If
                Dim con As New SqlConnection                                                    'Define connection variable for connecting to SQL-Server
                con.ConnectionString = ConfigurationManager.AppSettings("ConnectionString")    'Read the ConnectionString from web.config File
                con.Open()
                Dim cmd As New SqlCommand
                cmd.CommandType = CommandType.StoredProcedure
                cmd.CommandText = "Reference_Master_Proc"
                cmd.Connection = con
                cmd.Parameters.Add(New SqlParameter("@ReferenceM_Kid", SqlDbType.NVarChar, 10)).Value = RemoveLiterals(txtkid.Text.Trim) ' Genreate Kid
                cmd.Parameters.Add(New SqlParameter("@ReferenceM_Code", SqlDbType.NVarChar, 25)).Value = txtrefCode.Text.Trim 'Refe. Code
                cmd.Parameters.Add(New SqlParameter("@ReferenceM_Name", SqlDbType.NVarChar, 200)).Value = txtrefName.Text.Trim  ' Refe. Name
                cmd.Parameters.Add(New SqlParameter("@ReferenceM_CompanyId", SqlDbType.NVarChar, 10)).Value = Trim(Session("g_Company").ToString)       'Add Parameter Company_Code and assign the value of Session("g_Company") to it
                cmd.Parameters.Add(New SqlParameter("@ReferenceM_FinancialYearId", SqlDbType.NVarChar, 20)).Value = Session("g_FinYear").ToString().Trim
                cmd.Parameters.Add(New SqlParameter("@ReferenceM_UserId", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_User"))             'Add Parameter UserCode and assign the value of Session("Session("g_User")").toString to it
                cmd.Parameters.Add(New SqlParameter("@FormName", SqlDbType.NVarChar, 100)).Value = "Reference Master"
                cmd.Parameters.Add(New SqlParameter("@Mode", SqlDbType.VarChar, 50)).Value = "Insert"
                cmd.ExecuteNonQuery()
                FillGrid("")                                                                      'Fill the Grid
                ShowMessage("Record Save Successfully.")
                '  CreateMessageAlert(Me, "Record Save Successfully...", "StrKeyVal")             'Display the Message
                ClearFields()                                                                   'Clear the TextFields
                UnLockTextBox(False)                                                            'Disable the TextFields
                Call SaveClickVisible(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
            End If

        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")                                 'Display the Error Message
        End Try
    End Sub
    Protected Sub GenerateBankCode()
        Try
            Dim i As String
            Dim qry As String
            Dim code As String
            txtkid.Text = NewPrimaryKey(Me)
            i = "1"
            i = Format(Val(i), "000")
            While True
                code = "REF" & "/" & Year(Date.Today) & "/" & Format(Month(Date.Today), "00") & "/" & Day(Date.Today) & "/" & i
                qry = "select count(*) from Reference_Master where ReferenceM_Code='" & code & "'"
                If IsAlreadyPresent(qry) Then
                    i = Val(i) + 1
                    i = Format(Val(i), "000")
                Else
                    txtrefCode.Text = code
                    Exit Sub
                End If
            End While
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")     'Display the Error Message
        End Try
    End Sub

    Protected Sub BtnEdit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnEdit.Click
        Try
            Dim dt As Data.DataTable = getTable("select distinct ReferenceM_Kid, ReferenceM_Code, ReferenceM_Name FROM  Reference_Master where ReferenceM_Kid='" & RemoveLiterals(gvRef.SelectedDataKey.Value.ToString.Trim()) & "' and ReferenceM_isdeleted='0' and ReferenceM_companyId='" & g_Company & "'", "REF")
            If dt.Rows.Count > 0 Then
                txtrefCode.Text = dt.Rows(0).Item("ReferenceM_Code").ToString.Trim
                '  txtrefName.Text = dt.Rows(0).Item("ReferenceM_Name").ToString.Trim
                If txtrefCode.Text.Trim = "" Then
                    CreateMessageAlert(Me, "The reference code can not be blank.", "strkeyval")
                    Exit Sub
                ElseIf txtrefName.Text.Trim = "" Then
                    CreateMessageAlert(Me, "The reference name can not be blank.", "strkeyval")
                    Exit Sub
                Else

                    If IsAlreadyPresent("select count(*) from Reference_master where ReferenceM_Code='" & txtrefCode.Text.Trim & "' and ReferenceM_Name='" & txtrefName.Text.Trim & "' and ReferenceM_Isdeleted='0' and company_code='" & g_Company & "'") Then
                        CreateMessageAlert(Me, " Reference Code Already Present.", "StrKeyVal")      'Display the Message
                        Exit Sub
                    End If

                    Dim con As New SqlConnection                                                    'Define connection variable for connecting to SQL-Server
                    con.ConnectionString = ConfigurationManager.AppSettings("ConnectionString")    'Read the ConnectionString from web.config File
                    con.Open()
                    Dim cmd As New SqlCommand
                    cmd.CommandType = CommandType.StoredProcedure
                    cmd.CommandText = "Reference_Master_Proc"
                    cmd.Connection = con
                    cmd.Parameters.Add(New SqlParameter("@ReferenceM_Kid", SqlDbType.NVarChar, 10)).Value = RemoveLiterals(txtkid.Text.Trim) ' Genreate Kid
                    cmd.Parameters.Add(New SqlParameter("@ReferenceM_Code", SqlDbType.NVarChar, 25)).Value = txtrefCode.Text.Trim 'Refe. Code
                    cmd.Parameters.Add(New SqlParameter("@ReferenceM_Name", SqlDbType.NVarChar, 200)).Value = txtrefName.Text.Trim  ' Refe. Name
                    cmd.Parameters.Add(New SqlParameter("@ReferenceM_CompanyId", SqlDbType.NVarChar, 10)).Value = Trim(Session("g_Company").ToString)       'Add Parameter Company_Code and assign the value of Session("g_Company") to it
                    cmd.Parameters.Add(New SqlParameter("@ReferenceM_FinancialYearId", SqlDbType.NVarChar, 20)).Value = Session("g_FinYear").ToString().Trim
                    cmd.Parameters.Add(New SqlParameter("@ReferenceM_UserId", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_User"))             'Add Parameter UserCode and assign the value of Session("Session("g_User")").toString to it
                    cmd.Parameters.Add(New SqlParameter("@FormName", SqlDbType.NVarChar, 100)).Value = "Reference Master"
                    cmd.Parameters.Add(New SqlParameter("@Mode", SqlDbType.VarChar, 50)).Value = "Update"
                    cmd.ExecuteNonQuery()
                    FillGrid("")                                                                      'Fill the Grid
                    ShowMessage("Record Updated Successfully.")
                    ' CreateMessageAlert(Me, "Record Updated Successfully.", "StrKeyVal")             'Display the Message
                    ClearFields()                                                                   'Clear the TextFields
                    UnLockTextBox(False)                                                            'Disable the TextFields
                    Call EditClickVisible(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
                End If
            Else
                CreateMessageAlert(Me, "Record not found.", "StrKeyVal")
            End If
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")                                 'Display the Error Message
        End Try
       
    End Sub

    Protected Sub BtnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnDelete.Click
        Try
            Dim dt As Data.DataTable = getTable("select distinct ReferenceM_Kid, ReferenceM_Code, ReferenceM_Name FROM  Reference_Master where ReferenceM_Kid='" & RemoveLiterals(gvRef.SelectedDataKey.Value.ToString.Trim()) & "' and ReferenceM_isdeleted='0' and ReferenceM_companyId='" & g_Company & "'", "REF")
            If dt.Rows.Count > 0 Then
                txtrefCode.Text = dt.Rows(0).Item("ReferenceM_Code").ToString.Trim
                '  txtrefName.Text = dt.Rows(0).Item("ReferenceM_Name").ToString.Trim
                If txtrefCode.Text.Trim = "" Then
                    CreateMessageAlert(Me, "The reference code can not be blank.", "strkeyval")
                    Exit Sub
                ElseIf txtrefName.Text.Trim = "" Then
                    CreateMessageAlert(Me, "The reference name can not be blank.", "strkeyval")
                    Exit Sub
                Else

                    If IsAlreadyPresent("select count(*) from Reference_master where ReferenceM_Code='" & txtrefCode.Text.Trim & "' and ReferenceM_Name='" & txtrefName.Text.Trim & "' and ReferenceM_Isdeleted='0' and company_code='" & g_Company & "'") Then
                        CreateMessageAlert(Me, " Reference Code Already Present.", "StrKeyVal")      'Display the Message
                        Exit Sub
                    End If

                    Dim con As New SqlConnection                                                    'Define connection variable for connecting to SQL-Server
                    con.ConnectionString = ConfigurationManager.AppSettings("ConnectionString")    'Read the ConnectionString from web.config File
                    con.Open()
                    Dim cmd As New SqlCommand
                    cmd.CommandType = CommandType.StoredProcedure
                    cmd.CommandText = "Reference_Master_Proc"
                    cmd.Connection = con
                    cmd.Parameters.Add(New SqlParameter("@ReferenceM_Kid", SqlDbType.NVarChar, 10)).Value = RemoveLiterals(txtkid.Text.Trim) ' Genreate Kid
                    cmd.Parameters.Add(New SqlParameter("@ReferenceM_Code", SqlDbType.NVarChar, 25)).Value = txtrefCode.Text.Trim 'Refe. Code
                    cmd.Parameters.Add(New SqlParameter("@ReferenceM_Name", SqlDbType.NVarChar, 200)).Value = txtrefName.Text.Trim  ' Refe. Name
                    cmd.Parameters.Add(New SqlParameter("@ReferenceM_CompanyId", SqlDbType.NVarChar, 10)).Value = Trim(Session("g_Company").ToString)       'Add Parameter Company_Code and assign the value of Session("g_Company") to it
                    cmd.Parameters.Add(New SqlParameter("@ReferenceM_FinancialYearId", SqlDbType.NVarChar, 20)).Value = Session("g_FinYear").ToString().Trim
                    cmd.Parameters.Add(New SqlParameter("@ReferenceM_UserId", SqlDbType.NVarChar, 20)).Value = Trim(Session("g_User"))             'Add Parameter UserCode and assign the value of Session("Session("g_User")").toString to it
                    cmd.Parameters.Add(New SqlParameter("@FormName", SqlDbType.NVarChar, 100)).Value = "Reference Master"
                    cmd.Parameters.Add(New SqlParameter("@Mode", SqlDbType.VarChar, 50)).Value = "Delete"
                    cmd.ExecuteNonQuery()
                    FillGrid("")                                                                      'Fill the Grid
                    ShowMessage("Record Deleted Successfully.")
                    ' CreateMessageAlert(Me, "Record Updated Successfully.", "StrKeyVal")             'Display the Message
                    ClearFields()                                                                   'Clear the TextFields
                    UnLockTextBox(False)                                                            'Disable the TextFields
                    Call DeleteClickVisible(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
                End If
            Else
                CreateMessageAlert(Me, "Record not found.", "StrKeyVal")
            End If
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")                                 'Display the Error Message
        End Try

    End Sub

    Protected Sub BtnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnCancel.Click
        Call CancelClickVisible(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
        gvRef.SelectedIndex = -1
        ClearFields()
    End Sub

    Protected Sub BtnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSearch.Click
        Search = True
        txtrefName.Enabled = True
        txtrefName.AutoPostBack = True
        txtrefName.Focus()
        Call SearchClickVisible(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
        BtnSearch.Enabled = True
        If Search = True Then                               'If Search Mode is true then
            Call FillGrid(Trim(txtrefName.Text))  'Fill the Grid filtering on txtStockLocationName 
        End If
        If BtnSave.Enabled Then BtnSave.Focus()
    End Sub


    Protected Sub gvRef_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvRef.SelectedIndexChanged
        Try
            txtkid.Text = RemoveLiterals(gvRef.SelectedRow.Cells(1).Text.Trim)    'Assign the value of cell to the textField
            txtrefCode.Text = gvRef.SelectedRow.Cells(2).Text     'Assign the value of cell to the textField
            txtrefName.Text = gvRef.SelectedRow.Cells(3).Text     'Assign the value of cell to the textField
            UnLockTextBox(True)                                             'Enable the TextFields
            Call GridClickVisible(Me, BtnAdd, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
            Search = False
            txtrefName.Focus()
            
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")                 'Display the Error Message
        End Try
    End Sub

    
    Protected Sub gvRef_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gvRef.PageIndexChanging
        gvRef.PageIndex = e.NewPageIndex
        FillGrid("")
        gvRef.SelectedIndex = -1
        ClearFields()
    End Sub
End Class
