Imports System
Imports System.Text
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports Northwind45.BusinessObject
Imports System.Runtime.InteropServices
 
Namespace Northwind45
    Partial Public Class GridViewSearch_Products
        Inherits System.Web.UI.Page
 
        Private _validationErrors As String = [String].Empty
 
        Protected Sub Page_Load(ByVal sender As ObjectByVal e As System.EventArgsHandles Me.Load
            Dim parameter As String = Request("__EVENTARGUMENT")
 
            SetSortImage(parameter)
            SetPaging(parameter)
        End Sub
 
        Private Sub SetSortImage(parameter As String)
            If Not [String].IsNullOrEmpty(parameter) AndAlso parameter.Contains("Sort$"Then
                LitSortExpression.Text = parameter.Replace("Sort$""")
                LitSortDirection.Text = [String].Empty
 
                If parameter = "Sort$ProductID" Then
                    If (ImgSortProductID.ImageUrl.Contains("ArrowUp.png"))
                        ImgSortProductID.ImageUrl = "~/Images/ArrowDown.png"
                        LitSortDirection.Text = "desc"
                    Else
                        ImgSortProductID.ImageUrl = "~/Images/ArrowUp.png"
                    End If
                Else If parameter = "Sort$ProductName" Then
                    If (ImgSortProductName.ImageUrl.Contains("ArrowUp.png"))
                        ImgSortProductName.ImageUrl = "~/Images/ArrowDown.png"
                        LitSortDirection.Text = "desc"
                    Else
                        ImgSortProductName.ImageUrl = "~/Images/ArrowUp.png"
                    End If
                Else If parameter = "Sort$SupplierID" Then
                    If (ImgSortSupplierID.ImageUrl.Contains("ArrowUp.png"))
                        ImgSortSupplierID.ImageUrl = "~/Images/ArrowDown.png"
                        LitSortDirection.Text = "desc"
                    Else
                        ImgSortSupplierID.ImageUrl = "~/Images/ArrowUp.png"
                    End If
                Else If parameter = "Sort$CategoryID" Then
                    If (ImgSortCategoryID.ImageUrl.Contains("ArrowUp.png"))
                        ImgSortCategoryID.ImageUrl = "~/Images/ArrowDown.png"
                        LitSortDirection.Text = "desc"
                    Else
                        ImgSortCategoryID.ImageUrl = "~/Images/ArrowUp.png"
                    End If
                Else If parameter = "Sort$QuantityPerUnit" Then
                    If (ImgSortQuantityPerUnit.ImageUrl.Contains("ArrowUp.png"))
                        ImgSortQuantityPerUnit.ImageUrl = "~/Images/ArrowDown.png"
                        LitSortDirection.Text = "desc"
                    Else
                        ImgSortQuantityPerUnit.ImageUrl = "~/Images/ArrowUp.png"
                    End If
                Else If parameter = "Sort$UnitPrice" Then
                    If (ImgSortUnitPrice.ImageUrl.Contains("ArrowUp.png"))
                        ImgSortUnitPrice.ImageUrl = "~/Images/ArrowDown.png"
                        LitSortDirection.Text = "desc"
                    Else
                        ImgSortUnitPrice.ImageUrl = "~/Images/ArrowUp.png"
                    End If
                Else If parameter = "Sort$UnitsInStock" Then
                    If (ImgSortUnitsInStock.ImageUrl.Contains("ArrowUp.png"))
                        ImgSortUnitsInStock.ImageUrl = "~/Images/ArrowDown.png"
                        LitSortDirection.Text = "desc"
                    Else
                        ImgSortUnitsInStock.ImageUrl = "~/Images/ArrowUp.png"
                    End If
                Else If parameter = "Sort$UnitsOnOrder" Then
                    If (ImgSortUnitsOnOrder.ImageUrl.Contains("ArrowUp.png"))
                        ImgSortUnitsOnOrder.ImageUrl = "~/Images/ArrowDown.png"
                        LitSortDirection.Text = "desc"
                    Else
                        ImgSortUnitsOnOrder.ImageUrl = "~/Images/ArrowUp.png"
                    End If
                Else If parameter = "Sort$ReorderLevel" Then
                    If (ImgSortReorderLevel.ImageUrl.Contains("ArrowUp.png"))
                        ImgSortReorderLevel.ImageUrl = "~/Images/ArrowDown.png"
                        LitSortDirection.Text = "desc"
                    Else
                        ImgSortReorderLevel.ImageUrl = "~/Images/ArrowUp.png"
                    End If
                Else If parameter = "Sort$Discontinued" Then
                    If (ImgSortDiscontinued.ImageUrl.Contains("ArrowUp.png"))
                        ImgSortDiscontinued.ImageUrl = "~/Images/ArrowDown.png"
                        LitSortDirection.Text = "desc"
                    Else
                        ImgSortDiscontinued.ImageUrl = "~/Images/ArrowUp.png"
                    End If
                End If
 
                ' set all ImgSort images to spacer.gif
                If parameter <> "Sort$ProductID" Then
                    ImgSortProductID.ImageUrl = "~/Images/Spacer.gif"
                End If
 
                If parameter <> "Sort$ProductName" Then
                    ImgSortProductName.ImageUrl = "~/Images/Spacer.gif"
                End If
 
                If parameter <> "Sort$SupplierID" Then
                    ImgSortSupplierID.ImageUrl = "~/Images/Spacer.gif"
                End If
 
                If parameter <> "Sort$CategoryID" Then
                    ImgSortCategoryID.ImageUrl = "~/Images/Spacer.gif"
                End If
 
                If parameter <> "Sort$QuantityPerUnit" Then
                    ImgSortQuantityPerUnit.ImageUrl = "~/Images/Spacer.gif"
                End If
 
                If parameter <> "Sort$UnitPrice" Then
                    ImgSortUnitPrice.ImageUrl = "~/Images/Spacer.gif"
                End If
 
                If parameter <> "Sort$UnitsInStock" Then
                    ImgSortUnitsInStock.ImageUrl = "~/Images/Spacer.gif"
                End If
 
                If parameter <> "Sort$UnitsOnOrder" Then
                    ImgSortUnitsOnOrder.ImageUrl = "~/Images/Spacer.gif"
                End If
 
                If parameter <> "Sort$ReorderLevel" Then
                    ImgSortReorderLevel.ImageUrl = "~/Images/Spacer.gif"
                End If
 
                If parameter <> "Sort$Discontinued" Then
                    ImgSortDiscontinued.ImageUrl = "~/Images/Spacer.gif"
                End If
 
            End If
        End Sub
 
        Private Sub SetPaging(parameter As String)
            If Not [String].IsNullOrEmpty(parameter) AndAlso parameter.Contains("Page$"Then
                LitCurrentPage.Text = parameter.Replace("Page$""")
            End If
 
            If parameter Is Nothing Or parameter <> ListLastParam.Text Then
                If IBtnCancelSearch.Visible Then
                    FillGridViewDataSourceUsingSearch()
                Else
                    FillGridView((LitSortExpression.Text + " " + LitSortDirection.Text).Trim())
                    ListLastParam.Text = parameter
 
                    Dim pageCount As Integer = (Products.GetRecordCount() - 1) \ GridView1.PageSize + 1
                    BuildPager(pageCount)
                End If
            End If
        End Sub
 
        Private Sub BuildPager(pageCount As Integer)
            Dim currentPage As Integer = Convert.ToInt32(LitCurrentPage.Text)
            Dim nearestTen As Integer = Functions.RoundToNearestTens(currentPage)
 
            Dim pager As New StringBuilder()
            pager.Append("<table><tr>")
 
            If nearestTen > 10 Then
                Dim previousPage As Integer = nearestTen - 10
                pager.Append("<td><a href='javascript:__doPostBack(&#39;ctl00$MainContent$GridView1&#39;,&#39;Page$1&#39;)' style='color:#333333;'>< First</a></td>")
                pager.Append("<td><a href='javascript:__doPostBack(&#39;ctl00$MainContent$GridView1&#39;,&#39;Page$" & previousPage & "&#39;)' style='color:#333333;'>...</a></td>")
            End If
 
            For i As Integer = (nearestTen - 9) To nearestTen
                If i = currentPage Then
                    pager.Append("<td><span style='font-size:12px;'>" & i & "</span></td>")
                Else
                    pager.Append("<td><a href='javascript:__doPostBack(&#39;ctl00$MainContent$GridView1&#39;,&#39;Page$" & i & "&#39;)' style='color:#333333;'>" & i & "</a></td>")
                End If
 
                If nearestTen > pageCount AndAlso i = pageCount Then
                    Exit For
                End If
            Next
 
            If pageCount > nearestTen Then
                Dim nextPage As Integer = nearestTen + 1
                pager.Append("<td><a href='javascript:__doPostBack(&#39;ctl00$MainContent$GridView1&#39;,&#39;Page$" & nextPage & "&#39;)' style='color:#333333;'>...</a></td>")
                pager.Append("<td><a href='javascript:__doPostBack(&#39;ctl00$MainContent$GridView1&#39;,&#39;Page$" & pageCount & "&#39;)' style='color:#333333;'>Last ></a></td>")
            End If
 
            pager.Append("</tr></table>")
            LitPager.Text = pager.ToString()
        End Sub
 
        Private Sub FillGridView(sortExpression As String)
            Dim startRowIndex As Integer = (Convert.ToInt32(LitCurrentPage.Text) - 1) * GridView1.PageSize
            GridView1.DataSource = Products.SelectSkipAndTake(GridView1.PageSize, startRowIndex, sortExpression)
            GridView1.DataBind()
        End Sub
 
        Protected Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs)
            Functions.GridViewRowDataBound(sender, e, 1)
        End Sub
 
        Protected Sub GridView1_Sorting(sender As Object, e As GridViewSortEventArgs)
            If IBtnCancelSearch.Visible Then
                FillGridViewDataSourceUsingSearch()
            Else
                FillGridView((LitSortExpression.Text + " " + LitSortDirection.Text).Trim())
            End If
        End Sub
 
        Protected Sub GridView1_RowDeleting(sender As Object, e As GridViewDeleteEventArgs)
            Try
                Dim productIDTableCell As TableCell = GridView1.Rows(e.RowIndex).Cells(0)
                Products.Delete(Convert.ToInt32(productIDTableCell.Text))
 
                If IBtnCancelSearch.Visible Then
                    FillGridViewDataSourceUsingSearch()
                Else
                    GridView1.DataSource = Products.SelectAll(LitSortExpression.Text + " " + LitSortDirection.Text)
                    GridView1.DataBind()
                End If
 
            Catch ex As Exception
                e.Cancel = True
                Functions.ShowModalError(ex, Me)
            End Try
        End Sub
 
        Protected Sub IBtnSearch_Click(sender As Object, e As System.Web.UI.ImageClickEventArgs)
           If IsSearchFieldsValid() Then
               FillGridViewDataSourceUsingSearch(True)
 
               If Not IBtnCancelSearch.Visible Then
                   IBtnCancelSearch.Visible = True
               End If
           Else
               Functions.ShowModalHtmlError(_validationErrors, Me"Validation error occured")
           End If
        End Sub
 
        Protected Sub IBtnCancelSearch_Click(sender As Object, e As System.Web.UI.ImageClickEventArgs)
           IBtnCancelSearch.Visible = False
 
           ' clear control values
           TxtProductID.Text = String.Empty
           TxtProductName.Text = String.Empty
           DdlSupplierID.SelectedValue = String.Empty
           DdlCategoryID.SelectedValue = String.Empty
           TxtQuantityPerUnit.Text = String.Empty
           TxtUnitPrice.Text = String.Empty
           TxtUnitsInStock.Text = String.Empty
           TxtUnitsOnOrder.Text = String.Empty
           TxtReorderLevel.Text = String.Empty
           DdlDiscontinued.SelectedValue = String.Empty
 
           ' clear sorting and paging
           LitSortExpression.Text = String.Empty
           LitSortDirection.Text = String.Empty
 
           FillGridView(String.Empty)
 
           ' reset paging
           Dim pageCount As Integer = (Products.GetRecordCount() - 1) \ GridView1.PageSize + 1
           BuildPager(pageCount)
 
           ' clear sort images
           ImgSortProductID.ImageUrl = "~/Images/Spacer.gif"
           ImgSortProductName.ImageUrl = "~/Images/Spacer.gif"
           ImgSortSupplierID.ImageUrl = "~/Images/Spacer.gif"
           ImgSortCategoryID.ImageUrl = "~/Images/Spacer.gif"
           ImgSortQuantityPerUnit.ImageUrl = "~/Images/Spacer.gif"
           ImgSortUnitPrice.ImageUrl = "~/Images/Spacer.gif"
           ImgSortUnitsInStock.ImageUrl = "~/Images/Spacer.gif"
           ImgSortUnitsOnOrder.ImageUrl = "~/Images/Spacer.gif"
           ImgSortReorderLevel.ImageUrl = "~/Images/Spacer.gif"
           ImgSortDiscontinued.ImageUrl = "~/Images/Spacer.gif"
        End Sub
 
        Private Function IsSearchFieldsValid() As Boolean
            Dim isValid As Boolean = True
            Dim sb As New StringBuilder()
            _validationErrors = String.Empty
 
            ' check if at least one control has a value
            If [String].IsNullOrEmpty(TxtProductID.Text) AndAlso [String].IsNullOrEmpty(TxtProductName.Text) AndAlso [String].IsNullOrEmpty(DdlSupplierID.SelectedValue) AndAlso [String].IsNullOrEmpty(DdlCategoryID.SelectedValue) AndAlso [String].IsNullOrEmpty(TxtQuantityPerUnit.Text) AndAlso [String].IsNullOrEmpty(TxtUnitPrice.Text) AndAlso [String].IsNullOrEmpty(TxtUnitsInStock.Text) AndAlso [String].IsNullOrEmpty(TxtUnitsOnOrder.Text) AndAlso [String].IsNullOrEmpty(TxtReorderLevel.Text) AndAlso [String].IsNullOrEmpty(DdlDiscontinued.SelectedValue) Then
                sb.Append("- At least one search value must be filled<br>")
                isValid = False
            Else
                If Not [String].IsNullOrEmpty(TxtProductID.Text) Then
                    Dim productID As Integer
                    Dim isProductIDValid As Boolean = Int32.TryParse(TxtProductID.Text, productID)
 
                    If Not isProductIDValid Then
                        sb.Append("- Product ID is an invalid number<br>")
                        isValid = False
                    End If
                End If
 
                If Not [String].IsNullOrEmpty(TxtUnitPrice.Text) Then
                    Dim unitPrice As Decimal
                    Dim isUnitPriceValid As Boolean = Decimal.TryParse(TxtUnitPrice.Text, unitPrice)
 
                    If Not isUnitPriceValid Then
                        sb.Append("- Unit Price is an invalid number<br>")
                        isValid = False
                    End If
                End If
 
                If Not [String].IsNullOrEmpty(TxtUnitsInStock.Text) Then
                    Dim unitsInStock As Short
                    Dim isUnitsInStockValid As Boolean = Int16.TryParse(TxtUnitsInStock.Text, unitsInStock)
 
                    If Not isUnitsInStockValid Then
                        sb.Append("- Units In Stock is an invalid number<br>")
                        isValid = False
                    End If
                End If
 
                If Not [String].IsNullOrEmpty(TxtUnitsOnOrder.Text) Then
                    Dim unitsOnOrder As Short
                    Dim isUnitsOnOrderValid As Boolean = Int16.TryParse(TxtUnitsOnOrder.Text, unitsOnOrder)
 
                    If Not isUnitsOnOrderValid Then
                        sb.Append("- Units On Order is an invalid number<br>")
                        isValid = False
                    End If
                End If
 
                If Not [String].IsNullOrEmpty(TxtReorderLevel.Text) Then
                    Dim reorderLevel As Short
                    Dim isReorderLevelValid As Boolean = Int16.TryParse(TxtReorderLevel.Text, reorderLevel)
 
                    If Not isReorderLevelValid Then
                        sb.Append("- Reorder Level is an invalid number<br>")
                        isValid = False
                    End If
                End If
 
            End If
 
            If Not isValid Then
                _validationErrors = sb.ToString()
            End If
 
            Return isValid
        End Function
 
        Private Sub FillGridViewDataSourceUsingSearch(Optional ByVal isFromSearchButton As Boolean = False)
            ' everything is nullable, only items being searched for should be filled
            Dim productID As Integer? = Nothing
            Dim productName As String = Nothing
            Dim supplierID As Integer? = Nothing
            Dim categoryID As Integer? = Nothing
            Dim quantityPerUnit As String = Nothing
            Dim unitPrice As Decimal? = Nothing
            Dim unitsInStock As Short? = Nothing
            Dim unitsOnOrder As Short? = Nothing
            Dim reorderLevel As Short? = Nothing
            Dim discontinued As Boolean? = Nothing
 
            If Not [String].IsNullOrEmpty(TxtProductID.Text) Then
                productID = Convert.ToInt32(TxtProductID.Text)
            End If
 
            If Not [String].IsNullOrEmpty(TxtProductName.Text) Then
                productName = TxtProductName.Text
            End If
 
            If Not [String].IsNullOrEmpty(DdlSupplierID.SelectedValue) Then
                supplierID = Convert.ToInt32(DdlSupplierID.SelectedValue)
            End If
 
            If Not [String].IsNullOrEmpty(DdlCategoryID.SelectedValue) Then
                categoryID = Convert.ToInt32(DdlCategoryID.SelectedValue)
            End If
 
            If Not [String].IsNullOrEmpty(TxtQuantityPerUnit.Text) Then
                quantityPerUnit = TxtQuantityPerUnit.Text
            End If
 
            If Not [String].IsNullOrEmpty(TxtUnitPrice.Text) Then
                unitPrice = Convert.ToDecimal(TxtUnitPrice.Text)
            End If
 
            If Not [String].IsNullOrEmpty(TxtUnitsInStock.Text) Then
                unitsInStock = Convert.ToInt16(TxtUnitsInStock.Text)
            End If
 
            If Not [String].IsNullOrEmpty(TxtUnitsOnOrder.Text) Then
                unitsOnOrder = Convert.ToInt16(TxtUnitsOnOrder.Text)
            End If
 
            If Not [String].IsNullOrEmpty(TxtReorderLevel.Text) Then
                reorderLevel = Convert.ToInt16(TxtReorderLevel.Text)
            End If
 
            If Not [String].IsNullOrEmpty(DdlDiscontinued.SelectedValue) Then
                discontinued = Convert.ToBoolean(DdlDiscontinued.SelectedValue)
            End If
 
            Dim sortExpression As String = (LitSortExpression.Text & " " & LitSortDirection.Text).Trim()
            Dim parameter As String = Request("__EVENTARGUMENT")
            Dim totalRowCount As Integer
            Dim startRowIndex As Integer
 
            If isFromSearchButton Or (Not [String].IsNullOrEmpty(parameter) AndAlso parameter.Contains("Sort$")) Then
                startRowIndex = 0
                LitCurrentPage.Text = "1"
            Else
                startRowIndex = (Convert.ToInt32(LitCurrentPage.Text) - 1) * GridView1.PageSize
            End If
 
            GridView1.DataSource = Products.SelectSkipAndTakeDynamicWhere(productID, productName, supplierID, categoryID, quantityPerUnit, unitPrice, unitsInStock, unitsOnOrder, reorderLevel, discontinued, GridView1.PageSize, startRowIndex, totalRowCount, sortExpression)
            GridView1.DataBind()
 
            Dim pageCount As Integer = (totalRowCount - 1) \ GridView1.PageSize + 1
            BuildPager(pageCount)
        End Sub
 
        Public Function GetSuppliersDropDownListData() As SuppliersCollection
            Return Suppliers.SelectSuppliersDropDownListData()
        End Function
 
        Public Function GetCategoriesDropDownListData() As CategoriesCollection
            Return Categories.SelectCategoriesDropDownListData()
        End Function
    End Class
End Namespace