Imports System
Imports System.Collections.Generic
Imports System.ComponentModel.DataAnnotations
Imports System.Text
Imports System.Web.UI.WebControls
Imports Northwind45.BusinessObject
Imports System.Runtime.InteropServices
 
Namespace Northwind45
    Partial Public Class GridViewInline_Products
        Inherits System.Web.UI.Page
 
        Private _validationErrors As String = [String].Empty
 
        Protected Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs)
            Functions.GridViewRowDataBound(sender, e, 1)
        End Sub
 
        Protected Sub GridView1_RowCreated(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs)
            Functions.GridViewRowCreated(sender, e, 1)
        End Sub
 
        Public Function GetGridData(maximumRows As Integer, startRowIndex As Integer, <Out()> ByRef totalRowCount As Integer, sortByExpression As StringAs ProductsCollection
            Return Products.SelectSkipAndTake(maximumRows, startRowIndex, totalRowCount, sortByExpression)
        End Function
 
        Protected Sub GridView1_RowUpdated(sender As Object, e As GridViewUpdatedEventArgsHandles GridView1.RowUpdated
            Dim productNameValue As String = DirectCast(e.NewValues(0), String)
            Dim unitPriceValue As String = DirectCast(e.NewValues(4), String)
            Dim unitsInStockValue As String = DirectCast(e.NewValues(5), String)
            Dim unitsOnOrderValue As String = DirectCast(e.NewValues(6), String)
            Dim reorderLevelValue As String = DirectCast(e.NewValues(7), String)
 
            If Not IsFormValid(productNameValue, unitPriceValue, unitsInStockValue, unitsOnOrderValue, reorderLevelValue) Then
                Functions.ShowModalHtmlError(_validationErrors, Me"An error occured on item update!")
            End If
        End Sub
 
        Public Function GetSuppliersDropDownListData() As SuppliersCollection
            Return Suppliers.SelectSuppliersDropDownListData()
        End Function
 
        Public Function GetCategoriesDropDownListData() As CategoriesCollection
            Return Categories.SelectCategoriesDropDownListData()
        End Function
 
        Public Sub DeleteGridItem(ByVal productID As Integer)
            Try
                Products.Delete(productID)
            Catch ex As Exception
                Functions.ShowModalError(ex, Me)
            End Try
        End Sub
 
        Public Sub UpdateItem(objProducts As Products)
            TryUpdateModel(objProducts)
 
            If ModelState.IsValid Then
                Try
                    objProducts.Update()
                Catch ex As Exception
                    Functions.ShowModalError(ex, Me"An error occured on item update!")
                End Try
            End If
        End Sub
 
        Protected Sub IBtnAdd_Click(sender As Object, e As ImageClickEventArgs)
            ShowAddPanel()
        End Sub
 
        Protected Sub LbtnAdd_Click(sender As Object, e As EventArgs)
            ShowAddPanel()
        End Sub
 
        Protected Sub IBtnAddNewRecord_Click(sender As Object, e As ImageClickEventArgs)
            If IsFormValid(TxtProductName.Text, TxtUnitPrice.Text, TxtUnitsInStock.Text, TxtUnitsOnOrder.Text, TxtReorderLevel.Text) Then
                Dim isErrorOccured As Boolean = False
 
                Try
                    Dim objProducts As New  Products()
 
                    If Not [String].IsNullOrEmpty(TxtProductName.Text) Then
                        objProducts.ProductName = TxtProductName.Text
                    End If
 
                    If Not [String].IsNullOrEmpty(DdlSupplierID.SelectedValue) Then
                        objProducts.SupplierID = Convert.ToInt32(DdlSupplierID.SelectedValue)
                    End If
 
                    If Not [String].IsNullOrEmpty(DdlCategoryID.SelectedValue) Then
                        objProducts.CategoryID = Convert.ToInt32(DdlCategoryID.SelectedValue)
                    End If
 
                    If Not [String].IsNullOrEmpty(TxtQuantityPerUnit.Text) Then
                        objProducts.QuantityPerUnit = TxtQuantityPerUnit.Text
                    End If
 
                    If Not [String].IsNullOrEmpty(TxtUnitPrice.Text) Then
                        objProducts.UnitPrice = Convert.ToDecimal(TxtUnitPrice.Text)
                    End If
 
                    If Not [String].IsNullOrEmpty(TxtUnitsInStock.Text) Then
                        objProducts.UnitsInStock = Convert.ToInt16(TxtUnitsInStock.Text)
                    End If
 
                    If Not [String].IsNullOrEmpty(TxtUnitsOnOrder.Text) Then
                        objProducts.UnitsOnOrder = Convert.ToInt16(TxtUnitsOnOrder.Text)
                    End If
 
                    If Not [String].IsNullOrEmpty(TxtReorderLevel.Text) Then
                        objProducts.ReorderLevel = Convert.ToInt16(TxtReorderLevel.Text)
                    End If
 
                    objProducts.Discontinued = CbxDiscontinued.Checked
 
                    ' save record
                    objProducts.Insert()
 
                    ClearControlValues()
                Catch ex As Exception
                    Functions.ShowModalError(ex, Me"An error occured on item addition!")
                    isErrorOccured = True
                End Try
 
                If Not isErrorOccured Then
                    HideAddPanel()
                End If
            Else
                Functions.ShowModalHtmlError(_validationErrors, Me"Validation error occured")
            End If
        End Sub
 
        Protected Sub IBtnCancelAdd_Click(sender As Object, e As ImageClickEventArgs)
            ClearControlValues()
            HideAddPanel()
        End Sub
 
        Protected Sub IBtnDiscontinued_Click(sender As Object, e As ImageClickEventArgs)
            ' toggle checked and unchecked image, then save
            Dim ibtn As ImageButton = TryCast(sender, ImageButton)
            Dim objProducts As Products = Products.SelectByPrimaryKey(Convert.ToInt32(ibtn.AlternateText))
 
            If objProducts IsNot Nothing Then
                If ibtn.ImageUrl.Contains("CheckBoxTrue.png"Then
                    ibtn.ImageUrl = "~/Images/CheckBoxFalse.png"
                    objProducts.Discontinued = False
                Else
                    ibtn.ImageUrl = "~/Images/CheckBoxTrue.png"
                    objProducts.Discontinued = True
                End If
 
                objProducts.Update()
            End If
        End Sub
 
        Private Sub ShowAddPanel()
            GridView1.ShowHeader = False
            PnlAddNewRecord.Visible = True
        End Sub
 
        Private Sub HideAddPanel()
            GridView1.ShowHeader = True
            PnlAddNewRecord.Visible = False
        End Sub
 
        Private Sub ClearControlValues()
            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
            CbxDiscontinued.Checked = false
        End Sub
 
        Private Function IsFormValid(productNameValue As String, unitPriceValue As String, unitsInStockValue As String, unitsOnOrderValue As String, reorderLevelValue As StringAs Boolean
            Dim isValid As Boolean = True
            Dim sb As New StringBuilder()
            _validationErrors = String.Empty
 
            ' validate required fields
            If [String].IsNullOrEmpty(productNameValue) Then
                sb.Append("- Product Name is required<br>")
                isValid = False
            End If
 
            ' validate field data type
            If Not [String].IsNullOrEmpty(unitPriceValue) Then
                Dim unitPrice As Decimal
                Dim isUnitPriceValid As Boolean = Decimal.TryParse(unitPriceValue, unitPrice)
 
                If Not isUnitPriceValid Then
                    sb.Append("- Unit Price is an invalid number<br>")
                    isValid = False
                End If
            End If
 
            If Not [String].IsNullOrEmpty(unitsInStockValue) Then
                Dim unitsInStock As Short
                Dim isUnitsInStockValid As Boolean = Int16.TryParse(unitsInStockValue, 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(unitsOnOrderValue) Then
                Dim unitsOnOrder As Short
                Dim isUnitsOnOrderValid As Boolean = Int16.TryParse(unitsOnOrderValue, 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(reorderLevelValue) Then
                Dim reorderLevel As Short
                Dim isReorderLevelValid As Boolean = Int16.TryParse(reorderLevelValue, reorderLevel)
 
                If Not isReorderLevelValid Then
                    sb.Append("- Reorder Level is an invalid number<br>")
                    isValid = False
                End If
            End If
 
            If Not isValid Then
                _validationErrors = sb.ToString()
            End If
 
            Return isValid
        End Function
    End Class
End Namespace