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 System.IO.FileStream
Imports ModCommon
Imports Ajax

Partial Class BrandMaster
    Inherits System.Web.UI.Page

    Shared Search As Boolean
    Shared g_User As String
    Shared g_Company As String
    Shared g_FinYear As String
    Shared str As String
    Public strPath As String
    Shared img As Integer
    Dim strImageName As String = ""
    Dim file_name As String = ""




    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            Ajax.Utility.RegisterTypeForAjax(GetType(BrandMaster))
            If Session("SupplierID") Is Nothing And Session("AdminID") = Nothing Then
                Response.Redirect("listproduct.aspx?sess=expire")
                Exit Sub
            End If
            If (Not IsPostBack) Then        'If IsPostBack is false then
                If Session("SupplierID") Is Nothing Then
                    Response.Redirect("listProduct.aspx")
                    Exit Sub
                End If

                ClearFields()               'Clear the TextFields
                UnLockTextBox(False)        'Unlock (Enable) TextFields

                g_User = Session("g_User").ToString
                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, g_User, "Brand Master")
                img = 0

            End If
            txtBrandCode.MaxLength = 20 : txtBrandName.MaxLength = 50
            txtBrandName.Attributes.Add("onblur", "return CheckNull('txtBrandName');")
            txtBrandName.Attributes.Add("onkeypress", "return BlockNumericValue(event);")
            BrandFileUpload.Attributes.Add("onblur", "return  CheckNull('File1');")
            BtnEdit.Attributes.Add("onclick", "return CheckUpdateBrand('" & Session("SupplierID") & "');")
            BtnDelete.Attributes.Add("onclick", "return CheckDeleteBrand('" & Session("SupplierID") & "');")
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")
        End Try
    End Sub

    Protected Sub _Default_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init

        If Not IsValidConnectionString() Then CreateMessageAlert(Me, "Check the Connection String !", "StrKeyVal") 'If not a valid ConnectionString then Display the message 

    End Sub

       Protected Sub ClearFields()
        Try
            txtBrandId.Text = ""
            txtBrandCode.Text = ""                           'Assign Null to the TextField
            txtBrandName.Text = ""                           'Assign Null to the TextField
            BrandImage.ImageUrl = ""

        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
            txtBrandName.Enabled = Action
            BrandFileUpload.Enabled = Action
         

        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")
        End Try
    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
            Dim strSupID As String
            strSupID = RemoveLiterals(Session("SupplierID").ToString)
            If strSupID.Contains("[") Then
                strSupID = strSupID.Replace("[", "[[]")
            ElseIf strSupID.Contains("]") Then
                strSupID = strSupID.Replace("]", "[]]")
            End If

            ' Fill_Combo("Select Brand_Kid, Brand_Name From Brand_Master where Brand_IsDeleted = '0' and Brand_CompanyId like '%" & strSupID & "%'  order by Brand_Name", ddlBrandName)
            If Trim(PTN) = "" Then
                qry = "SELECT     Brand_Kid, Brand_Code AS Code, Brand_Name AS Brand, Brand_Image AS Image   FROM Brand_Master WHERE Brand_IsDeleted = '0' AND Brand_CompanyId LIKE '%" & RemoveLiterals(strSupID) & "%' ORDER BY Brand"
            Else
                qry = "SELECT     Brand_Kid, Brand_Code AS Code, Brand_Name AS Brand, Brand_Image AS Image   FROM Brand_Master WHERE Brand_IsDeleted = '0' AND Brand_CompanyId LIKE '%" & RemoveLiterals(strSupID) & "%' AND Brand_name like '" & Trim(PTN) & "%' ORDER BY Brand"
            End If

            gvBrand.Columns(1).Visible = True
            gvBrand.Columns(2).Visible = True
            gvBrand.Columns(5).Visible = True
            Dim cmd As New SqlCommand(qry, con)                 'Define command variable to execute the query

            Dim dt As New DataTable
            dt = ReturnDataTable(qry)
            gvBrand.DataSource = dt                          'Set the DataReader Variable as DataSource for the Grid
            gvBrand.DataBind()                               'Bind the Data to the Grid
            gvBrand.Columns(1).Visible = False
            gvBrand.Columns(2).Visible = False
            gvBrand.Columns(5).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
           
            ClearFields()                                       'Clears the TextFields
            UnLockTextBox(True)                                 'Enable the TextFields
            Call AddClickVisible(Me, btnADD, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
            Call GenerateBrandCode()
            txtBrandName.Focus()
            BtnSave.Attributes.Add("onclick", "return CheckProductBrand('" & Session("SupplierID") & "');")
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")     'Display the Error Message
        End Try
    End Sub

    Protected Sub gvBrand_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvBrand.RowDataBound
        Try
            If e.Row.RowType = DataControlRowType.DataRow Then
                Dim Pimg As Image
                Pimg = CType(e.Row.Cells(4).FindControl("Image1"), Image)
                Pimg.ImageUrl = CType(e.Row.Cells(5).FindControl("lblImageUrl"), Label).Text.ToString
                Dim imgpath As String
                imgpath = Server.MapPath(Pimg.ImageUrl)
                KeepAspectRatioNew(Pimg, imgpath, 40, 30)
            End If
            If e.Row.RowType = DataControlRowType.Footer Then
                e.Row.Cells(3).Text = "Page " & (gvBrand.PageIndex + 1) & " of " & gvBrand.PageCount

            End If
        Catch ex As Exception

        End Try
    End Sub

    Protected Sub gvBrand_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvBrand.SelectedIndexChanged
        Try
            txtBrandId.Text = RemoveLiterals(gvBrand.SelectedRow.Cells(1).Text)     'Assign the value of cell to the textField
            txtBrandCode.Text = gvBrand.SelectedRow.Cells(2).Text   'Assign the value of cell to the textField
            txtBrandName.Text = gvBrand.SelectedRow.Cells(3).Text   'Assign the value of cell to the textField
            hfkid.Value = RemoveLiterals(gvBrand.SelectedRow.Cells(1).Text)
            BrandImage.ImageUrl = CType(gvBrand.SelectedRow.FindControl("lblImageUrl"), Label).Text 'Assign the value of cell to the textField 
            Dim imgpath As String
            imgpath = Server.MapPath(BrandImage.ImageUrl)
            KeepAspectRatioNew(BrandImage, imgpath, 50, 40)
            UnLockTextBox(True)                                         'Enable the TextFields
            Call GridClickVisible(Me, btnADD, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
            Search = False
            txtBrandName.Focus()
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")                 'Display the Error Message
        End Try
    End Sub
    <Ajax.AjaxMethod()> _
   Public Function CheckExistingBrand(ByVal btext As String, ByVal supid As String) As Boolean

        If IsAlreadyPresent("Select count(*) from Brand_Master where Brand_companyId like '%" & RemoveLiterals(supid) & "%' and Brand_Name='" & btext.Trim & "' and Brand_IsDeleted='0'") Then
            Return False
        End If
        Return True

    End Function
    'Protected Sub CheckBrand()
    '    Try
    '        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
    '        Dim present As DataTable
    '        Dim dt_brand As DataTable
    '        present = ReturnDataTable("select Brand_Kid,Brand_Code,Brand_Image,Brand_CompanyId from Brand_Master where Brand_companyId like '%" & RemoveLiterals(Session("SupplierID")) & "%' and Brand_Name='" & txtBrandName.Text.Trim & "' and Brand_IsDeleted='0'")
    '        If present.Rows.Count <> 0 Then

    '            If flag = "S" Then
    '                If present.Rows(0).Item("Brand_CompanyId").ToString.Contains(Session("SupplierID")) Then
    '                    CreateMessageAlert(Me, "Brand is Already Added", "strkeyVal")
    '                    txtBrandName.Text = ""
    '                    Exit Sub
    '                End If
    '            End If

    '            If flag = "U" Then

    '                Dim supid1 As String = present.Rows(0).Item("Brand_CompanyID").ToString
    '                Dim arr1 = Split(supid1, "-")
    '                If arr1.Length > 1 Then
    '                    CreateMessageAlert(Me, "You Can Not Update this Brand. Other Suppliers also has this Brand.", "strkeyVal")
    '                    txtBrandName.Text = ""
    '                    Exit Sub
    '                Else
    '                    InsertUpdateBrandName("Update", present.Rows(0).Item("Brand_Kid").ToString, present.Rows(0).Item("Brand_CompanyId").ToString, txtBrandCode.Text.Trim, strImageName)
    '                    Exit Sub
    '                End If
    '            End If


    '        Else
    '            Dim pr_old As DataTable = ReturnDataTable("Select Brand_Kid,Brand_Code,Brand_CompanyId,Brand_Image from Brand_Master where Brand_Name = '" & txtBrandName.Text.Trim & "' and Brand_IsDeleted='0'")
    '            If pr_old.Rows.Count <> 0 Then
    '                Dim res As Integer = MsgBox("Brand Name Already Added by Other Supplier. Still You want to Add ?", MsgBoxStyle.YesNo, "Brand Name")
    '                If res = MsgBoxResult.Yes Then
    '                    InsertUpdateBrandName("Update", pr_old.Rows(0).Item("Brand_Kid").ToString, pr_old.Rows(0).Item("Brand_CompanyID").ToString & "-" & RemoveLiterals(Session("SupplierId")), pr_old.Rows(0).Item("Brand_Code").ToString, pr_old.Rows(0).Item("Brand_Image").ToString)
    '                    Exit Sub
    '                End If
    '            End If

    '            dt_brand = ReturnDataTable("Select Brand_Kid,Brand_Code,Brand_Image,Brand_CompanyId from Brand_Master where Brand_IsDeleted='0' and Brand_KId ='" & RemoveLiterals(txtBrandId.Text.Trim) & "'")
    '            If dt_brand.Rows.Count <> 0 Then
    '                Dim supid As String = dt_brand.Rows(0).Item("Brand_CompanyID").ToString

    '                Dim arr = Split(supid, "-")
    '                If arr.Length > 1 Then
    '                    CreateMessageAlert(Me, "You Can Not Update this Brand. Other Suppliers also has this Brand.", "strkeyVal")
    '                    txtBrandName.Text = ""
    '                    Exit Sub
    '                Else
    '                    If RemoveLiterals(supid) = RemoveLiterals(Session("SupplierID")) Then
    '                        InsertUpdateBrandName("Update", dt_brand.Rows(0).Item("Brand_Kid").ToString, RemoveLiterals(supid), txtBrandCode.Text.Trim, strImageName)
    '                        txtBrandName.Text = ""
    '                        Exit Sub
    '                    End If

    '                End If
    '            Else
    '                ''If dt_brand.Rows(0).Item("Brand_CompanyId").ToString.Contains(Session("SupplierID")) Then
    '                ''    CreateMessageAlert(Me, "Brand is Already Added", "strkeyVal")
    '                ''    txtBrandName.Text = ""
    '                ''    Exit Sub
    '                ''Else

    '                ''Dim res As Integer = MsgBox("Brand Name Already Added by Other Supplier. Still You want to Add ?", MsgBoxStyle.YesNo, "Brand Name")
    '                ''If res = MsgBoxResult.Yes Then
    '                ''    InsertUpdateBrandName("Update", dt_brand.Rows(0).Item("Brand_Kid").ToString, dt_brand.Rows(0).Item("Brand_CompanyID").ToString, txtBrandCode.Text.Trim, strImageName)
    '                ''    Exit Sub
    '                ''End If

    '                ' '' End If

    '            End If
    '            InsertUpdateBrandName("Insert", txtBrandId.Text.Trim, Session("SupplierID"), txtBrandCode.Text.Trim, strImageName)
    '        End If

    '    Catch ex As Exception
    '    End Try

    'End Sub

    Protected Sub InsertUpdateBrandName(ByVal mode As String, ByVal BrName As String, ByVal kid As String, ByVal supid As String, ByVal bcode As String, ByVal b_img As String)

        Try

            Dim cmd As New Data.SqlClient.SqlCommand()
            Dim sqlcoll As Data.SqlClient.SqlParameterCollection = cmd.Parameters
            sqlcoll.Clear()

            If mode = "Insert" Then

                sqlcoll.Add("@Brand_Kid", Data.SqlDbType.NVarChar, 20).Value = RemoveLiterals(kid)
                sqlcoll.Add("@Brand_Code", Data.SqlDbType.NVarChar, 25).Value = bcode
                sqlcoll.Add("@Brand_Name", Data.SqlDbType.NVarChar, 100).Value = BrName.Trim
                sqlcoll.Add("@Brand_Image", Data.SqlDbType.NVarChar, 100).Value = b_img
                sqlcoll.Add("@Brand_FinancialYearID", Data.SqlDbType.NVarChar, 20).Value = Session("g_FinYear")
                sqlcoll.Add("@Brand_CompanyId", Data.SqlDbType.NVarChar).Value = Session("SupplierID")
                sqlcoll.Add("@Brand_UserId", Data.SqlDbType.NVarChar, 20).Value = Session("g_User")
                sqlcoll.Add("@FormName", Data.SqlDbType.NVarChar, 50).Value = "BrandMaster"
                sqlcoll.Add("@Mode", Data.SqlDbType.Char, 50).Value = "Insert"
                ExecQuery("Brand_Master_Proc", sqlcoll)
                CreateMessageAlert(Me, "Record Saved Successfully...", "StrKeyVal")             'Display the Message
            Else
                sqlcoll.Add("@Brand_Kid", Data.SqlDbType.NVarChar, 20).Value = RemoveLiterals(kid)
                sqlcoll.Add("@Brand_Code", Data.SqlDbType.NVarChar, 25).Value = bcode
                sqlcoll.Add("@Brand_Name", Data.SqlDbType.NVarChar, 100).Value = BrName.Trim
                sqlcoll.Add("@Brand_Image", Data.SqlDbType.NVarChar, 100).Value = b_img
                sqlcoll.Add("@Brand_FinancialYearID", Data.SqlDbType.NVarChar, 20).Value = Session("g_FinYear")
                sqlcoll.Add("@Brand_CompanyId", Data.SqlDbType.NVarChar, 500).Value = supid
                sqlcoll.Add("@Brand_UserId", Data.SqlDbType.NVarChar, 20).Value = Session("g_User")
                sqlcoll.Add("@FormName", Data.SqlDbType.NVarChar, 50).Value = "BrandMaster"
                sqlcoll.Add("@Mode", Data.SqlDbType.Char, 50).Value = "Update"
                ExecQuery("Brand_Master_Proc", sqlcoll)
                CreateMessageAlert(Me, "Record Modified Successfully...", "StrKeyVal")         'Display the Message
            End If
        Catch ex As Exception

        End Try
    End Sub

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSave.Click
        Try

            If Trim(txtBrandCode.Text) = "" Then                                         'If txtPartTypeCode TextField is Null then
                CreateMessageAlert(Me, "Brand Code Cannot be Null !", "StrKeyVal")      'Display the Message 
                Exit Sub
            End If
            If Trim(txtBrandName.Text) = "" Then                                         'If txtPartTypeName TextField is Null then
                CreateMessageAlert(Me, "Brand Name Cannot be Null !", "StrKeyVal")      'Display the Message
                Exit Sub
            End If

            If IsAlreadyPresent("select count(*) from Brand_Master where brand_code!='" & Trim(txtBrandCode.Text) & "' and  Brand_Name='" & txtBrandName.Text.Trim & "'  and Brand_isdeleted='0' and Brand_companyId like '%" & RemoveLiterals(Session("SupplierID")) & "%'") Then  ' To Check Existance of Engineer Code
                CreateMessageAlert(Me, " Brand Name Already Present !", "StrKeyVal")      'Display the Message
                txtBrandName.Text = "" : txtBrandName.Focus()
                Exit Sub
            End If
            If (BrandFileUpload.HasFile) Then
                Dim fileType As String = Path.GetExtension(BrandFileUpload.FileName)
                If fileType = ".gif" Or fileType = ".png" Or fileType = ".jpg" Or fileType = ".jpeg" Or fileType = ".bmp" Then
                    strImageName = Final_FileUpload(BrandFileUpload, img, Server.MapPath("~\Upload Image\Brand_Image\"))
                    lblMsg.Visible = False
                    'strImageName = Server.MapPath("~/Upload Image/Product Image/UploadImages/")
                    'file_name = Fileupload(ProRevwFileUpload, img, strImageName) 'Replace Final_FileUpload() function to Fileuload() by Pankaj mishra
                Else
                    lblMsg.Visible = True
                    lblMsg.Text = "Please Select image File Only!"
                    BrandFileUpload.Focus()
                    Exit Sub
                End If
            End If

            '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


            ''If IsAlreadyPresent("select count(*) from Brand_Master where Brand_Name='" & txtBrandName.Text.Trim & "'and Brand_isdeleted='0' and Brand_companyId like '%" & RemoveLiterals(Session("SupplierID")) & "%'") Then  ' To Check Existance of Engineer Code
            ''    CreateMessageAlert(Me, " Brand Name Already Present !", "StrKeyVal")      'Display the Message
            ''    txtBrandName.Text = "" : txtBrandName.Focus()
            ''    Exit Sub
            ''End If


            ''Dim cmd As New SqlCommand                                                       'Define command variable to execute the query
            ''cmd.CommandType = CommandType.StoredProcedure                                   'Set the Command Type to Stored procedure
            ''cmd.CommandText = "Brand_Master_Proc"                                        'Assign the Name of Stored Procedure, to Execute
            ''cmd.Connection = con                                                            'Assign the connection
            ''cmd.Parameters.Add(New SqlParameter("@Brand_Kid", SqlDbType.NVarChar, 20)).Value = Trim(RemoveLiterals(txtBrandId.Text))     'Add Parameter Banke_Kid and assign the value  to it
            ''cmd.Parameters.Add(New SqlParameter("@Brand_Code", SqlDbType.NVarChar, 20)).Value = Trim(txtBrandCode.Text)       'Add Parameter Banke_Code and assign the value of txtBrandCode TextField to it
            ''cmd.Parameters.Add(New SqlParameter("@Brand_Name", SqlDbType.NVarChar, 100)).Value = Trim(txtBrandName.Text)       'Add Parameter Bank_Name and assign the value of txtBrandName TextField to it
            ''cmd.Parameters.Add(New SqlParameter("@Brand_Image", SqlDbType.NVarChar, 100)).Value = Trim(strImageName)       'Add Parameter Bank_Image and assign the value of txtBrandImage TextField to it
            ''cmd.Parameters.Add(New SqlParameter("@Brand_FinancialYearID", SqlDbType.NVarChar, 20)).Value = Trim(g_FinYear)       'Add Parameter Company_Code and assign the value of Session("g_Company") to it
            ''cmd.Parameters.Add(New SqlParameter("@Brand_CompanyId", SqlDbType.NVarChar, 500)).Value = Trim(Session("SupplierID"))       'Add Parameter Company_Code and assign the value of Session("g_Company") to it
            ''cmd.Parameters.Add(New SqlParameter("@Brand_UserId", SqlDbType.NVarChar, 20)).Value = Trim(g_User)             'Add Parameter UserCode and assign the value of Session("g_User").toString to it
            ''cmd.Parameters.Add(New SqlParameter("@FormName", SqlDbType.NVarChar, 100)).Value = "Brand Master"                           'Add Parameter FormName and assign the name of form to it
            ''cmd.Parameters.Add(New SqlParameter("@Mode", SqlDbType.VarChar, 50)).Value = "Insert"                                   'Add Parameter Mode and assign the DML Operation to Execute (Insert)
            ''cmd.ExecuteNonQuery()                                                           'Execute the Query
            ''flag = "S"
            '' CheckBrand()        'check the brand and insert record

            InsertBrand()
            FillGrid("")                                                                      'Fill the Grid
            ClearFields()                                                                   'Clear the TextFields
            UnLockTextBox(False)                                                            'Disable the TextFields
            Call SaveClickVisible(Me, btnADD, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
            gvBrand.SelectedIndex = -1
        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

            If Trim(txtBrandName.Text) = "" Then                                         'If txtPartTypeName TextField is Null then
                CreateMessageAlert(Me, "Brand Name Cannot be Null !", "StrKeyVal")      'Display the Message 
                Exit Sub
            End If

            If IsAlreadyPresent("select count(*) from Brand_Master where brand_code!='" & Trim(txtBrandCode.Text) & "' and  Brand_Name='" & txtBrandName.Text.Trim & "'  and Brand_isdeleted='0' and Brand_companyId like '%" & RemoveLiterals(Session("SupplierID")) & "%'") Then  ' To Check Existance of Engineer Code
                CreateMessageAlert(Me, " Brand Name Already Present !", "StrKeyVal")      'Display the Message
                txtBrandName.Text = "" : txtBrandName.Focus()
                Exit Sub
            End If


            If (BrandFileUpload.HasFile) Then
                Dim fileType As String = Path.GetExtension(BrandFileUpload.FileName)
                If fileType = ".gif" Or fileType = ".png" Or fileType = ".jpg" Or fileType = ".jpeg" Or fileType = ".bmp" Then
                    strImageName = Final_FileUpload(BrandFileUpload, img, Server.MapPath("~\Upload Image\Brand_Image\"))
                    lblMsg.Visible = False
                    'strImageName = Server.MapPath("~/Upload Image/Product Image/UploadImages/")
                    'file_name = Fileupload(ProRevwFileUpload, img, strImageName) 'Replace Final_FileUpload() function to Fileuload() by Pankaj mishra
                Else
                    lblMsg.Visible = True
                    lblMsg.Text = "Please Select image File Only!"
                    BrandFileUpload.Focus()
                    Exit Sub
                End If
            Else
                strImageName = ReturnValue("Select Brand_Image from Brand_Master where Brand_Kid = '" & RemoveLiterals(txtBrandId.Text.Trim) & "' and Brand_IsDeleted = '0'")
            End If
            ''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
            ''Dim cmd As New SqlCommand                                                       'Define command variable to execute the query
            ''cmd.CommandType = CommandType.StoredProcedure                                   'Set the Command Type to Stored procedure
            ''cmd.CommandText = "Brand_Master_Proc"                                        'Assign the Name of Stored Procedure, to Execute
            ''cmd.Connection = con                                                            'Assign the connection
            ''cmd.Parameters.Add(New SqlParameter("@Brand_Kid", SqlDbType.NVarChar, 10)).Value = Trim(RemoveLiterals(txtBrandId.Text))       'Add Parameter Brand_Kid and assign the value of txtBrandId TextField  to it
            ''cmd.Parameters.Add(New SqlParameter("@Brand_Code", SqlDbType.NVarChar, 25)).Value = Trim(txtBrandCode.Text)       'Add Parameter Brand_Code and assign the value of txtBrandCode TextField to it
            ''cmd.Parameters.Add(New SqlParameter("@Brand_Name", SqlDbType.NVarChar, 100)).Value = Trim(txtBrandName.Text)       'Add Parameter Brand_Name and assign the value oftxtBrandName TextField to it
            ''cmd.Parameters.Add(New SqlParameter("@Brand_Image", SqlDbType.NVarChar, 100)).Value = Trim(strImageName)       'Add Parameter Bank_Image and assign the value of txtBrandImage TextField to it
            ''cmd.Parameters.Add(New SqlParameter("@Brand_FinancialYearID", SqlDbType.NVarChar, 20)).Value = Trim(g_FinYear)       'Add Parameter Company_Code and assign the value of Session("g_Company") to it
            ''cmd.Parameters.Add(New SqlParameter("@Brand_CompanyId", SqlDbType.NVarChar, 500)).Value = Trim(Session("SupplierID"))       'Add Parameter Company_Code and assign the value of Session("g_Company") to it
            ''cmd.Parameters.Add(New SqlParameter("@Brand_UserId", SqlDbType.NVarChar, 10)).Value = Trim(g_User)             'Add Parameter UserCode and assign the value of Session("g_User").toString to it
            ''cmd.Parameters.Add(New SqlParameter("@FormName", SqlDbType.NVarChar, 100)).Value = "Brand Master"
            ''cmd.Parameters.Add(New SqlParameter("@Mode", SqlDbType.VarChar, 50)).Value = "Update"                                   'Add Parameter Mode and assign the DML Operation to Execute (Update)
            ''cmd.ExecuteNonQuery()                                                           'Execute the Query
            ''flag = "U"
            '' CheckBrand()

            UpdateBrand()
            FillGrid("")
            BrandImage.ImageUrl = ""
            ClearFields()                                                                   'Clear the TextFields
            UnLockTextBox(False)                                                            'Disable the TextFields
            Call EditClickVisible(Me, btnADD, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
            gvBrand.SelectedIndex = -1
        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
            If Trim(txtBrandCode.Text) = "" Then                                         'If txtPartTypeCode TextField is Null then
                CreateMessageAlert(Me, "Brand Code Cannot be Null !", "StrKeyVal")      'Display the Message 
                txtBrandCode.Focus()
                Exit Sub
            End If
            If Trim(txtBrandName.Text) = "" Then                                         'If txtPartTypeName TextField is Null then
                CreateMessageAlert(Me, "Brand Name Cannot be Null !", "StrKeyVal")      'Display the Message 
                txtBrandName.Focus()
                Exit Sub
            End If

            Dim dt_brand As DataTable = ReturnDataTable("Select Brand_Kid,Brand_Code,Brand_Image,Brand_CompanyId from Brand_Master where Brand_IsDeleted='0' and Brand_KId ='" & RemoveLiterals(txtBrandId.Text.Trim) & "'")
            If dt_brand.Rows.Count <> 0 Then
                Dim supid As String = dt_brand.Rows(0).Item("Brand_CompanyID").ToString
                Dim arr = Split(supid, "-")
                If arr.Length > 1 Then
                    CreateMessageAlert(Me, "You Can Not Delete this Brand. Other Suppliers also has this Brand.", "strkeyVal")
                    ClearFields()                                                                   'Clear the TextFields
                    UnLockTextBox(False)                                                            'Disable the TextFields
                    Call DeleteClickVisible(Me, btnADD, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
                    gvBrand.SelectedIndex = -1
                    Exit Sub
                End If
            End If


            'If IsAlreadyPresent("select count(*) from Brand_Master where Brand_Code='" & txtBrandCode.Text.Trim & "'and Brand_isdeleted='0' and Brand_companyId='" & g_Company & "'") Then  ' To Check Existance of Engineer Code
            '    CreateMessageAlert(Me, " Unable to Delete, Referenced to Other Records... !", "StrKeyVal")      'Display the Message
            '    btnCancel_Click(sender, e)
            '    Exit Sub
            'End If
            Dim strImageName As String = ReturnValue("Select Brand_Image from Brand_Master where Brand_Kid = '" & RemoveLiterals(txtBrandId.Text.Trim) & "' and Brand_IsDeleted = '0'")
            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
            Dim cmd As New SqlCommand                                                       'Define command variable to execute the query
            cmd.CommandType = CommandType.StoredProcedure                                   'Set the Command Type to Stored procedure
            cmd.CommandText = "Brand_Master_Proc"                                        'Assign the Name of Stored Procedure, to Execute
            cmd.Connection = con                                                            'Assign the connection

            cmd.Parameters.Add(New SqlParameter("@Brand_Kid", SqlDbType.NVarChar, 20)).Value = Trim(RemoveLiterals(txtBrandId.Text))       'Add Parameter Brand_Kid and assign the value of  txtBrandId TextField  to it
            cmd.Parameters.Add(New SqlParameter("@Brand_Code", SqlDbType.NVarChar, 25)).Value = Trim(txtBrandCode.Text)       'Add Parameter Brand_Code and assign the value of txtBrandCode TextField to it
            cmd.Parameters.Add(New SqlParameter("@Brand_Name", SqlDbType.NVarChar, 100)).Value = Trim(txtBrandName.Text)       'Add Parameter Brand_Name and assign the value of txtBrandName TextField to it
            cmd.Parameters.Add(New SqlParameter("@Brand_Image", SqlDbType.NVarChar, 100)).Value = Trim(strImageName)       'Add Parameter Brand_Image and assign the value of txtBrandImage TextField to it
            cmd.Parameters.Add(New SqlParameter("@Brand_FinancialYearID", SqlDbType.NVarChar, 20)).Value = Trim(g_FinYear)       'Add Parameter Company_Code and assign the value of Session("g_Company") to it
            cmd.Parameters.Add(New SqlParameter("@Brand_CompanyId", SqlDbType.NVarChar, 500)).Value = Trim(Session("SupplierID"))       'Add Parameter Company_Code and assign the value of Session("g_Company") to it
            cmd.Parameters.Add(New SqlParameter("@Brand_UserId", SqlDbType.NVarChar, 20)).Value = Trim(g_User)             'Add Parameter UserCode and assign the value of Session("g_User").toString to it
            cmd.Parameters.Add(New SqlParameter("@FormName", SqlDbType.NVarChar, 100)).Value = "Brand Master"
            cmd.Parameters.Add(New SqlParameter("@Mode", SqlDbType.VarChar, 50)).Value = "Delete"                                   'Add Parameter Mode and assign the DML Operation to Execute (Delete)
            cmd.ExecuteNonQuery()                                                           'Execute the Query
            FillGrid("")                                                                      'Fill the Grid
            BrandImage.ImageUrl = ""
            CreateMessageAlert(Me, "Record Deleted Successfully...", "StrKeyVal")             'Display the Message
            ClearFields()                                                                   'Clear the TextFields
            UnLockTextBox(False)                                                            'Disable the TextFields
            Call DeleteClickVisible(Me, btnADD, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
            gvBrand.SelectedIndex = -1
        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
        Try
            ClearFields()                                       'Clears the TextFields
            UnLockTextBox(False)                                'Disable the TextFields
            Search = False
            txtBrandName.AutoPostBack = False
            Call FillGrid("")
            Call CancelClickVisible(Me, btnADD, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
            gvBrand.SelectedIndex = -1
        Catch ex As Exception
            CreateMessageAlert(Me, ex.Message, "StrKeyVal")     'Display the Error Message
        End Try
    End Sub

    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSearch.Click
        Search = True                                       'Set Search Mode True
        Call SearchClickVisible(Me, btnADD, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)
        txtBrandName.Enabled = True
        txtBrandName.AutoPostBack = True
        txtBrandName.Focus()                             'Set Focus to txtPartTypeName TextField
    End Sub

    Protected Sub txtBrandName_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtBrandName.TextChanged
        'If Search = True Then                               'If Search Mode is true then
        Call FillGrid(Trim(txtBrandName.Text))  'Fill the Grid filtering on txtStockLocationName 
        'Call FillGrid(Trim(txtBrandImage.Text)) 'Fill the Grid filtering on txtStockLocationName  
        ' End If
        If BtnSave.Enabled Then BtnSave.Focus()
    End Sub
    Protected Sub GenerateBrandCode()
        Try
            Dim i As String
            Dim qry As String
            Dim code As String
            txtBrandId.Text = NewPrimaryKey(Me)
            hfid.Value = txtBrandId.Text
            i = "1"
            i = Format(Val(i), "000")
            While True
                code = "BND" & "/" & Year(Date.Today) & "/" & Format(Month(Date.Today), "00") & "/" & Day(Date.Today) & "/" & i
                qry = "select count(*) from Brand_Master where Brand_Code='" & code & "'"
                If IsAlreadyPresent(qry) Then
                    i = Val(i) + 1
                    i = Format(Val(i), "000")
                Else
                    txtBrandCode.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
    'Private Function UploadBrandImage() As String
    '    Dim strFileName2 As String
    '    Dim strFileName As String
    '    Dim strr As String
    '    strFileName = Mid(File1.PostedFile.FileName.ToString, File1.PostedFile.FileName.ToString.LastIndexOf("\") + 2, Len(File1.PostedFile.FileName.ToString))
    '    strr = strFileName.Substring(strFileName.LastIndexOf(".") + 1)
    '    If String.Compare(strr, "jpg", False) = 0 Then
    '        strPath = Server.MapPath("~\Upload Image\Brand_Image\")
    '        '-----Calling a function from the class file-------------
    '        strFileName2 = IsUploadImageAlreadyPersent.FileExists(strFileName, strPath)
    '        If strFileName2 <> "" Then
    '            File1.PostedFile.SaveAs(Server.MapPath("~\Upload Image\Brand_Image\") & strFileName2)
    '            UploadBrandImage = strFileName2
    '        End If
    '    End If
    'End Function

    Protected Sub gvBrand_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gvBrand.PageIndexChanging
        gvBrand.PageIndex = e.NewPageIndex
        FillGrid("")
        gvBrand.SelectedIndex = -1
        ClearFields()
        Call CancelClickVisible(Me, btnADD, BtnSave, BtnEdit, BtnDelete, BtnCancel, BtnSearch)

    End Sub

    <Ajax.AjaxMethod()> _
       Public Function CheckExistingName(ByVal txtname As String, ByVal txtkid As String) As Boolean
        Dim nm As String = ReturnValue("Select Brand_Kid from Brand_Master where Brand_Name='" & txtname.Trim & "' and Brand_IsDeleted='0' and Brand_Kid <>'" & RemoveLiterals(txtkid.Trim) & "'")
        If nm = "" Then
            Return True
        Else
            Return False
        End If
    End Function

    <Ajax.AjaxMethod()> _
            Public Function CheckExistingSupplier(ByVal btext As String, ByVal supid As String) As Boolean
        If IsAlreadyPresent("Select count(*) from Brand_Master where Brand_Name='" & btext & "'and Brand_CompanyId like '%" & RemoveLiterals(supid) & "%' and Brand_IsDeleted='0'") Then
            Return False
        End If
        Return True
    End Function

    <Ajax.AjaxMethod()> _
       Public Function CheckExistingBrandUpdate(ByVal bkid As String) As Boolean
        Dim dt_brand As DataTable = ReturnDataTable("Select Brand_Kid,Brand_Code,Brand_Image,Brand_CompanyId from Brand_Master where Brand_IsDeleted='0' and Brand_KId ='" & RemoveLiterals(bkid.Trim) & "'")
        If dt_brand.Rows.Count <> 0 Then
            Dim supid As String = dt_brand.Rows(0).Item("Brand_CompanyID").ToString

            Dim arr = Split(supid, "-")
            If arr.Length > 1 Then
                Return False
            Else
                Return True
            End If
        Else
            Return True
        End If

    End Function
    <Ajax.AjaxMethod()> _
        Public Function CheckNotExistingSupplier(ByVal txtnm As String, ByVal txtkid As String) As Boolean

        Dim dt_brand As DataTable = ReturnDataTable("Select Brand_Kid,Brand_Code,Brand_Image,Brand_CompanyId from Brand_Master where Brand_IsDeleted='0' and Brand_KId <>'" & RemoveLiterals(txtkid.Trim) & "' and Brand_Name='" & txtnm.ToString & "'")
        If dt_brand.Rows.Count <> 0 Then
            Dim supid As String = dt_brand.Rows(0).Item("Brand_CompanyID").ToString

            Dim arr = Split(supid, "-")
            If arr.Length > 1 Then
                Return False
            Else
                Return True
            End If
        Else
            Return False
        End If

    End Function


    Protected Sub InsertBrand()
        Dim s_nm As DataTable = ReturnDataTable("Select Brand_Name, Brand_Kid,Brand_CompanyId,Brand_Code,Brand_Image from Brand_Master where Brand_Name='" & txtBrandName.Text.Trim & "' and Brand_IsDeleted='0' and Brand_Kid <> '" & RemoveLiterals(txtBrandId.Text) & "'")

        If s_nm.Rows.Count <> 0 Then
            InsertUpdateBrandName("Update", s_nm.Rows(0).Item("Brand_Name").ToString, s_nm.Rows(0).Item("Brand_Kid").ToString, s_nm.Rows(0).Item("Brand_CompanyId").ToString & "-" & RemoveLiterals(Session("SupplierID")), s_nm.Rows(0).Item("Brand_Code").ToString, s_nm.Rows(0).Item("Brand_Image").ToString)
        Else
            InsertUpdateBrandName("Insert", txtBrandName.Text.Trim, txtBrandId.Text.Trim, RemoveLiterals(Session("SupplierID")), txtBrandCode.Text.Trim, strImageName)
        End If
    End Sub

    Protected Sub UpdateBrand()
        Dim s_nm As DataTable = ReturnDataTable("Select Brand_Kid,Brand_CompanyId,Brand_Code,Brand_Image from Brand_Master where Brand_Kid='" & RemoveLiterals(txtBrandId.Text.Trim) & "' and Brand_IsDeleted='0'")
        If s_nm.Rows.Count <> 0 Then
            InsertUpdateBrandName("Update", txtBrandName.Text.Trim, s_nm.Rows(0).Item("Brand_Kid").ToString, s_nm.Rows(0).Item("Brand_CompanyId").ToString, s_nm.Rows(0).Item("Brand_Code").ToString, strImageName)
        End If
    End Sub
   
End Class