
' This file implements the TableControl, TableControlRow, and RecordControl classes for the 
' AddCustomers.aspx page.  The Row or RecordControl classes are the 
' ideal place to add code customizations. For example, you can override the LoadData, 
' CreateWhereClause, DataBind, SaveData, GetUIData, and Validate methods.

#Region "Imports statements"

Option Strict On
Imports Microsoft.VisualBasic
Imports BaseClasses.Web.UI.WebControls
Imports System
Imports System.Collections
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports BaseClasses
Imports BaseClasses.Data
Imports BaseClasses.Utils
Imports ReportTools.ReportCreator
Imports ReportTools.Shared

  
        
Imports UseDAL.Business
Imports UseDAL.Data
        

#End Region

  
Namespace UseDAL.UI.Controls.AddCustomers

#Region "Section 1: Place your customizations here."

    
Public Class OrdersTableControlRow
        Inherits BaseOrdersTableControlRow
        ' The BaseOrdersTableControlRow implements code for a ROW within the
        ' the OrdersTableControl table.  The BaseOrdersTableControlRow implements the DataBind and SaveData methods.
        ' The loading of data is actually performed by the LoadData method in the base class of OrdersTableControl.

        ' This is the ideal place to add your code customizations. For example, you can override the DataBind, 
        ' SaveData, GetUIData, and Validate methods.
        

End Class

  

Public Class OrdersTableControl
        Inherits BaseOrdersTableControl

        ' The BaseOrdersTableControl class implements the LoadData, DataBind, CreateWhereClause
        ' and other methods to load and display the data in a table control.

        ' This is the ideal place to add your code customizations. You can override the LoadData and CreateWhereClause,
        ' The OrdersTableControlRow class offers another place where you can customize
        ' the DataBind, GetUIData, SaveData and Validate methods specific to each row displayed on the table.

End Class

  
Public Class CustomersRecordControl
        Inherits BaseCustomersRecordControl
        ' The BaseCustomersRecordControl implements the LoadData, DataBind and other
        ' methods to load and display the data in a table control.

        ' This is the ideal place to add your code customizations. For example, you can override the LoadData, 
        ' CreateWhereClause, DataBind, SaveData, GetUIData, and Validate methods.
        

End Class

  

#End Region

  

#Region "Section 2: Do not modify this section."
    
    
' Base class for the OrdersTableControlRow control on the AddCustomers page.
' Do not modify this class. Instead override any method in OrdersTableControlRow.
Public Class BaseOrdersTableControlRow
        Inherits UseDAL.UI.BaseApplicationRecordControl

        '  To customize, override this method in OrdersTableControlRow.
      Protected Overridable Sub Control_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Init

      
      
            ' Register the event handlers.
        
        Me.EmployeeIDAddRecordLink.PostBackUrl = "../Employees/AddEmployees.aspx" & "?Target=" & Me.EmployeeID.ClientID & "&DFKA=LastName"
          
              Me.EmployeeIDAddRecordLink.Attributes.Item("onClick") = "window.open('" & Me.EmployeeIDAddRecordLink.PostBackUrl & "','_blank', 'width=900, height=700, resizable, scrollbars, modal=yes'); return false;"
              
              AddHandler Me.EmployeeIDAddRecordLink.Click, AddressOf EmployeeIDAddRecordLink_Click
              
              AddHandler Me.OrdersRowDeleteButton.Click, AddressOf OrdersRowDeleteButton_Click
              
              AddHandler Me.EmployeeID.SelectedIndexChanged, AddressOf EmployeeID_SelectedIndexChanged
            
              AddHandler Me.ShipVia.SelectedIndexChanged, AddressOf ShipVia_SelectedIndexChanged
            
        End Sub

        '  To customize, override this method in OrdersTableControlRow.
        Protected Overridable Sub Control_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        
                ' Show confirmation message on Click
                Me.OrdersRowDeleteButton.Attributes.Add("onClick", "return (confirm('" & (CType(Me.Page,BaseApplicationPage)).GetResourceValue("DeleteRecordConfirm", "UseDAL") & "'));")
    
    End Sub

        ' Read data from database.  To customize, override this method in OrdersTableControlRow.
        Public Overridable Sub LoadData()        
        
            If Not Me.RecordUniqueId Is Nothing AndAlso Me.RecordUniqueId.Trim <> "" Then
                Me.DataSource = OrdersTable.GetRecord(Me.RecordUniqueId, True)
                Return
            End If
        
            ' Since this is a row in the table, the data for this row is loaded by the 
            ' LoadData method of the BaseOrdersTableControl when the data for the entire
            ' table is loaded.
            Me.DataSource = New OrdersRecord()
          
        End Sub

        ' Populate the UI controls using the DataSource.  To customize, override this method in OrdersTableControlRow.
        Public Overrides Sub DataBind()

            MyBase.DataBind()

            ' Make sure that the DataSource is initialized.
            If Me.DataSource Is Nothing Then
                Return
            End If
        
      
            ' For each field, check to see if a value is specified.  If a value is specified,
            ' then format the value for display.  If no value is specified, use the default value (formatted).

        
            If Me.DataSource.EmployeeIDSpecified Then
                Me.PopulateEmployeeIDDropDownList(Me.DataSource.EmployeeID.ToString(), 100)
            Else
                If Not Me.DataSource.IsCreated Then
                    Me.PopulateEmployeeIDDropDownList(OrdersTable.EmployeeID.DefaultValue, 100)
                Else
                    Me.PopulateEmployeeIDDropDownList(Nothing, 100)
                End If
            End If
                
            If Me.DataSource.FreightSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(OrdersTable.Freight, "$#,##0.00;($#,##0.00)")
                Me.Freight.Text = formattedValue
              
            Else      
                Me.Freight.Text = OrdersTable.Freight.Format(OrdersTable.Freight.DefaultValue, "$#,##0.00;($#,##0.00)")
              
            End If
                    
            Me.OrderDate.Attributes.Add("onkeyup", "DateFormat(this, '', event, '" & System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern.Replace("'", "").ToLower() & "')")
            
            If Me.DataSource.OrderDateSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(OrdersTable.OrderDate)
                Me.OrderDate.Text = formattedValue
              
            Else      
                Me.OrderDate.Text = OrdersTable.OrderDate.Format(OrdersTable.OrderDate.DefaultValue)
              
            End If
                    
            Me.RequiredDate.Attributes.Add("onkeyup", "DateFormat(this, '', event, '" & System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern.Replace("'", "").ToLower() & "')")
            
            If Me.DataSource.RequiredDateSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(OrdersTable.RequiredDate)
                Me.RequiredDate.Text = formattedValue
              
            Else      
                Me.RequiredDate.Text = OrdersTable.RequiredDate.Format(OrdersTable.RequiredDate.DefaultValue)
              
            End If
                    
            If Me.DataSource.ShipAddressSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(OrdersTable.ShipAddress)
                Me.ShipAddress.Text = formattedValue
              
            Else      
                Me.ShipAddress.Text = OrdersTable.ShipAddress.Format(OrdersTable.ShipAddress.DefaultValue)
              
            End If
                    
            If Me.DataSource.ShipCitySpecified Then
                Dim formattedValue As String = Me.DataSource.Format(OrdersTable.ShipCity)
                Me.ShipCity.Text = formattedValue
              
            Else      
                Me.ShipCity.Text = OrdersTable.ShipCity.Format(OrdersTable.ShipCity.DefaultValue)
              
            End If
                    
            If Me.DataSource.ShipCountrySpecified Then
                Dim formattedValue As String = Me.DataSource.Format(OrdersTable.ShipCountry)
                Me.ShipCountry.Text = formattedValue
              
            Else      
                Me.ShipCountry.Text = OrdersTable.ShipCountry.Format(OrdersTable.ShipCountry.DefaultValue)
              
            End If
                    
            If Me.DataSource.ShipNameSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(OrdersTable.ShipName)
                Me.ShipName.Text = formattedValue
              
            Else      
                Me.ShipName.Text = OrdersTable.ShipName.Format(OrdersTable.ShipName.DefaultValue)
              
            End If
                    
            Me.ShippedDate.Attributes.Add("onkeyup", "DateFormat(this, '', event, '" & System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern.Replace("'", "").ToLower() & "')")
            
            If Me.DataSource.ShippedDateSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(OrdersTable.ShippedDate)
                Me.ShippedDate.Text = formattedValue
              
            Else      
                Me.ShippedDate.Text = OrdersTable.ShippedDate.Format(OrdersTable.ShippedDate.DefaultValue)
              
            End If
                    
            If Me.DataSource.ShipPostalCodeSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(OrdersTable.ShipPostalCode)
                Me.ShipPostalCode.Text = formattedValue
              
            Else      
                Me.ShipPostalCode.Text = OrdersTable.ShipPostalCode.Format(OrdersTable.ShipPostalCode.DefaultValue)
              
            End If
                    
            If Me.DataSource.ShipRegionSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(OrdersTable.ShipRegion)
                Me.ShipRegion.Text = formattedValue
              
            Else      
                Me.ShipRegion.Text = OrdersTable.ShipRegion.Format(OrdersTable.ShipRegion.DefaultValue)
              
            End If
                    
            If Me.DataSource.ShipViaSpecified Then
                Me.PopulateShipViaDropDownList(Me.DataSource.ShipVia.ToString(), 100)
            Else
                If Not Me.DataSource.IsCreated Then
                    Me.PopulateShipViaDropDownList(OrdersTable.ShipVia.DefaultValue, 100)
                Else
                    Me.PopulateShipViaDropDownList(Nothing, 100)
                End If
            End If
                
            Me.IsNewRecord = True
            If Me.DataSource.IsCreated Then
                Me.IsNewRecord = False
        
                Me.RecordUniqueId = Me.DataSource.GetID.ToXmlString()
            End If

            

            ' Load data for each record and table UI control.
            ' Ordering is important because child controls get 
            ' their parent ids from their parent UI controls.
            Dim shouldResetControl as Boolean = False
            
      End Sub

        
        
        ' To customize, override this method in OrdersTableControlRow.
        Public Overridable Sub SaveData()

            ' 1. Load the existing record from the database. Since we save the entire record, this ensures 
            ' that fields that are not displayed also properly initialized.
            Me.LoadData()
        
        Dim customersRecordControlObj as CustomersRecordControl
        
  
          customersRecordControlObj = DirectCast(Me.Page.FindControlRecursively("CustomersRecordControl"), CustomersRecordControl)
          If (Not IsNothing(customersRecordControlObj) AndAlso IsNothing(customersRecordControlObj.DataSource)) 
                ' Load the record if it is not loaded yet.
                customersRecordControlObj.LoadData()
            End If
            If (IsNothing(customersRecordControlObj) OrElse IsNothing(customersRecordControlObj.DataSource)) 
                ' Get the error message from the application resource file.
                Throw New Exception(Page.GetResourceValue("Err:NoParentRecId", "UseDAL"))
            End If
            
            Me.DataSource.CustomerID = customersRecordControlObj.DataSource.CustomerID
              
            ' 2. Validate the data.  Override in OrdersTableControlRow to add custom validation.
            Me.Validate()

            ' 3. Set the values in the record with data from UI controls.  Override in OrdersTableControlRow to set additional fields.
            Me.GetUIData()

            ' 4. Save in the database.
            ' We should not save the record if the data did not change. This
            ' will save a database hit and avoid triggering any database triggers.
            If Me.DataSource.IsAnyValueChanged Then
                ' Save record to database but do not commit.
                ' Auto generated ids are available after saving for use by child (dependent) records.
                Me.DataSource.Save()
              
                DirectCast(GetParentControlObject(Me, "OrdersTableControl"), OrdersTableControl).DataChanged = True
                DirectCast(GetParentControlObject(Me, "OrdersTableControl"), OrdersTableControl).ResetData = True
            End If
            Me.DataChanged = True
            Me.ResetData = True
            ' Reseting of Me.IsNewRecord is moved to Save button's click even handler.
            ' Me.IsNewRecord() = False
            
        End Sub

        ' To customize, override this method in OrdersTableControlRow.
        Public Overridable Sub GetUIData()
            
            Me.DataSource.Parse(GetValueSelectedPageRequest(Me.EmployeeID), OrdersTable.EmployeeID)
                  
            Me.DataSource.Parse(Me.Freight.Text, OrdersTable.Freight)
                          
            Me.DataSource.Parse(Me.OrderDate.Text, OrdersTable.OrderDate)
                          
            Me.DataSource.Parse(Me.RequiredDate.Text, OrdersTable.RequiredDate)
                          
            Me.DataSource.Parse(Me.ShipAddress.Text, OrdersTable.ShipAddress)
                          
            Me.DataSource.Parse(Me.ShipCity.Text, OrdersTable.ShipCity)
                          
            Me.DataSource.Parse(Me.ShipCountry.Text, OrdersTable.ShipCountry)
                          
            Me.DataSource.Parse(Me.ShipName.Text, OrdersTable.ShipName)
                          
            Me.DataSource.Parse(Me.ShippedDate.Text, OrdersTable.ShippedDate)
                          
            Me.DataSource.Parse(Me.ShipPostalCode.Text, OrdersTable.ShipPostalCode)
                          
            Me.DataSource.Parse(Me.ShipRegion.Text, OrdersTable.ShipRegion)
                          
            Me.DataSource.Parse(GetValueSelectedPageRequest(Me.ShipVia), OrdersTable.ShipVia)
                  
        End Sub

        
      
        ' To customize, override this method in OrdersTableControlRow.
        Public Overridable Function CreateWhereClause() As WhereClause
        
            Return Nothing
          
        End Function
        

        ' To customize, override this method in OrdersTableControlRow.
        Public Overridable Sub Validate() 
            ' Initially empty.  Override to add custom validation.
        End Sub

        Public Overridable Sub Delete()
        
            If Me.IsNewRecord() Then
                Return
            End If

            Dim pk As KeyValue = KeyValue.XmlToKey(Me.RecordUniqueId)
            OrdersTable.DeleteRecord(pk)

          
            DirectCast(GetParentControlObject(Me, "OrdersTableControl"), OrdersTableControl).DataChanged = True
            DirectCast(GetParentControlObject(Me, "OrdersTableControl"), OrdersTableControl).ResetData = True
        End Sub

        Protected Overridable Sub Control_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.PreRender
            Try
                DbUtils.StartTransaction()

                If Not Me.Page.ErrorOnPage AndAlso (Me.Page.IsPageRefresh OrElse Me.DataChanged OrElse Me.ResetData) Then
                    Me.LoadData()
                    Me.DataBind()
                End If

            Catch ex As Exception
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
                DbUtils.EndTransaction()
            End Try
        End Sub
        
        

        Protected Overrides Sub LoadViewState(ByVal savedState As Object)
            MyBase.LoadViewState(savedState)
            Dim isNewRecord As String = CType(ViewState("IsNewRecord"), String)
            If Not isNewRecord Is Nothing AndAlso isNewRecord.Trim <> "" Then
                Me.IsNewRecord = Boolean.Parse(isNewRecord)
            End If
            
            Dim myCheckSum As String = CType(ViewState("CheckSum"), String)
            If Not myCheckSum Is Nothing AndAlso myCheckSum.Trim <> "" Then
                Me.CheckSum = myCheckSum
            End If
            
        End Sub

        Protected Overrides Function SaveViewState() As Object
            ViewState("IsNewRecord") = Me.IsNewRecord.ToString()
            ViewState("CheckSum") = Me.CheckSum
            
            Return MyBase.SaveViewState()
        End Function
        
        
        Public Overridable Function CreateWhereClause_EmployeeIDDropDownList() As WhereClause
            Return New WhereClause()
        End Function
                
        Public Overridable Function CreateWhereClause_ShipViaDropDownList() As WhereClause
            Return New WhereClause()
        End Function
                
        ' Fill the EmployeeID list.
        Protected Overridable Sub PopulateEmployeeIDDropDownList( _
                ByVal selectedValue As String, _
                ByVal maxItems As Integer)
                  
            'Setup the WHERE clause.
            Dim wc As WhereClause = CreateWhereClause_EmployeeIDDropDownList()
            Dim orderBy As OrderBy = New OrderBy(False, True)
            orderBy.Add(EmployeesTable.LastName, OrderByItem.OrderDir.Asc)

            Me.EmployeeID.Items.Clear()
            Dim itemValue As EmployeesRecord
            For Each itemValue In EmployeesTable.GetRecords(wc, orderBy, 0, maxItems)
                ' Create the item and add to the list.
                Dim cvalue As String = Nothing
                Dim fvalue As String = Nothing
                If itemValue.EmployeeIDSpecified Then
                    cvalue = itemValue.EmployeeID.ToString()
                    fvalue = itemValue.Format(EmployeesTable.LastName)
                End If

                Dim item As ListItem = New ListItem(fvalue, cvalue)
                Me.EmployeeID.Items.Add(item)
            Next
                    
            ' Setup the selected item.
            If Not selectedValue Is Nothing AndAlso _
                selectedValue.Trim <> "" AndAlso _
                Not SetSelectedValue(Me.EmployeeID, selectedValue) AndAlso _
                Not MiscUtils.SetSelectedValue(Me.EmployeeID, OrdersTable.EmployeeID.Format(selectedValue))Then
                Dim fvalue As String = OrdersTable.EmployeeID.Format(selectedValue)
                Dim item As ListItem = New ListItem(fvalue, selectedValue)
                item.Selected = True
                Me.EmployeeID.Items.Insert(0, item)
            End If

                  
            Me.EmployeeID.Items.Insert(0, New ListItem(Page.GetResourceValue("Txt:PleaseSelect", "UseDAL"), "--PLEASE_SELECT--"))
                  
        End Sub
                
        ' Fill the ShipVia list.
        Protected Overridable Sub PopulateShipViaDropDownList( _
                ByVal selectedValue As String, _
                ByVal maxItems As Integer)
                  
            'Setup the WHERE clause.
            Dim wc As WhereClause = CreateWhereClause_ShipViaDropDownList()
            Dim orderBy As OrderBy = New OrderBy(False, True)
            orderBy.Add(ShippersTable.CompanyName, OrderByItem.OrderDir.Asc)

            Me.ShipVia.Items.Clear()
            Dim itemValue As ShippersRecord
            For Each itemValue In ShippersTable.GetRecords(wc, orderBy, 0, maxItems)
                ' Create the item and add to the list.
                Dim cvalue As String = Nothing
                Dim fvalue As String = Nothing
                If itemValue.ShipperIDSpecified Then
                    cvalue = itemValue.ShipperID.ToString()
                    fvalue = itemValue.Format(ShippersTable.CompanyName)
                End If

                Dim item As ListItem = New ListItem(fvalue, cvalue)
                Me.ShipVia.Items.Add(item)
            Next
                    
            ' Setup the selected item.
            If Not selectedValue Is Nothing AndAlso _
                selectedValue.Trim <> "" AndAlso _
                Not SetSelectedValue(Me.ShipVia, selectedValue) AndAlso _
                Not MiscUtils.SetSelectedValue(Me.ShipVia, OrdersTable.ShipVia.Format(selectedValue))Then
                Dim fvalue As String = OrdersTable.ShipVia.Format(selectedValue)
                Dim item As ListItem = New ListItem(fvalue, selectedValue)
                item.Selected = True
                Me.ShipVia.Items.Insert(0, item)
            End If

                  
            Me.ShipVia.Items.Insert(0, New ListItem(Page.GetResourceValue("Txt:PleaseSelect", "UseDAL"), "--PLEASE_SELECT--"))
                  
        End Sub
                
        ' event handler for ImageButton
        Public Overridable Sub EmployeeIDAddRecordLink_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Dim url As String = "../Employees/AddEmployees.aspx"
            Dim shouldRedirect As Boolean = True
            Dim TargetKey As String = Nothing
            Dim DFKA As String = Nothing
            Dim id As String = Nothing
            Dim value As String = Nothing
            Try
                DbUtils.StartTransaction
                
            url = Me.ModifyRedirectUrl(url, "",False)
            url = Me.Page.ModifyRedirectUrl(url, "",False)
          Me.Page.CommitTransaction(sender)
          
            Catch ex As Exception
                Me.Page.RollBackTransaction(sender)
                shouldRedirect = False
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
                DbUtils.EndTransaction
            End Try
            If shouldRedirect Then
                Me.Page.ShouldSaveControlsToSession = True
                Me.Page.Response.Redirect(url)
            ElseIf Not TargetKey Is Nothing AndAlso _
                        Not shouldRedirect Then
            Me.Page.ShouldSaveControlsToSession = True
            Me.Page.CloseWindow(True)
        
            End If              
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub OrdersRowDeleteButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                DbUtils.StartTransaction
                
            If(Not Me.Page.IsPageRefresh) Then
        
                Dim tc As OrdersTableControl = DirectCast(GetParentControlObject(Me, "OrdersTableControl"), OrdersTableControl)
                If Not (IsNothing(tc)) Then
                    If Not Me.IsNewRecord Then
                        tc.AddToDeletedRecordIds(DirectCast(Me, OrdersTableControlRow))
                    End If
                    Me.Visible = False
                End If
              
            End If
      Me.Page.CommitTransaction(sender)
          
            Catch ex As Exception
                Me.Page.RollBackTransaction(sender)
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
                DbUtils.EndTransaction
            End Try
                  
        End Sub
            
              Protected Overridable Sub EmployeeID_SelectedIndexChanged(ByVal sender As Object, ByVal args As EventArgs)
              Dim selectedValue As String = MiscUtils.GetValueSelectedPageRequest(Me.EmployeeID)
              If Not selectedValue Is Nothing AndAlso _
              selectedValue.Trim <> "" AndAlso _
              Not SetSelectedValue(Me.EmployeeID, selectedValue) AndAlso _
              Not MiscUtils.SetSelectedValue(Me.EmployeeID, OrdersTable.EmployeeID.Format(selectedValue)) Then
              Dim fvalue As String = OrdersTable.EmployeeID.Format(selectedValue)
              Dim item As ListItem = New ListItem(fvalue, selectedValue)
              item.Selected = True
              Me.EmployeeID.Items.Insert(0, item)
              End If
              End Sub
            
              Protected Overridable Sub ShipVia_SelectedIndexChanged(ByVal sender As Object, ByVal args As EventArgs)
              Dim selectedValue As String = MiscUtils.GetValueSelectedPageRequest(Me.ShipVia)
              If Not selectedValue Is Nothing AndAlso _
              selectedValue.Trim <> "" AndAlso _
              Not SetSelectedValue(Me.ShipVia, selectedValue) AndAlso _
              Not MiscUtils.SetSelectedValue(Me.ShipVia, OrdersTable.ShipVia.Format(selectedValue)) Then
              Dim fvalue As String = OrdersTable.ShipVia.Format(selectedValue)
              Dim item As ListItem = New ListItem(fvalue, selectedValue)
              item.Selected = True
              Me.ShipVia.Items.Insert(0, item)
              End If
              End Sub
            
   
        Private _IsNewRecord As Boolean = True
        Public Overridable Property IsNewRecord() As Boolean
            Get
                Return Me._IsNewRecord
            End Get
            Set(ByVal value As Boolean)
                Me._IsNewRecord = value
            End Set
        End Property

        Private _DataChanged As Boolean = False
        Public Overridable Property DataChanged() As Boolean
            Get
                Return Me._DataChanged
            End Get
            Set(ByVal Value As Boolean)
                Me._DataChanged = Value
            End Set
        End Property

        Private _ResetData As Boolean = False
        Public Overridable Property ResetData() As Boolean
            Get
                Return Me._ResetData
            End Get
            Set(ByVal Value As Boolean)
                Me._ResetData = Value
            End Set
        End Property
        
        Public Property RecordUniqueId() As String
            Get
                Return CType(Me.ViewState("BaseOrdersTableControlRow_Rec"), String)
            End Get
            Set(ByVal value As String)
                Me.ViewState("BaseOrdersTableControlRow_Rec") = value
            End Set
        End Property
        
        Private _DataSource As OrdersRecord
        Public Property DataSource() As OrdersRecord
            Get
                Return Me._DataSource
            End Get
            Set(ByVal value As OrdersRecord)
                Me._DataSource = value
            End Set
        End Property

        Private _checkSum As String
        Public Overridable Property CheckSum() As String
            Get
                Return Me._checkSum
            End Get
            Set(ByVal value As String)
                Me._checkSum = value
            End Set
        End Property
        
        Private _TotalPages As Integer
        Public Property TotalPages() As Integer
            Get
                Return Me._TotalPages
            End Get
            Set(ByVal value As Integer)
                Me._TotalPages = value
            End Set
        End Property
        
        Private _PageIndex As Integer
        Public Property PageIndex() As Integer
            Get
                ' Return the PageIndex
                Return Me._PageIndex
            End Get
            Set(ByVal value As Integer)
                Me._PageIndex = value
            End Set
        End Property
    
        Private _DisplayLastPage As Boolean
        Public Property DisplayLastPage() As Boolean
            Get
                Return Me._DisplayLastPage
            End Get
            Set(ByVal value As Boolean)
                Me._DisplayLastPage = value
            End Set
        End Property
        
        

#Region "Helper Properties"
        
        Public ReadOnly Property EmployeeID() As System.Web.UI.WebControls.DropDownList
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "EmployeeID"), System.Web.UI.WebControls.DropDownList)
            End Get
        End Property
            
        Public ReadOnly Property EmployeeIDAddRecordLink() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "EmployeeIDAddRecordLink"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property Freight() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "Freight"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property OrderDate() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "OrderDate"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property OrdersRecordRowSelection() As System.Web.UI.WebControls.CheckBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "OrdersRecordRowSelection"), System.Web.UI.WebControls.CheckBox)
            End Get
        End Property
        
        Public ReadOnly Property OrdersRowDeleteButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "OrdersRowDeleteButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property RequiredDate() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "RequiredDate"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property ShipAddress() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ShipAddress"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property ShipCity() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ShipCity"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property ShipCountry() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ShipCountry"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property ShipName() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ShipName"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property ShippedDate() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ShippedDate"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property ShipPostalCode() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ShipPostalCode"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property ShipRegion() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ShipRegion"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property ShipVia() As System.Web.UI.WebControls.DropDownList
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ShipVia"), System.Web.UI.WebControls.DropDownList)
            End Get
        End Property
            
    #End Region

    #Region "Helper Functions"

    Public Overrides Overloads Function ModifyRedirectUrl(ByVal url As String, ByVal arg As String, ByVal bEncrypt As Boolean) As String
        Return Me.Page.EvaluateExpressions(url, arg, bEncrypt, Me)
    End Function

    Public Overrides Overloads Function EvaluateExpressions(ByVal url As String, ByVal arg As String, ByVal bEncrypt As Boolean) As String
    Dim rec As OrdersRecord = Nothing
            
            Try
                rec = Me.GetRecord()
            Catch ex As Exception
                ' Do nothing
            End Try

            If rec Is Nothing AndAlso url.IndexOf("{") >= 0 Then
                ' Localization.
                
            Throw New Exception(Page.GetResourceValue("Err:RecDataSrcNotInitialized", "UseDAL"))
                    
            End If
            Return EvaluateExpressions(url, arg, rec, bEncrypt)
        End Function

        Public Overridable Function GetRecord() As OrdersRecord
            If Not Me.DataSource Is Nothing Then
                Return Me.DataSource
            End If
            
            If Not Me.RecordUniqueId Is Nothing Then
                Return OrdersTable.GetRecord(Me.RecordUniqueId, True)
            End If
            
            ' Localization.
            
            Return Nothing
                
        End Function

        Public Shadows ReadOnly Property Page() As BaseApplicationPage
            Get
                Return DirectCast(MyBase.Page, BaseApplicationPage)
            End Get
        End Property

#End Region

End Class

  

' Base class for the OrdersTableControl control on the AddCustomers page.
' Do not modify this class. Instead override any method in OrdersTableControl.
Public Class BaseOrdersTableControl
        Inherits UseDAL.UI.BaseApplicationTableControl

        Protected Overridable Sub Control_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Init

            ' Setup the pagination events.
        
              AddHandler Me.OrdersPagination.FirstPage.Click, AddressOf OrdersPagination_FirstPage_Click
              
              AddHandler Me.OrdersPagination.LastPage.Click, AddressOf OrdersPagination_LastPage_Click
              
              AddHandler Me.OrdersPagination.NextPage.Click, AddressOf OrdersPagination_NextPage_Click
              
              AddHandler Me.OrdersPagination.PageSizeButton.Click, AddressOf OrdersPagination_PageSizeButton_Click
            
              AddHandler Me.OrdersPagination.PreviousPage.Click, AddressOf OrdersPagination_PreviousPage_Click
              

            ' Setup the sorting events.
        
              AddHandler Me.EmployeeIDLabel1.Click, AddressOf EmployeeIDLabel1_Click
            
              AddHandler Me.FreightLabel.Click, AddressOf FreightLabel_Click
            
              AddHandler Me.OrderDateLabel.Click, AddressOf OrderDateLabel_Click
            
              AddHandler Me.RequiredDateLabel.Click, AddressOf RequiredDateLabel_Click
            
              AddHandler Me.ShipAddressLabel.Click, AddressOf ShipAddressLabel_Click
            
              AddHandler Me.ShipCityLabel.Click, AddressOf ShipCityLabel_Click
            
              AddHandler Me.ShipCountryLabel.Click, AddressOf ShipCountryLabel_Click
            
              AddHandler Me.ShipNameLabel.Click, AddressOf ShipNameLabel_Click
            
              AddHandler Me.ShippedDateLabel.Click, AddressOf ShippedDateLabel_Click
            
              AddHandler Me.ShipPostalCodeLabel.Click, AddressOf ShipPostalCodeLabel_Click
            
              AddHandler Me.ShipRegionLabel.Click, AddressOf ShipRegionLabel_Click
            
              AddHandler Me.ShipViaLabel1.Click, AddressOf ShipViaLabel1_Click
            

            ' Setup the button events.
        
              AddHandler Me.OrdersAddButton.Click, AddressOf OrdersAddButton_Click
              
              AddHandler Me.OrdersDeleteButton.Click, AddressOf OrdersDeleteButton_Click
              
              AddHandler Me.OrdersResetButton.Click, AddressOf OrdersResetButton_Click
              

            ' Setup the filter and search events.
        

            ' Control Initializations.
            ' Initialize the table's current sort order.
            If Me.InSession(Me, "Order_By") Then
                Me.CurrentSortOrder = OrderBy.FromXmlString(Me.GetFromSession(Me, "Order_By", Nothing))
            Else
                Me.CurrentSortOrder = New OrderBy(True, True)
        
            End If

            ' Setup default pagination settings.
        
            Me.PageSize = CInt(Me.GetFromSession(Me, "Page_Size", "10"))
            Me.PageIndex = CInt(Me.GetFromSession(Me, "Page_Index", "0"))
            Me.ClearControlsFromSession()
        End Sub

        Protected Overridable Sub Control_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        
            SaveControlsToSession_Ajax()
        
                ' Show confirmation message on Click
                Me.OrdersDeleteButton.Attributes.Add("onClick", "return (confirm('" & (CType(Me.Page,BaseApplicationPage)).GetResourceValue("DeleteConfirm", "UseDAL") & "'));")
        End Sub

        ' Read data from database. Returns an array of records that can be assigned
        ' to the DataSource table control property.
        Public Overridable Sub LoadData()
            Try
            
                ' The WHERE clause will be empty when displaying all records in table.
                Dim wc As WhereClause = CreateWhereClause()
                If Not wc Is Nothing AndAlso Not wc.RunQuery Then
                    ' Initialize an empty array of records
                    Dim alist As New ArrayList(0)
                    Me.DataSource = DirectCast(alist.ToArray(GetType(OrdersRecord)), OrdersRecord())
                    ' Add records to the list if needed.
                    Me.AddNewRecords()
                    Return
                End If

                Dim orderBy As OrderBy = CreateOrderBy()

                ' Get the pagesize from the pagesize control.
                Me.GetPageSize()

                ' Get the total number of records to be displayed.
                Me.TotalRecords = OrdersTable.GetRecordCount(wc)

                ' Go to the last page.
                If Me.TotalPages <= 0 OrElse Me.PageIndex < 0 Then
                    Me.PageIndex = 0
                ElseIf Me.DisplayLastPage OrElse Me.PageIndex >= Me.TotalPages Then
                    Me.PageIndex = Me.TotalPages - 1
                End If

                ' Retrieve the records and set the table DataSource.
                ' Only PageSize records are fetched starting at PageIndex (zero based).
                If Me.TotalRecords <= 0 Then
                    ' Initialize an empty array of records
                    Dim alist As New ArrayList(0)
                    Me.DataSource = DirectCast(alist.ToArray(GetType(OrdersRecord)), OrdersRecord())
                ElseIf Me.AddNewRecord > 0 Then
                    ' Get the records from the posted data
                    Dim postdata As New ArrayList
                    For Each rc As OrdersTableControlRow In Me.GetRecordControls()
                        If Not rc.IsNewRecord Then
                            rc.DataSource = rc.GetRecord()
                            rc.GetUIData()
                            postdata.Add(rc.DataSource)
                        End If
                    Next
                    Me.DataSource = DirectCast(postdata.ToArray(GetType(OrdersRecord)), OrdersRecord())
                Else
                    ' Get the records from the database
                    Me.DataSource = OrdersTable.GetRecords(wc, orderBy, Me.PageIndex, Me.PageSize)
                End If
                ' Add records to the list.
                Me.AddNewRecords()
            
                ' Turn off the ToggleAll checkbox
                Me.OrdersToggleAll.Checked = False
            

                ' Initialize the page and grand totals. now
            
            Catch ex As Exception
                Throw ex
            End Try
        End Sub

        ' Populate the UI controls.
        Public Overrides Sub DataBind()

            MyBase.DataBind()

            ' Make sure that the DataSource is initialized.
            If Me.DataSource Is Nothing Then
                Return
            End If

        
          ' Improve performance by prefetching display as records.
          Me.PreFetchForeignKeyValues()
        

            ' Setup the pagination controls.
            BindPaginationControls()

            ' Populate all filters data.
        

            ' Bind the repeater with the list of records to expand the UI.
            Dim rep As System.Web.UI.WebControls.Repeater = CType(Me.FindControl("OrdersTableControlRepeater"), System.Web.UI.WebControls.Repeater)
      If rep is Nothing Then Return
            rep.DataSource = DataSource()
            rep.DataBind()

            Dim index as Integer = 0
            For Each repItem as System.Web.UI.WebControls.RepeaterItem in rep.Items
                ' Loop through all rows in the table, set its DataSource and call DataBind().
                Dim recControl as OrdersTableControlRow = DirectCast(repItem.FindControl("OrdersTableControlRow"),OrdersTableControlRow) 
                recControl.DataSource = Me.DataSource(index)
                recControl.DataBind()
                recControl.Visible = Not Me.InDeletedRecordIds(recControl)
                index += 1
            Next

        
      ' setting the state of expand or collapse alternative rows
      
      End Sub

        Public Overridable Sub ResetControl()
        
            
              Me.CurrentSortOrder.Reset()
              If (Me.InSession(Me, "Order_By")) Then
              Me.CurrentSortOrder = OrderBy.FromXmlString(Me.GetFromSession(Me, "Order_By", Nothing))
              Else
              Me.CurrentSortOrder = New OrderBy(true, true)
            
            End If
                
            Me.PageIndex = 0
    End Sub


    
          Public Sub PreFetchForeignKeyValues()
          If (IsNothing(Me.DataSource))
            Return
          End If
          
            Me.Page.PregetDfkaRecords(OrdersTable.EmployeeID, Me.DataSource)
          
            Me.Page.PregetDfkaRecords(OrdersTable.ShipVia, Me.DataSource)
          
          End Sub
         

        Protected Overridable Sub BindPaginationControls()

            ' Setup the pagination controls.

            ' Bind the buttons for OrdersTableControl pagination.
        
            Me.OrdersPagination.FirstPage.Enabled = Not (Me.PageIndex = 0)
            Me.OrdersPagination.LastPage.Enabled = Not (Me.PageIndex = Me.TotalPages - 1)
            If Me.TotalPages = 0 Then
                Me.OrdersPagination.LastPage.Enabled = False
            End If
          
            Me.OrdersPagination.NextPage.Enabled = Not (Me.PageIndex = Me.TotalPages - 1)
            If Me.TotalPages = 0 Then
                Me.OrdersPagination.NextPage.Enabled = False
            End If
          
            Me.OrdersPagination.PreviousPage.Enabled = Not (Me.PageIndex = 0)

            ' Bind the pagination labels.
        
            If Me.TotalPages > 0 Then
                Me.OrdersPagination.CurrentPage.Text = (Me.PageIndex + 1).ToString()
            Else
                Me.OrdersPagination.CurrentPage.Text = "0"
            End If
            Me.OrdersPagination.PageSize.Text = Me.PageSize.ToString()
            Me.OrdersPagination.TotalItems.Text = Me.TotalRecords.ToString()
            Me.OrdersPagination.TotalPages.Text = Me.TotalPages.ToString()
        End Sub

        Public Overridable Sub SaveData()
            Dim recCtl As OrdersTableControlRow
            For Each recCtl In Me.GetRecordControls()
        
                If Me.InDeletedRecordIds(recCtl) Then
                    recCtl.Delete()
                Else
                    If recCtl.Visible Then
                        recCtl.SaveData()
                    End If
                End If
          
            Next
            
            Me.DataChanged = True
            Me.ResetData = True
            
            
          
          ' When one tries to add two duplicate records, an exception is thrown.Before throwing an exception, the first record's IsNewRecord property is set to false. 
          ' Now when one tries to delete these two records simultaneously, since the first record's IsNewRecord property is false, the server tries to delete it from the database, which result in an error.
          ' To avoid this problem every record's IsNewRecord property is set to false only after all the records are saved in the database. 
          For Each recCtl in Me.GetRecordControls()
              recCtl.IsNewRecord = False
          Next
    
      
                ' Whenever an existing record is deleted and saved and then tried to add the same record, it does not display the newly added record after saving, because, while displaying each records DeletedRecordIds is checked to see if it is waiting to be deleted.
          ' Since DeletedRecordIds is not reset after each record deletion, when one tries to add the same record it sees record id in DeleteReordIds and does not display it. 
          ' To overcome this problem, DeletedRecordIds is reset.
           Me.DeletedRecordIds = Nothing
      
            
            
        End Sub

        Public Overridable Function CreateOrderBy() As OrderBy
            Return Me.CurrentSortOrder
        End Function
        
        'This CreateWhereClause is used for loading the data.
        Public Overridable Function CreateWhereClause() As WhereClause
            OrdersTable.Instance.InnerFilter = Nothing
            Dim wc As WhereClause = New WhereClause()
            ' Compose the WHERE clause consiting of:
            ' 1. Static clause defined at design time.
            ' 2. User selected filter criteria.
            ' 3. User selected search criteria.

              
      Dim selectedRecordKeyValue as KeyValue = New KeyValue()
    
              Dim customersRecordControlObj As CustomersRecordControl = DirectCast(MiscUtils.FindControlRecursively(Me.Page, "CustomersRecordControl"), CustomersRecordControl)
              
                If (Not IsNothing(customersRecordControlObj) AndAlso Not IsNothing(customersRecordControlObj.GetRecord()) AndAlso Not IsNothing(customersRecordControlObj.GetRecord().CustomerID))
                    wc.iAND(OrdersTable.CustomerID, BaseFilter.ComparisonOperator.EqualsTo, customersRecordControlObj.GetRecord().CustomerID.ToString())
                    selectedRecordKeyValue.AddElement(OrdersTable.CustomerID.InternalName, customersRecordControlObj.GetRecord().CustomerID.ToString())
                Else
                    wc.RunQuery = False
                    Return wc                    
                End If          
              
      HttpContext.Current.Session("OrdersTableControlWhereClause") = selectedRecordKeyValue.ToXmlString()
    
            Return wc
        End Function
        
        
        ' This CreateWhereClause is used for loading list of suggestions for Auto Type-Ahead feature.
        Public Overridable Function CreateWhereClause(ByVal searchText as String, ByVal fromSearchControl as String, ByVal AutoTypeAheadSearch as String, ByVal AutoTypeAheadWordSeparators as String) As WhereClause
            OrdersTable.Instance.InnerFilter = Nothing
            Dim wc As WhereClause = New WhereClause()
            ' Compose the WHERE clause consiting of:
            ' 1. Static clause defined at design time.
            ' 2. User selected filter criteria.
            ' 3. User selected search criteria.
            Dim appRelativeVirtualPath As String = CType(HttpContext.Current.Session("AppRelativeVirtualPath"), String)
            
            Dim selectedRecordInCustomersRecordControl as String = DirectCast(HttpContext.Current.Session("OrdersTableControlWhereClause"), String)
            
            If Not selectedRecordInCustomersRecordControl Is Nothing AndAlso KeyValue.IsXmlKey(selectedRecordInCustomersRecordControl) Then
                Dim selectedRecordKeyValue as KeyValue = KeyValue.XmlToKey(selectedRecordInCustomersRecordControl)
                
       If Not IsNothing(selectedRecordKeyValue) AndAlso selectedRecordKeyValue.ContainsColumn(OrdersTable.CustomerID) Then
            wc.iAND(OrdersTable.CustomerID, BaseFilter.ComparisonOperator.EqualsTo, selectedRecordKeyValue.GetColumnValue(OrdersTable.CustomerID).ToString())
        End If
    
  
            End If
          
            ' Adds clauses if values are selected in Filter controls which are configured in the page.
          
            Return wc
        End Function
          
          
        'Formats the resultItem and adds it to the list of suggestions.
        Public Overridable Function FormatSuggestions(ByVal prefixText As String, ByVal resultItem as String, _
                                                 ByVal columnLength As Integer, ByVal AutoTypeAheadDisplayFoundText as String, _
                                                 ByVal autoTypeAheadSearch as String, ByVal AutoTypeAheadWordSeparators as String, _
                                                 ByVal resultList as ArrayList) as Boolean
            Dim index As Integer = resultItem.ToUpper(System.Threading.Thread.CurrentThread.CurrentCulture).IndexOf(prefixText.ToUpper(System.Threading.Thread.CurrentThread.CurrentCulture))
            Dim itemToAdd As String = ""
            Dim isFound as Boolean = False
            Dim isAdded as Boolean = False
            ' Get the index where prfixt is at the beginning of resultItem. If not found then, index of word which begins with prefixText.
            If InvariantLCase(autoTypeAheadSearch).equals("wordsstartingwithsearchstring") and not index = 0 Then
                ' Expression to find word which contains AutoTypeAheadWordSeparators followed by prefixText
                Dim regex1 As System.Text.RegularExpressions.Regex = new System.Text.RegularExpressions.Regex( AutoTypeAheadWordSeparators + prefixText, System.Text.RegularExpressions.RegexOptions.IgnoreCase)
                If regex1.IsMatch(resultItem) Then
                    index = regex1.Match(resultItem).Index
                    isFound = True
                End If
                ' If the prefixText is found immediatly after white space then starting of the word is found so don not search any further
                If not resultItem(index).ToString() = " " Then
                    ' Expression to find beginning of the word which contains AutoTypeAheadWordSeparators followed by prefixText
                    Dim regex As System.Text.RegularExpressions.Regex = new System.Text.RegularExpressions.Regex("\\S*" + AutoTypeAheadWordSeparators + prefixText, System.Text.RegularExpressions.RegexOptions.IgnoreCase)
                    If regex.IsMatch(resultItem) Then
                        index = regex.Match(resultItem).Index
                        isFound = True
                    End If
                 End If
            End If
            ' If autoTypeAheadSearch value is wordsstartingwithsearchstring then, extract the substring only if the prefixText is found at the 
            ' beginning of the resultItem (index = 0) or a word in resultItem is found starts with prefixText. 
            If index = 0 Or isFound Or InvariantLCase(autoTypeAheadSearch).Equals("anywhereinstring") then
                If InvariantLCase(AutoTypeAheadDisplayFoundText).equals("atbeginningofmatchedstring") Then
                    ' Expression to find beginning of the word which contains prefixText
                    Dim regex1 As System.Text.RegularExpressions.Regex = new System.Text.RegularExpressions.Regex("\\S*" + prefixText, System.Text.RegularExpressions.RegexOptions.IgnoreCase)
                    '  Find the beginning of the word which contains prefexText
                    If (StringUtils.InvariantLCase(autoTypeAheadSearch).Equals("anywhereinstring") AndAlso regex1.IsMatch(resultItem)) Then
                        index = regex1.Match(resultItem).Index
                        isFound = True
                    End If
                    ' Display string from the index till end of the string if sub string from index till end is less than columnLength value.
                    If Len(resultItem) - index <= columnLength Then
                        If index = 0 Then 
                            itemToAdd = resultItem 
                        Else
                            itemToAdd = "..." & resultItem.Substring(index, Len(resultItem) - index) 
                        End If
                    Else
                        If index = 0 Then
                            itemToAdd = resultItem.Substring(index, (columnLength - 3)) & "..."
                        Else
                            'Truncate the string to show only columnLength - 6 characters as begining and trailing "..." has to be appended.
                            itemToAdd = "..." & resultItem.Substring(index , columnLength - 6) & "..." 
                        End If
                    End If
                ElseIf InvariantLCase(AutoTypeAheadDisplayFoundText).equals("inmiddleofmatchedstring") Then
                    Dim subStringBeginIndex as Integer = CType(columnLength/2, Integer)
                    If Len(resultItem) <= columnLength Then
                        itemToAdd = resultItem
                    Else
                        ' Sanity check at end of the string
                        If index + Len(prefixText) = columnLength Then
                            itemToAdd =  "..." & resultItem.Substring(index-columnLength,index)
                        ElseIf Len(resultITem) - index < subStringBeginIndex Then 
                            ' Display string from the end till columnLength value if, index is closer to the end of the string.
                            itemToAdd =  "..." & resultItem.Substring(Len(resultItem)-columnLength,Len(resultItem))
                        ElseIf index <= subStringBeginIndex Then 
                            ' Sanity chet at beginning of the string
                            itemToAdd =  resultItem.Substring(0, columnLength) & "..."
                        Else
                            ' Display string containing text before the prefixText occures and text after the prefixText
                            itemToAdd =  "..." & resultItem.Substring(index - subStringBeginIndex, columnLength) & "..." 
                        End If
                    End If
                ElseIf InvariantLCase(AutoTypeAheadDisplayFoundText).equals("atendofmatchedstring") Then
                     ' Expression to find ending of the word which contains prefexText
                    Dim regex1 as System.Text.RegularExpressions.Regex = new System.Text.RegularExpressions.Regex("\s", System.Text.RegularExpressions.RegexOptions.IgnoreCase)
                    ' Find the ending of the word which contains prefexText
                    If regex1.IsMatch(resultItem, index + 1) Then
                        index = regex1.Match(resultItem, index + 1).Index
                    Else
                        ' If the word which contains prefexText is the last word in string, regex1.IsMatch returns false.
                        index = resultItem.Length
                    End If
                    If index > Len(resultItem) Then
                        index = Len(resultItem)
                    End If
                    ' If text from beginning of the string till index is less than columnLength value then, display string from the beginning till index.
                    If  index <= columnLength Then
                        if index = Len(resultItem) then   'Make decision to append "..."
                            itemToAdd = resultItem.Substring(0,index)
                        Else
                            itemToAdd = resultItem.Substring(0,index) & "..."
                        End If
                    Else
                        If index = Len(resultItem) Then
                            itemToAdd = "..." & resultItem.Substring(index - (columnLength - 3), (columnLength - 3))
                        Else
                            'Truncate the string to show only columnLength - 6 characters as begining and trailing "..." has to be appended.
                            itemToAdd = "..." & resultItem.Substring(index - (columnLength - 6), columnLength - 6) & "..." 
                        End If
                    End If
                End If
                
                ' Remove newline character from itemToAdd
                Dim prefixTextIndex As Integer = itemToAdd.IndexOf(prefixText, StringComparison.CurrentCultureIgnoreCase)
                ' If itemToAdd contains any newline after the search text then show text only till newline
                Dim regex2 As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("(" & vbCrLf & "|" & vbLf & ")", System.Text.RegularExpressions.RegexOptions.IgnoreCase)
                Dim newLineIndexAfterPrefix As Integer = -1
                If regex2.IsMatch(itemToAdd, prefixTextIndex) Then
                    newLineIndexAfterPrefix = regex2.Match(itemToAdd, prefixTextIndex).Index
                End If
                If (newLineIndexAfterPrefix > -1) Then
                    If itemToAdd.EndsWith("...") Then
                        itemToAdd = (itemToAdd.Substring(0, newLineIndexAfterPrefix) + "...")
                    Else
                        itemToAdd = itemToAdd.Substring(0, newLineIndexAfterPrefix)
                    End If
                End If
                ' If itemToAdd contains any newline before search text then show text which comes after newline
                Dim regex3 As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("(" & vbCrLf & "|" & vbLf & ")", (System.Text.RegularExpressions.RegexOptions.IgnoreCase Or System.Text.RegularExpressions.RegexOptions.RightToLeft))
                Dim newLineIndexBeforePrefix As Integer = -1
                If regex3.IsMatch(itemToAdd, prefixTextIndex) Then
                    newLineIndexBeforePrefix = regex3.Match(itemToAdd, prefixTextIndex).Index
                End If
                If (newLineIndexBeforePrefix > -1) Then
                    If itemToAdd.StartsWith("...") Then
                        itemToAdd = ("..." + itemToAdd.Substring((newLineIndexBeforePrefix + regex3.Match(itemToAdd, prefixTextIndex).Length)))
                    Else
                        itemToAdd = itemToAdd.Substring((newLineIndexBeforePrefix + regex3.Match(itemToAdd, prefixTextIndex).Length))
                    End If
                End If

                If Not itemToAdd is nothing AndAlso Not resultList.Contains(itemToAdd) Then
                    resultList.Add(itemToAdd)
                    isAdded = true
                End If
            End If
            Return isAdded
        End Function
        
    
        Protected Overridable Sub GetPageSize()
        
            If Me.OrdersPagination.PageSize.Text.Trim <> "" Then
                Try
                    'Me.PageSize = Integer.Parse(Me.OrdersPagination.PageSize.Text)
                Catch ex As Exception
                End Try
            End If
        End Sub

        Protected Overridable Sub AddNewRecords()
            Dim newRecordList As ArrayList = New ArrayList()

            ' Loop though all the record controls and if the record control
            ' does not have a unique record id set, then create a record
            ' and add to the list.
            If Not Me.ResetData Then
                Dim rep As System.Web.UI.WebControls.Repeater = CType(Me.FindControl("OrdersTableControlRepeater"), System.Web.UI.WebControls.Repeater)
        If rep is Nothing Then Return

                Dim repItem As System.Web.UI.WebControls.RepeaterItem
                For Each repItem In rep.Items
                    ' Loop through all rows in the table, set its DataSource and call DataBind().
                    Dim recControl As OrdersTableControlRow = DirectCast(repItem.FindControl("OrdersTableControlRow"), OrdersTableControlRow)

                    If recControl.Visible AndAlso recControl.IsNewRecord() Then
                        Dim rec As OrdersRecord = New OrdersRecord()
        
                        If MiscUtils.IsValueSelected(recControl.EmployeeID) Then
                            rec.Parse(recControl.EmployeeID.SelectedItem.Value, OrdersTable.EmployeeID)
                        End If
                        If recControl.Freight.Text <> "" Then
                            rec.Parse(recControl.Freight.Text, OrdersTable.Freight)
                        End If
                        If recControl.OrderDate.Text <> "" Then
                            rec.Parse(recControl.OrderDate.Text, OrdersTable.OrderDate)
                        End If
                        If recControl.RequiredDate.Text <> "" Then
                            rec.Parse(recControl.RequiredDate.Text, OrdersTable.RequiredDate)
                        End If
                        If recControl.ShipAddress.Text <> "" Then
                            rec.Parse(recControl.ShipAddress.Text, OrdersTable.ShipAddress)
                        End If
                        If recControl.ShipCity.Text <> "" Then
                            rec.Parse(recControl.ShipCity.Text, OrdersTable.ShipCity)
                        End If
                        If recControl.ShipCountry.Text <> "" Then
                            rec.Parse(recControl.ShipCountry.Text, OrdersTable.ShipCountry)
                        End If
                        If recControl.ShipName.Text <> "" Then
                            rec.Parse(recControl.ShipName.Text, OrdersTable.ShipName)
                        End If
                        If recControl.ShippedDate.Text <> "" Then
                            rec.Parse(recControl.ShippedDate.Text, OrdersTable.ShippedDate)
                        End If
                        If recControl.ShipPostalCode.Text <> "" Then
                            rec.Parse(recControl.ShipPostalCode.Text, OrdersTable.ShipPostalCode)
                        End If
                        If recControl.ShipRegion.Text <> "" Then
                            rec.Parse(recControl.ShipRegion.Text, OrdersTable.ShipRegion)
                        End If
                        If MiscUtils.IsValueSelected(recControl.ShipVia) Then
                            rec.Parse(recControl.ShipVia.SelectedItem.Value, OrdersTable.ShipVia)
                        End If
                        newRecordList.Add(rec)
                    End If
                Next
            End If

            ' Add any new record to the list.
            Dim index As Integer = 0
            For index = 1 To Me.AddNewRecord
                newRecordList.Insert(0, New OrdersRecord())
            Next
            Me.AddNewRecord = 0

            ' Finally, add any new records to the DataSource.
            If newRecordList.Count > 0 Then
                Dim finalList As ArrayList = New ArrayList(Me.DataSource)
                finalList.InsertRange(0, newRecordList)

                Me.DataSource = DirectCast(finalList.ToArray(GetType(OrdersRecord)), OrdersRecord())
            End If

        End Sub

        
        Public Sub AddToDeletedRecordIds(ByVal rec As OrdersTableControlRow)
            If rec.IsNewRecord() Then
                Return
            End If

            If Not Me.DeletedRecordIds Is Nothing AndAlso Me.DeletedRecordIds.Trim <> "" Then
                Me.DeletedRecordIds &= ","
            End If

            Me.DeletedRecordIds &= "[" & rec.RecordUniqueId & "]"
        End Sub

        Protected Overridable Function InDeletedRecordIds(ByVal rec As OrdersTableControlRow) As Boolean
            If Me.DeletedRecordIds Is Nothing OrElse Me.DeletedRecordIds.Trim = "" Then
                Return False
            End If

            Return Me.DeletedRecordIds.IndexOf("[" & rec.RecordUniqueId & "]") >= 0
        End Function

        Private _DeletedRecordIds As String
        Public Property DeletedRecordIds() As String
            Get
                Return Me._DeletedRecordIds
            End Get

            Set(ByVal value As String)
                Me._DeletedRecordIds = value
            End Set
        End Property
        
        Protected Overridable Sub Control_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.PreRender
            Try
                DbUtils.StartTransaction
                
                If Not Me.Page.ErrorOnPage AndAlso (Me.Page.IsPageRefresh OrElse Me.DataChanged OrElse Me.ResetData) Then
                    Me.LoadData()
                    Me.DataBind()
                End If
                
            Catch ex As Exception
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
                DbUtils.EndTransaction
            End Try
        End Sub
        
        Protected Overrides Sub SaveControlsToSession()
            MyBase.SaveControlsToSession()

            ' Save filter controls to values to session.
        
            
            ' Save table control properties to the session.
            If Not Me.CurrentSortOrder Is Nothing Then
                Me.SaveToSession(Me, "Order_By", Me.CurrentSortOrder.ToXmlString())
            End If
            Me.SaveToSession(Me, "Page_Index", Me.PageIndex.ToString())
            Me.SaveToSession(Me, "Page_Size", Me.PageSize.ToString())
        
            Me.SaveToSession(Me, "DeletedRecordIds", Me.DeletedRecordIds)  
        
        End Sub
        
        Protected  Sub SaveControlsToSession_Ajax()
            ' Save filter controls to values to session.
          
            HttpContext.Current.Session("AppRelativeVirtualPath") = Me.Page.AppRelativeVirtualPath
         
        End Sub
        
        Protected Overrides Sub ClearControlsFromSession()
            MyBase.ClearControlsFromSession()

            ' Clear filter controls values from the session.
        
            
            ' Clear table properties from the session.
            Me.RemoveFromSession(Me, "Order_By")
            Me.RemoveFromSession(Me, "Page_Index")
            Me.RemoveFromSession(Me, "Page_Size")
            
            Me.RemoveFromSession(Me, "DeletedRecordIds")  
            
        End Sub

        Protected Overrides Sub LoadViewState(ByVal savedState As Object)
            MyBase.LoadViewState(savedState)

            Dim orderByStr As String = CType(ViewState("OrdersTableControl_OrderBy"), String)
            If Not orderByStr Is Nothing AndAlso orderByStr.Trim <> "" Then
                Me.CurrentSortOrder = BaseClasses.Data.OrderBy.FromXmlString(orderByStr)
            Else
                Me.CurrentSortOrder = New OrderBy(True, True)
            End If

            Dim pageIndex As String = CType(ViewState("Page_Index"), String)
            If Not pageIndex Is Nothing Then
                Me.PageIndex = CInt(pageIndex)
            End If

            Dim pageSize As String = CType(ViewState("Page_Size"), String)
            If Not pageSize Is Nothing Then
                Me.PageSize = CInt(pageSize)
            End If
        
            Me.DeletedRecordIds = CType(Me.ViewState("DeletedRecordIds"), String)
        
        End Sub

        Protected Overrides Function SaveViewState() As Object
            
            If Not Me.CurrentSortOrder Is Nothing Then
                Me.ViewState("OrdersTableControl_OrderBy") = Me.CurrentSortOrder.ToXmlString()
            End If
            
            Me.ViewState("Page_Index") = Me.PageIndex
            Me.ViewState("Page_Size") = Me.PageSize
        
            Me.ViewState("DeletedRecordIds") = Me.DeletedRecordIds
        
            Return MyBase.SaveViewState()

        End Function

        ' Generate the event handling functions for pagination events.
        
        ' event handler for ImageButton
        Public Overridable Sub OrdersPagination_FirstPage_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                
            Me.PageIndex = 0
            Me.DataChanged = True
      
            Catch ex As Exception
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
    
            End Try
                  
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub OrdersPagination_LastPage_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                
            Me.DisplayLastPage = True
            Me.DataChanged = True
      
            Catch ex As Exception
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
    
            End Try
                  
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub OrdersPagination_NextPage_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                
            Me.PageIndex += 1
            Me.DataChanged = True
      
            Catch ex As Exception
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
    
            End Try
                  
        End Sub
            
        ' event handler for LinkButton
        Public Overridable Sub OrdersPagination_PageSizeButton_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Try
                
            Me.DataChanged = True
      
            Me.PageSize = Integer.Parse(Me.OrdersPagination.PageSize.Text)
      
            Me.PageIndex = Integer.Parse(Me.OrdersPagination.CurrentPage.Text) - 1
          
            Catch ex As Exception
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
    
            End Try
    
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub OrdersPagination_PreviousPage_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                
            If Me.PageIndex > 0 Then
                Me.PageIndex -= 1
                Me.DataChanged = True
            End If
      
            Catch ex As Exception
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
    
            End Try
                  
        End Sub
            

        ' Generate the event handling functions for sorting events.
        
        ' event handler for FieldSort
        Public Overridable Sub EmployeeIDLabel1_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(OrdersTable.EmployeeID)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(OrdersTable.EmployeeID, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            
        ' event handler for FieldSort
        Public Overridable Sub FreightLabel_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(OrdersTable.Freight)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(OrdersTable.Freight, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            
        ' event handler for FieldSort
        Public Overridable Sub OrderDateLabel_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(OrdersTable.OrderDate)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(OrdersTable.OrderDate, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            
        ' event handler for FieldSort
        Public Overridable Sub RequiredDateLabel_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(OrdersTable.RequiredDate)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(OrdersTable.RequiredDate, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            
        ' event handler for FieldSort
        Public Overridable Sub ShipAddressLabel_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(OrdersTable.ShipAddress)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(OrdersTable.ShipAddress, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            
        ' event handler for FieldSort
        Public Overridable Sub ShipCityLabel_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(OrdersTable.ShipCity)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(OrdersTable.ShipCity, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            
        ' event handler for FieldSort
        Public Overridable Sub ShipCountryLabel_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(OrdersTable.ShipCountry)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(OrdersTable.ShipCountry, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            
        ' event handler for FieldSort
        Public Overridable Sub ShipNameLabel_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(OrdersTable.ShipName)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(OrdersTable.ShipName, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            
        ' event handler for FieldSort
        Public Overridable Sub ShippedDateLabel_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(OrdersTable.ShippedDate)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(OrdersTable.ShippedDate, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            
        ' event handler for FieldSort
        Public Overridable Sub ShipPostalCodeLabel_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(OrdersTable.ShipPostalCode)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(OrdersTable.ShipPostalCode, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            
        ' event handler for FieldSort
        Public Overridable Sub ShipRegionLabel_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(OrdersTable.ShipRegion)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(OrdersTable.ShipRegion, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            
        ' event handler for FieldSort
        Public Overridable Sub ShipViaLabel1_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Dim sd As OrderByItem = Me.CurrentSortOrder.Find(OrdersTable.ShipVia)
            If Not sd Is Nothing Then
                sd.Reverse()
            Else
                Me.CurrentSortOrder.Reset()
                Me.CurrentSortOrder.Add(OrdersTable.ShipVia, OrderByItem.OrderDir.Asc)
            End If

            Me.DataChanged = True
              
        End Sub
            

        ' Generate the event handling functions for button events.
        
        ' event handler for ImageButton
        Public Overridable Sub OrdersAddButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                DbUtils.StartTransaction
                
            Me.AddNewRecord = 1
            Me.DataChanged = True
      Me.Page.CommitTransaction(sender)
          
            Catch ex As Exception
                Me.Page.RollBackTransaction(sender)
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
                DbUtils.EndTransaction
            End Try
                  
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub OrdersDeleteButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                DbUtils.StartTransaction
                
            If(Not Me.Page.IsPageRefresh) Then
        
                Me.DeleteSelectedRecords(True)
          
            End If
      Me.Page.CommitTransaction(sender)
          
            Catch ex As Exception
                Me.Page.RollBackTransaction(sender)
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
                DbUtils.EndTransaction
            End Try
                  
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub OrdersResetButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                
              Me.CurrentSortOrder.Reset()
              If Me.InSession(Me, "Order_By") Then
                  Me.CurrentSortOrder = OrderBy.FromXmlString(Me.GetFromSession(Me, "Order_By", Nothing))
              Else
                  Me.CurrentSortOrder = New OrderBy(True, True)
          
              End If
              

        Me.DataChanged = True
            
            Catch ex As Exception
                Me.Page.ErrorOnPage = True
    
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
    
            End Try
                  
        End Sub
            
      

        ' Generate the event handling functions for filter and search events.
        

        ' pagination properties
        Private _PageSize As Integer
        Public Property PageSize() As Integer
            Get
                Return Me._PageSize
            End Get
            Set(ByVal value As Integer)
                Me._PageSize = value
            End Set
        End Property

        Private _PageIndex As Integer
        Public Property PageIndex() As Integer
            Get
                ' Return the PageIndex
                Return Me._PageIndex
            End Get
            Set(ByVal value As Integer)
                Me._PageIndex = value
            End Set
        End Property

        Private _TotalRecords As Integer
        Public Property TotalRecords() As Integer
            Get
                Return Me._TotalRecords
            End Get
            Set(ByVal value As Integer)
                If Me.PageSize > 0 Then
                    Me.TotalPages = CInt(Math.Ceiling(value / Me.PageSize))
                End If

                Me._TotalRecords = value
            End Set
        End Property

        Private _TotalPages As Integer
        Public Property TotalPages() As Integer
            Get
                Return Me._TotalPages
            End Get
            Set(ByVal value As Integer)
                Me._TotalPages = value
            End Set
        End Property

        Private _DisplayLastPage As Boolean
        Public Property DisplayLastPage() As Boolean
            Get
                Return Me._DisplayLastPage
            End Get
            Set(ByVal value As Boolean)
                Me._DisplayLastPage = value
            End Set
        End Property

        Private _DataChanged As Boolean = False
        Public Property DataChanged() As Boolean
            Get
                Return Me._DataChanged
            End Get
            Set(ByVal value As Boolean)
                Me._DataChanged = value
            End Set
        End Property
        
        Private _ResetData As Boolean = False
        Public Property ResetData() As Boolean
            Get
                Return Me._ResetData
            End Get
            Set(ByVal value As Boolean)
                Me._ResetData = value
            End Set
        End Property

        Private _AddNewRecord As Integer = 0
        Public Property AddNewRecord() As Integer
            Get
                Return Me._AddNewRecord
            End Get
            Set(ByVal value As Integer)
                Me._AddNewRecord = value
            End Set
        End Property

        Private _CurrentSortOrder As OrderBy = Nothing
        Public Property CurrentSortOrder() As OrderBy
            Get
                Return Me._CurrentSortOrder
            End Get
            Set(ByVal value As BaseClasses.Data.OrderBy)
                Me._CurrentSortOrder = value
            End Set
        End Property

        Private _DataSource() As OrdersRecord = Nothing
        Public Property DataSource() As OrdersRecord ()
            Get
                Return Me._DataSource
            End Get
            Set(ByVal value() As OrdersRecord)
                Me._DataSource = value
            End Set
        End Property

#Region "Helper Properties"
        
        Public ReadOnly Property EmployeeIDLabel1() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "EmployeeIDLabel1"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
        Public ReadOnly Property FreightLabel() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "FreightLabel"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
        Public ReadOnly Property OrderDateLabel() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "OrderDateLabel"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
        Public ReadOnly Property OrdersAddButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "OrdersAddButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property OrdersDeleteButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "OrdersDeleteButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property OrdersPagination() As UseDAL.UI.IPagination
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "OrdersPagination"), UseDAL.UI.IPagination)
          End Get
          End Property
        
        Public ReadOnly Property OrdersResetButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "OrdersResetButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property OrdersToggleAll() As System.Web.UI.WebControls.CheckBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "OrdersToggleAll"), System.Web.UI.WebControls.CheckBox)
            End Get
        End Property
        
        Public ReadOnly Property RequiredDateLabel() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "RequiredDateLabel"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
        Public ReadOnly Property ShipAddressLabel() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ShipAddressLabel"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
        Public ReadOnly Property ShipCityLabel() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ShipCityLabel"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
        Public ReadOnly Property ShipCountryLabel() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ShipCountryLabel"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
        Public ReadOnly Property ShipNameLabel() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ShipNameLabel"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
        Public ReadOnly Property ShippedDateLabel() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ShippedDateLabel"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
        Public ReadOnly Property ShipPostalCodeLabel() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ShipPostalCodeLabel"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
        Public ReadOnly Property ShipRegionLabel() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ShipRegionLabel"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
        Public ReadOnly Property ShipViaLabel1() As System.Web.UI.WebControls.LinkButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ShipViaLabel1"), System.Web.UI.WebControls.LinkButton)
            End Get
        End Property
        
#End Region

#Region "Helper Functions"
        
        Public Overrides Overloads Function ModifyRedirectUrl(url As String, arg As String, ByVal bEncrypt As Boolean) As String
            Return Me.Page.EvaluateExpressions(url, arg, bEncrypt, Me)
        End Function
      
           Public Overrides Overloads Function EvaluateExpressions(url As String, arg As String, ByVal bEncrypt As Boolean) As String
            Dim needToProcess As Boolean = AreAnyUrlParametersForMe(url, arg)
            If (needToProcess) Then
                Dim recCtl As OrdersTableControlRow = Me.GetSelectedRecordControl()
                If recCtl Is Nothing AndAlso url.IndexOf("{") >= 0 Then
                    ' Localization.
                    Throw New Exception(Page.GetResourceValue("Err:NoRecSelected", "UseDAL"))
                End If

                Dim rec As OrdersRecord = Nothing
                If Not recCtl Is Nothing Then
                    rec = recCtl.GetRecord()
                End If
                Return EvaluateExpressions(url, arg, rec, bEncrypt)
            End If
            Return url
        End Function
          
        Public Overridable Function GetSelectedRecordIndex() As Integer
            Dim counter As Integer = 0
            Dim recControl As OrdersTableControlRow
            For Each recControl In Me.GetRecordControls()
                If recControl.OrdersRecordRowSelection.Checked Then
                    Return counter
                End If
                counter += 1
            Next
            Return -1
        End Function
        
        Public Overridable Function GetSelectedRecordControl() As OrdersTableControlRow
            Dim selectedList() As OrdersTableControlRow = Me.GetSelectedRecordControls()
            If selectedList.Length = 0 Then
                Return Nothing
            End If
            Return selectedList(0)
          
        End Function

        Public Overridable Function GetSelectedRecordControls() As OrdersTableControlRow()
        
            Dim selectedList As ArrayList = New ArrayList(25)
            Dim recControl As OrdersTableControlRow
            For Each recControl In Me.GetRecordControls()
                If recControl.OrdersRecordRowSelection.Checked Then
                    selectedList.Add(recControl)
                End If
            Next
            Return DirectCast(selectedList.ToArray(GetType(OrdersTableControlRow)), OrdersTableControlRow())
          
        End Function

        Public Overridable Sub DeleteSelectedRecords(ByVal deferDeletion As Boolean)
            Dim recList() As OrdersTableControlRow = Me.GetSelectedRecordControls()
            If recList.Length = 0 Then
                ' Localization.
                Throw New Exception(Page.GetResourceValue("Err:NoRecSelected", "UseDAL"))
            End If
            
            Dim recCtl As OrdersTableControlRow
            For Each recCtl In recList
                If deferDeletion Then
                    If Not recCtl.IsNewRecord Then
                
                        Me.AddToDeletedRecordIds(recCtl)
                  
                    End If
                    recCtl.Visible = False
                
                    recCtl.OrdersRecordRowSelection.Checked = False
                
                Else
                
                    recCtl.Delete()
                    Me.DataChanged = True
                    Me.ResetData = True
                  
                End If
            Next
        End Sub

        Public Function GetRecordControls() As OrdersTableControlRow()
            Dim recList As ArrayList = New ArrayList()
            Dim rep As System.Web.UI.WebControls.Repeater = CType(Me.FindControl("OrdersTableControlRepeater"), System.Web.UI.WebControls.Repeater)
      If rep is Nothing Then Return Nothing
            Dim repItem As System.Web.UI.WebControls.RepeaterItem

            For Each repItem In rep.Items
                Dim recControl As OrdersTableControlRow = DirectCast(repItem.FindControl("OrdersTableControlRow"), OrdersTableControlRow)
                recList.Add(recControl)
            Next

            Return DirectCast(recList.ToArray(GetType(OrdersTableControlRow)), OrdersTableControlRow())
        End Function

        Public Shadows ReadOnly Property Page() As BaseApplicationPage
            Get
                Return DirectCast(MyBase.Page, BaseApplicationPage)
            End Get
        End Property

#End Region

    

End Class

  
' Base class for the CustomersRecordControl control on the AddCustomers page.
' Do not modify this class. Instead override any method in CustomersRecordControl.
Public Class BaseCustomersRecordControl
        Inherits UseDAL.UI.BaseApplicationRecordControl

        '  To customize, override this method in CustomersRecordControl.
      Protected Overridable Sub Control_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Init

      
      ' Setup the pagination events.
      
          
        ' Setup the filter and search events.
        
      
            ' Register the event handlers.
        
        End Sub

        '  To customize, override this method in CustomersRecordControl.
        Protected Overridable Sub Control_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
        
    
    End Sub

        ' Read data from database.  To customize, override this method in CustomersRecordControl.
        Public Overridable Sub LoadData()        
        
            If Not Me.RecordUniqueId Is Nothing AndAlso Me.RecordUniqueId.Trim <> "" Then
                Me.DataSource = CustomersTable.GetRecord(Me.RecordUniqueId, True)
                Return
            End If
        
            Dim wc As WhereClause = Me.CreateWhereClause()
            
            If wc Is Nothing OrElse Not wc.RunQuery Then
                Me.DataSource = New CustomersRecord()
                
                Return
            End If
            

          
              
            ' Retrieve the record from the database.
            
            Dim recList() As CustomersRecord = CustomersTable.GetRecords(wc, Nothing, 0, 2)
            If recList.Length = 0 Then
                
                wc.RunQuery = False
                                    
                
                Return
            End If
              
            Me.DataSource = CType(CustomersRecord.Copy(recList(0), False), CustomersRecord)
                  
        End Sub

        ' Populate the UI controls using the DataSource.  To customize, override this method in CustomersRecordControl.
        Public Overrides Sub DataBind()

            MyBase.DataBind()

            ' Make sure that the DataSource is initialized.
            If Me.DataSource Is Nothing Then
                Return
            End If
        
      
            ' For each field, check to see if a value is specified.  If a value is specified,
            ' then format the value for display.  If no value is specified, use the default value (formatted).

        
            If Me.DataSource.AddressSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(CustomersTable.Address)
                Me.Address.Text = formattedValue
              
            Else      
                Me.Address.Text = CustomersTable.Address.Format(CustomersTable.Address.DefaultValue)
              
            End If
                    
            If Me.DataSource.CitySpecified Then
                Dim formattedValue As String = Me.DataSource.Format(CustomersTable.City)
                Me.City.Text = formattedValue
              
            Else      
                Me.City.Text = CustomersTable.City.Format(CustomersTable.City.DefaultValue)
              
            End If
                    
            If Me.DataSource.CompanyNameSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(CustomersTable.CompanyName)
                Me.CompanyName.Text = formattedValue
              
            Else      
                Me.CompanyName.Text = CustomersTable.CompanyName.Format(CustomersTable.CompanyName.DefaultValue)
              
            End If
                    
            If Me.DataSource.ContactNameSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(CustomersTable.ContactName)
                Me.ContactName.Text = formattedValue
              
            Else      
                Me.ContactName.Text = CustomersTable.ContactName.Format(CustomersTable.ContactName.DefaultValue)
              
            End If
                    
            If Me.DataSource.ContactTitleSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(CustomersTable.ContactTitle)
                Me.ContactTitle.Text = formattedValue
              
            Else      
                Me.ContactTitle.Text = CustomersTable.ContactTitle.Format(CustomersTable.ContactTitle.DefaultValue)
              
            End If
                    
            If Me.DataSource.CountrySpecified Then
                Dim formattedValue As String = Me.DataSource.Format(CustomersTable.Country)
                Me.Country.Text = formattedValue
              
            Else      
                Me.Country.Text = CustomersTable.Country.Format(CustomersTable.Country.DefaultValue)
              
            End If
                    
            If Me.DataSource.CustomerIDSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(CustomersTable.CustomerID)
                Me.CustomerID.Text = formattedValue
              
            Else      
                Me.CustomerID.Text = CustomersTable.CustomerID.Format(CustomersTable.CustomerID.DefaultValue)
              
            End If
                    
            If Me.DataSource.EmailAddressSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(CustomersTable.EmailAddress)
                Me.EmailAddress.Text = formattedValue
              
            Else      
                Me.EmailAddress.Text = CustomersTable.EmailAddress.Format(CustomersTable.EmailAddress.DefaultValue)
              
            End If
                    
            If Me.DataSource.FaxSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(CustomersTable.Fax)
                Me.Fax.Text = formattedValue
              
            Else      
                Me.Fax.Text = CustomersTable.Fax.Format(CustomersTable.Fax.DefaultValue)
              
            End If
                    
            If Me.DataSource.PhoneSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(CustomersTable.Phone)
                Me.Phone.Text = formattedValue
              
            Else      
                Me.Phone.Text = CustomersTable.Phone.Format(CustomersTable.Phone.DefaultValue)
              
            End If
                    
            If Me.DataSource.PostalCodeSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(CustomersTable.PostalCode)
                Me.PostalCode.Text = formattedValue
              
            Else      
                Me.PostalCode.Text = CustomersTable.PostalCode.Format(CustomersTable.PostalCode.DefaultValue)
              
            End If
                    
            If Me.DataSource.RegionSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(CustomersTable.Region)
                Me.Region.Text = formattedValue
              
            Else      
                Me.Region.Text = CustomersTable.Region.Format(CustomersTable.Region.DefaultValue)
              
            End If
                    
            Me.IsNewRecord = True
            If Me.DataSource.IsCreated Then
                Me.IsNewRecord = False
        
                Me.RecordUniqueId = Me.DataSource.GetID.ToXmlString()
            End If

            

            ' Load data for each record and table UI control.
            ' Ordering is important because child controls get 
            ' their parent ids from their parent UI controls.
            Dim shouldResetControl as Boolean = False
            
        Dim recOrdersTableControl as OrdersTableControl = DirectCast(MiscUtils.FindControlRecursively(Me.Page, "OrdersTableControl"), OrdersTableControl)
        
            If (shouldResetControl OrElse Me.Page.IsPageRefresh)
              recOrdersTableControl.ResetControl()
            End IF
        
        recOrdersTableControl.LoadData()
        recOrdersTableControl.DataBind()
        
      End Sub

        
        Public Overridable Sub ResetControl()
        
          
          End Sub
        
        
        ' To customize, override this method in CustomersRecordControl.
        Public Overridable Sub SaveData()

            ' 1. Load the existing record from the database. Since we save the entire record, this ensures 
            ' that fields that are not displayed also properly initialized.
            Me.LoadData()
        
              
            ' 2. Validate the data.  Override in CustomersRecordControl to add custom validation.
            Me.Validate()

            ' 3. Set the values in the record with data from UI controls.  Override in CustomersRecordControl to set additional fields.
            Me.GetUIData()

            ' 4. Save in the database.
            ' We should not save the record if the data did not change. This
            ' will save a database hit and avoid triggering any database triggers.
            If Me.DataSource.IsAnyValueChanged Then
                ' Save record to database but do not commit.
                ' Auto generated ids are available after saving for use by child (dependent) records.
                Me.DataSource.Save()
              
            End If
            Me.DataChanged = True
            Me.ResetData = True
            ' Reseting of Me.IsNewRecord is moved to Save button's click even handler.
            ' Me.IsNewRecord() = False
            
        Dim recOrdersTableControl as OrdersTableControl = DirectCast(MiscUtils.FindControlRecursively(Me.Page, "OrdersTableControl"), OrdersTableControl)
        recOrdersTableControl.SaveData()
        
        End Sub

        ' To customize, override this method in CustomersRecordControl.
        Public Overridable Sub GetUIData()
            
            Dim clearDataSource As Boolean = False
            Dim col As BaseColumn
            For Each col In CustomersRecord.TableUtils.TableDefinition.Columns()
                If col.ColumnType.Equals(BaseColumn.ColumnTypes.Unique_Identifier) Then
                    clearDataSource = True
                End If
            Next

            If clearDataSource Then
                Me.DataSource = New CustomersRecord()
            End If
            
            Me.DataSource.Parse(Me.Address.Text, CustomersTable.Address)
                          
            Me.DataSource.Parse(Me.City.Text, CustomersTable.City)
                          
            Me.DataSource.Parse(Me.CompanyName.Text, CustomersTable.CompanyName)
                          
            Me.DataSource.Parse(Me.ContactName.Text, CustomersTable.ContactName)
                          
            Me.DataSource.Parse(Me.ContactTitle.Text, CustomersTable.ContactTitle)
                          
            Me.DataSource.Parse(Me.Country.Text, CustomersTable.Country)
                          
            Me.DataSource.Parse(Me.CustomerID.Text, CustomersTable.CustomerID)
                          
            Me.DataSource.Parse(Me.EmailAddress.Text, CustomersTable.EmailAddress)
                          
            Me.DataSource.Parse(Me.Fax.Text, CustomersTable.Fax)
                          
            Me.DataSource.Parse(Me.Phone.Text, CustomersTable.Phone)
                          
            Me.DataSource.Parse(Me.PostalCode.Text, CustomersTable.PostalCode)
                          
            Me.DataSource.Parse(Me.Region.Text, CustomersTable.Region)
                          
        End Sub

        
      
        ' To customize, override this method in CustomersRecordControl.
        Public Overridable Function CreateWhereClause() As WhereClause
        
            Dim wc As WhereClause
            CustomersTable.Instance.InnerFilter = Nothing
            wc = New WhereClause()
            ' Compose the WHERE clause consiting of:
            ' 1. Static clause defined at design time.
            ' 2. User selected filter criteria.
            ' 3. User selected search criteria.
            
            ' Retrieve the record id from the URL parameter.
            Dim recId As String = Me.Page.Request.QueryString.Item("Customers")
            If recId Is Nothing OrElse recId.Trim = "" Then
            ' Get the error message from the application resource file.
            Return Nothing
            End If
              
            HttpContext.Current.Session("QueryString in AddCustomers") = recId
                
            If KeyValue.IsXmlKey(recId) Then
            Dim pkValue As KeyValue = KeyValue.XmlToKey(recId)
                    
                wc.iAND(CustomersTable.CustomerID, BaseFilter.ComparisonOperator.EqualsTo, pkValue.GetColumnValue(CustomersTable.CustomerID).ToString())
            Else
                    
                wc.iAND(CustomersTable.CustomerID, BaseFilter.ComparisonOperator.EqualsTo, recId)
            End If
                
            Return wc
          
        End Function
        
        ' This CreateWhereClause is used for loading list of suggestions for Auto Type-Ahead feature.
        Public Overridable Function CreateWhereClause(ByVal searchText as String, ByVal fromSearchControl as String, ByVal AutoTypeAheadSearch as String, ByVal AutoTypeAheadWordSeparators as String) As WhereClause
            CustomersTable.Instance.InnerFilter = Nothing
            Dim wc As WhereClause = New WhereClause()
            ' Compose the WHERE clause consiting of:
            ' 1. Static clause defined at design time.
            ' 2. User selected filter criteria.
            ' 3. User selected search criteria.
            Dim appRelativeVirtualPath As String = CType(HttpContext.Current.Session("AppRelativeVirtualPath"), String)
            
            
            ' Adds clauses if values are selected in Filter controls which are configured in the page.
          
       
          
            Return wc
        End Function
          
          
        'Formats the resultItem and adds it to the list of suggestions.
        Public Overridable Function FormatSuggestions(ByVal prefixText As String, ByVal resultItem as String, _
                                                 ByVal columnLength As Integer, ByVal AutoTypeAheadDisplayFoundText as String, _
                                                 ByVal autoTypeAheadSearch as String, ByVal AutoTypeAheadWordSeparators as String, _
                                                 ByVal resultList as ArrayList) as Boolean
            Dim index As Integer = resultItem.ToUpper(System.Threading.Thread.CurrentThread.CurrentCulture).IndexOf(prefixText.ToUpper(System.Threading.Thread.CurrentThread.CurrentCulture))
            Dim itemToAdd As String = ""
            Dim isFound as Boolean = False
            Dim isAdded as Boolean = False
            ' Get the index where prfixt is at the beginning of resultItem. If not found then, index of word which begins with prefixText.
            If InvariantLCase(autoTypeAheadSearch).equals("wordsstartingwithsearchstring") and not index = 0 Then
                ' Expression to find word which contains AutoTypeAheadWordSeparators followed by prefixText
                Dim regex1 As System.Text.RegularExpressions.Regex = new System.Text.RegularExpressions.Regex( AutoTypeAheadWordSeparators + prefixText, System.Text.RegularExpressions.RegexOptions.IgnoreCase)
                If regex1.IsMatch(resultItem) Then
                    index = regex1.Match(resultItem).Index
                    isFound = True
                End If
                ' If the prefixText is found immediatly after white space then starting of the word is found so don not search any further
                If not resultItem(index).ToString() = " " Then
                    ' Expression to find beginning of the word which contains AutoTypeAheadWordSeparators followed by prefixText
                    Dim regex As System.Text.RegularExpressions.Regex = new System.Text.RegularExpressions.Regex("\\S*" + AutoTypeAheadWordSeparators + prefixText, System.Text.RegularExpressions.RegexOptions.IgnoreCase)
                    If regex.IsMatch(resultItem) Then
                        index = regex.Match(resultItem).Index
                        isFound = True
                    End If
                 End If
            End If
            ' If autoTypeAheadSearch value is wordsstartingwithsearchstring then, extract the substring only if the prefixText is found at the 
            ' beginning of the resultItem (index = 0) or a word in resultItem is found starts with prefixText. 
            If index = 0 Or isFound Or InvariantLCase(autoTypeAheadSearch).Equals("anywhereinstring") then
                If InvariantLCase(AutoTypeAheadDisplayFoundText).equals("atbeginningofmatchedstring") Then
                    ' Expression to find beginning of the word which contains prefixText
                    Dim regex1 As System.Text.RegularExpressions.Regex = new System.Text.RegularExpressions.Regex("\\S*" + prefixText, System.Text.RegularExpressions.RegexOptions.IgnoreCase)
                    '  Find the beginning of the word which contains prefexText
                    If (StringUtils.InvariantLCase(autoTypeAheadSearch).Equals("anywhereinstring") AndAlso regex1.IsMatch(resultItem)) Then
                        index = regex1.Match(resultItem).Index
                        isFound = True
                    End If
                    ' Display string from the index till end of the string if sub string from index till end is less than columnLength value.
                    If Len(resultItem) - index <= columnLength Then
                        If index = 0 Then 
                            itemToAdd = resultItem 
                        Else
                            itemToAdd = "..." & resultItem.Substring(index, Len(resultItem) - index) 
                        End If
                    Else
                        If index = 0 Then
                            itemToAdd = resultItem.Substring(index, (columnLength - 3)) & "..."
                        Else
                            'Truncate the string to show only columnLength - 6 characters as begining and trailing "..." has to be appended.
                            itemToAdd = "..." & resultItem.Substring(index , columnLength - 6) & "..." 
                        End If
                    End If
                ElseIf InvariantLCase(AutoTypeAheadDisplayFoundText).equals("inmiddleofmatchedstring") Then
                    Dim subStringBeginIndex as Integer = CType(columnLength/2, Integer)
                    If Len(resultItem) <= columnLength Then
                        itemToAdd = resultItem
                    Else
                        ' Sanity check at end of the string
                        If index + Len(prefixText) = columnLength Then
                            itemToAdd =  "..." & resultItem.Substring(index-columnLength,index)
                        ElseIf Len(resultITem) - index < subStringBeginIndex Then 
                            ' Display string from the end till columnLength value if, index is closer to the end of the string.
                            itemToAdd =  "..." & resultItem.Substring(Len(resultItem)-columnLength,Len(resultItem))
                        ElseIf index <= subStringBeginIndex Then 
                            ' Sanity chet at beginning of the string
                            itemToAdd =  resultItem.Substring(0, columnLength) & "..."
                        Else
                            ' Display string containing text before the prefixText occures and text after the prefixText
                            itemToAdd =  "..." & resultItem.Substring(index - subStringBeginIndex, columnLength) & "..." 
                        End If
                    End If
                ElseIf InvariantLCase(AutoTypeAheadDisplayFoundText).equals("atendofmatchedstring") Then
                     ' Expression to find ending of the word which contains prefexText
                    Dim regex1 as System.Text.RegularExpressions.Regex = new System.Text.RegularExpressions.Regex("\s", System.Text.RegularExpressions.RegexOptions.IgnoreCase)
                    ' Find the ending of the word which contains prefexText
                    If regex1.IsMatch(resultItem, index + 1) Then
                        index = regex1.Match(resultItem, index + 1).Index
                    Else
                        ' If the word which contains prefexText is the last word in string, regex1.IsMatch returns false.
                        index = resultItem.Length
                    End If
                    If index > Len(resultItem) Then
                        index = Len(resultItem)
                    End If
                    ' If text from beginning of the string till index is less than columnLength value then, display string from the beginning till index.
                    If  index <= columnLength Then
                        if index = Len(resultItem) then   'Make decision to append "..."
                            itemToAdd = resultItem.Substring(0,index)
                        Else
                            itemToAdd = resultItem.Substring(0,index) & "..."
                        End If
                    Else
                        If index = Len(resultItem) Then
                            itemToAdd = "..." & resultItem.Substring(index - (columnLength - 3), (columnLength - 3))
                        Else
                            'Truncate the string to show only columnLength - 6 characters as begining and trailing "..." has to be appended.
                            itemToAdd = "..." & resultItem.Substring(index - (columnLength - 6), columnLength - 6) & "..." 
                        End If
                    End If
                End If
                
                ' Remove newline character from itemToAdd
                Dim prefixTextIndex As Integer = itemToAdd.IndexOf(prefixText, StringComparison.CurrentCultureIgnoreCase)
                ' If itemToAdd contains any newline after the search text then show text only till newline
                Dim regex2 As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("(" & vbCrLf & "|" & vbLf & ")", System.Text.RegularExpressions.RegexOptions.IgnoreCase)
                Dim newLineIndexAfterPrefix As Integer = -1
                If regex2.IsMatch(itemToAdd, prefixTextIndex) Then
                    newLineIndexAfterPrefix = regex2.Match(itemToAdd, prefixTextIndex).Index
                End If
                If (newLineIndexAfterPrefix > -1) Then
                    If itemToAdd.EndsWith("...") Then
                        itemToAdd = (itemToAdd.Substring(0, newLineIndexAfterPrefix) + "...")
                    Else
                        itemToAdd = itemToAdd.Substring(0, newLineIndexAfterPrefix)
                    End If
                End If
                ' If itemToAdd contains any newline before search text then show text which comes after newline
                Dim regex3 As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex("(" & vbCrLf & "|" & vbLf & ")", (System.Text.RegularExpressions.RegexOptions.IgnoreCase Or System.Text.RegularExpressions.RegexOptions.RightToLeft))
                Dim newLineIndexBeforePrefix As Integer = -1
                If regex3.IsMatch(itemToAdd, prefixTextIndex) Then
                    newLineIndexBeforePrefix = regex3.Match(itemToAdd, prefixTextIndex).Index
                End If
                If (newLineIndexBeforePrefix > -1) Then
                    If itemToAdd.StartsWith("...") Then
                        itemToAdd = ("..." + itemToAdd.Substring((newLineIndexBeforePrefix + regex3.Match(itemToAdd, prefixTextIndex).Length)))
                    Else
                        itemToAdd = itemToAdd.Substring((newLineIndexBeforePrefix + regex3.Match(itemToAdd, prefixTextIndex).Length))
                    End If
                End If

                If Not itemToAdd is nothing AndAlso Not resultList.Contains(itemToAdd) Then
                    resultList.Add(itemToAdd)
                    isAdded = true
                End If
            End If
            Return isAdded
        End Function
        

        ' To customize, override this method in CustomersRecordControl.
        Public Overridable Sub Validate() 
            ' Initially empty.  Override to add custom validation.
        End Sub

        Public Overridable Sub Delete()
        
            If Me.IsNewRecord() Then
                Return
            End If

            Dim pk As KeyValue = KeyValue.XmlToKey(Me.RecordUniqueId)
            CustomersTable.DeleteRecord(pk)

          
        End Sub

        Protected Overridable Sub Control_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.PreRender
            Try
                DbUtils.StartTransaction()

                If Not Me.Page.ErrorOnPage AndAlso (Me.Page.IsPageRefresh OrElse Me.DataChanged OrElse Me.ResetData) Then
                    Me.LoadData()
                    Me.DataBind()
                End If

            Catch ex As Exception
                Utils.MiscUtils.RegisterJScriptAlert(Me, "BUTTON_CLICK_MESSAGE", ex.Message)
            Finally
                DbUtils.EndTransaction()
            End Try
        End Sub
        
        

        Protected Overrides Sub LoadViewState(ByVal savedState As Object)
            MyBase.LoadViewState(savedState)
            Dim isNewRecord As String = CType(ViewState("IsNewRecord"), String)
            If Not isNewRecord Is Nothing AndAlso isNewRecord.Trim <> "" Then
                Me.IsNewRecord = Boolean.Parse(isNewRecord)
            End If
            
            Dim myCheckSum As String = CType(ViewState("CheckSum"), String)
            If Not myCheckSum Is Nothing AndAlso myCheckSum.Trim <> "" Then
                Me.CheckSum = myCheckSum
            End If
            
        End Sub

        Protected Overrides Function SaveViewState() As Object
            ViewState("IsNewRecord") = Me.IsNewRecord.ToString()
            ViewState("CheckSum") = Me.CheckSum
            
            Return MyBase.SaveViewState()
        End Function
        
        
        ' Generate the event handling functions for pagination events.
            
      
        ' Generate the event handling functions for filter and search events.
            
   
        Private _IsNewRecord As Boolean = True
        Public Overridable Property IsNewRecord() As Boolean
            Get
                Return Me._IsNewRecord
            End Get
            Set(ByVal value As Boolean)
                Me._IsNewRecord = value
            End Set
        End Property

        Private _DataChanged As Boolean = False
        Public Overridable Property DataChanged() As Boolean
            Get
                Return Me._DataChanged
            End Get
            Set(ByVal Value As Boolean)
                Me._DataChanged = Value
            End Set
        End Property

        Private _ResetData As Boolean = False
        Public Overridable Property ResetData() As Boolean
            Get
                Return Me._ResetData
            End Get
            Set(ByVal Value As Boolean)
                Me._ResetData = Value
            End Set
        End Property
        
        Public Property RecordUniqueId() As String
            Get
                Return CType(Me.ViewState("BaseCustomersRecordControl_Rec"), String)
            End Get
            Set(ByVal value As String)
                Me.ViewState("BaseCustomersRecordControl_Rec") = value
            End Set
        End Property
        
        Private _DataSource As CustomersRecord
        Public Property DataSource() As CustomersRecord
            Get
                Return Me._DataSource
            End Get
            Set(ByVal value As CustomersRecord)
                Me._DataSource = value
            End Set
        End Property

        Private _checkSum As String
        Public Overridable Property CheckSum() As String
            Get
                Return Me._checkSum
            End Get
            Set(ByVal value As String)
                Me._checkSum = value
            End Set
        End Property
        
        Private _TotalPages As Integer
        Public Property TotalPages() As Integer
            Get
                Return Me._TotalPages
            End Get
            Set(ByVal value As Integer)
                Me._TotalPages = value
            End Set
        End Property
        
        Private _PageIndex As Integer
        Public Property PageIndex() As Integer
            Get
                ' Return the PageIndex
                Return Me._PageIndex
            End Get
            Set(ByVal value As Integer)
                Me._PageIndex = value
            End Set
        End Property
    
        Private _PageSize As Integer
        Public Property PageSize() As Integer
            Get
                Return Me._PageSize
            End Get
            Set(ByVal value As Integer)
                Me._PageSize = value
            End Set
        End Property
    
        Private _TotalRecords As Integer
        Public Property TotalRecords() As Integer
            Get
                Return Me._TotalRecords
            End Get
            Set(ByVal value As Integer)
                If Me.PageSize > 0 Then
                    Me.TotalPages = CInt(Math.Ceiling(value / Me.PageSize))
                End If

                Me._TotalRecords = value
            End Set
        End Property
        
        Private _DisplayLastPage As Boolean
        Public Property DisplayLastPage() As Boolean
            Get
                Return Me._DisplayLastPage
            End Get
            Set(ByVal value As Boolean)
                Me._DisplayLastPage = value
            End Set
        End Property
        
        

#Region "Helper Properties"
        
        Public ReadOnly Property Address() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "Address"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property AddressLabel() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "AddressLabel"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
        
        Public ReadOnly Property City() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "City"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property CityLabel() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CityLabel"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
        
        Public ReadOnly Property CompanyName() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CompanyName"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property CompanyNameLabel() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CompanyNameLabel"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
        
        Public ReadOnly Property ContactName() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ContactName"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property ContactNameLabel() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ContactNameLabel"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
        
        Public ReadOnly Property ContactTitle() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ContactTitle"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property ContactTitleLabel() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "ContactTitleLabel"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
        
        Public ReadOnly Property Country() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "Country"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property CountryLabel() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CountryLabel"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
        
        Public ReadOnly Property CustomerID() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CustomerID"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property CustomerIDLabel() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CustomerIDLabel"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
        
        Public ReadOnly Property CustomersTitle() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CustomersTitle"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
        
        Public ReadOnly Property EmailAddress() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "EmailAddress"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property EmailAddressLabel() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "EmailAddressLabel"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
        
        Public ReadOnly Property Fax() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "Fax"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property FaxLabel() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "FaxLabel"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
        
        Public ReadOnly Property Phone() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "Phone"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property PhoneLabel() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "PhoneLabel"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
        
        Public ReadOnly Property PostalCode() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "PostalCode"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property PostalCodeLabel() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "PostalCodeLabel"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
        
        Public ReadOnly Property Region() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "Region"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
        Public ReadOnly Property RegionLabel() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "RegionLabel"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
        
    #End Region

    #Region "Helper Functions"

    Public Overrides Overloads Function ModifyRedirectUrl(ByVal url As String, ByVal arg As String, ByVal bEncrypt As Boolean) As String
        Return Me.Page.EvaluateExpressions(url, arg, bEncrypt, Me)
    End Function

    Public Overrides Overloads Function EvaluateExpressions(ByVal url As String, ByVal arg As String, ByVal bEncrypt As Boolean) As String
    Dim rec As CustomersRecord = Nothing
            
            Try
                rec = Me.GetRecord()
            Catch ex As Exception
                ' Do nothing
            End Try

            If rec Is Nothing AndAlso url.IndexOf("{") >= 0 Then
                ' Localization.
                
            Throw New Exception(Page.GetResourceValue("Err:RecDataSrcNotInitialized", "UseDAL"))
                    
            End If
            Return EvaluateExpressions(url, arg, rec, bEncrypt)
        End Function

        Public Overridable Function GetRecord() As CustomersRecord
            If Not Me.DataSource Is Nothing Then
              Return Me.DataSource
            End If
            
            Return New CustomersRecord()
          
        End Function

        Public Shadows ReadOnly Property Page() As BaseApplicationPage
            Get
                Return DirectCast(MyBase.Page, BaseApplicationPage)
            End Get
        End Property

#End Region

End Class

  

#End Region
    
  
End Namespace

  