
' This file implements the TableControl, TableControlRow, and RecordControl classes for the 
' SelectEditCategoriesPage.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 Training2.Business
Imports Training2.Data
        

#End Region

  
Namespace Training2.UI.Controls.SelectEditCategoriesPage

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

    
Public Class CategoriesRecordControl
        Inherits BaseCategoriesRecordControl
        ' The BaseCategoriesRecordControl 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 CategoriesRecordControl control on the SelectEditCategoriesPage page.
' Do not modify this class. Instead override any method in CategoriesRecordControl.
Public Class BaseCategoriesRecordControl
        Inherits Training2.UI.BaseApplicationRecordControl

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

      
      ' Setup the pagination events.
      
              AddHandler Me.CategoriesPagination.FirstPage.Click, AddressOf CategoriesPagination_FirstPage_Click
              
              AddHandler Me.CategoriesPagination.LastPage.Click, AddressOf CategoriesPagination_LastPage_Click
              
              AddHandler Me.CategoriesPagination.NextPage.Click, AddressOf CategoriesPagination_NextPage_Click
              
              AddHandler Me.CategoriesPagination.PageSizeButton.Click, AddressOf CategoriesPagination_PageSizeButton_Click
            
              AddHandler Me.CategoriesPagination.PreviousPage.Click, AddressOf CategoriesPagination_PreviousPage_Click
              
          
        ' Setup the filter and search events.
        
            AddHandler Me.CategoryNameFilter.SelectedIndexChanged, AddressOf CategoryNameFilter_SelectedIndexChanged
            If Not Me.Page.IsPostBack AndAlso Me.InSession(Me.CategoriesSearchArea) Then
                
                Me.CategoriesSearchArea.Text = Me.GetFromSession(Me.CategoriesSearchArea)
            End If
            If Not Me.Page.IsPostBack AndAlso Me.InSession(Me.CategoryNameFilter) Then
                
            Dim CategoryNameFilterselectedFilterItemList As ArrayList = Nothing
            Dim CategoryNameFiltersessionString As String = Me.GetFromSession(Me.CategoryNameFilter)
            If Not isNothing(CategoryNameFiltersessionString)
                Dim CategoryNameFilteritemListFromSession() As String = CategoryNameFiltersessionString.Split("$"c)
                Dim index As Integer = 0
                For Each item As String In CategoryNameFilteritemListFromSession
                    If index = 0 AndAlso _
                       item.ToString.Equals("") Then
                    Else
                        Me.CategoryNameFilter.Items.Add(item)
                        'Me.CategoryNameFilter.Items.Item(index).Selected = True
                    End If
                    index += 1
                Next
                Dim listItem As ListItem
                For Each listItem In Me.CategoryNameFilter.Items
                    listItem.Selected = True
                Next
            End If
                    
            End If
      
            ' Register the event handlers.
        
              AddHandler Me.CategoriesNewButton.Click, AddressOf CategoriesNewButton_Click
              
              AddHandler Me.CategoriesCopyButton.Click, AddressOf CategoriesCopyButton_Click
              
              AddHandler Me.CategoriesDeleteButton.Click, AddressOf CategoriesDeleteButton_Click
              
              AddHandler Me.CategoriesSaveButton.Click, AddressOf CategoriesSaveButton_Click
              
              Me.Page.RegisterPostBackTrigger(MiscUtils.FindControlRecursively(Me,"CategoriesSaveButton"), MiscUtils.GetParentControlObject(Me,"CategoriesRecordControlUpdatePanel"))
                        
        Me.CategoriesSaveButton.Attributes.Add("onclick", "SubmitHRefOnce(this, """ & Me.Page.GetResourceValue("Txt:SaveRecord", "Training2") & """);")
        
              AddHandler Me.CategoriesRefreshButton.Click, AddressOf CategoriesRefreshButton_Click
              
              AddHandler Me.CategoriesResetButton.Click, AddressOf CategoriesResetButton_Click
              
              AddHandler Me.CategoriesSearchButton.Button.Click, AddressOf CategoriesSearchButton_Click
              
              AddHandler Me.CategoriesFilterButton.Button.Click, AddressOf CategoriesFilterButton_Click
              
            ' 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
          
            Me.PageIndex = CInt(Me.GetFromSession(Me, "Page_Index", "0"))
            Me.ClearControlsFromSession()
      
        End Sub

        '  To customize, override this method in CategoriesRecordControl.
        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.CategoriesDeleteButton.Attributes.Add("onClick", "return (confirm('" & (CType(Me.Page,BaseApplicationPage)).GetResourceValue("DeleteConfirm", "Training2") & "'));")
        Me.Page.ClientScript.RegisterOnSubmitStatement(Description.GetType(), "Description", "FCKUpdateLinkedField('" + Description.ClientID + "');")
      
    
    End Sub

        ' Read data from database.  To customize, override this method in CategoriesRecordControl.
        Public Overridable Sub LoadData()        
        
            Dim wc As WhereClause = Me.CreateWhereClause()
            
            Dim Panel As System.Web.UI.WebControls.Panel = CType(MiscUtils.FindControlRecursively(Me, "CategoriesRecordControlPanel"), System.Web.UI.WebControls.Panel)
            If Not Panel is Nothing Then
                Panel.visible = True
            End If
            
            If wc Is Nothing OrElse Not wc.RunQuery Then
                Me.DataSource = New CategoriesRecord()
                
                If Not Panel is Nothing Then
                    Panel.visible = False
                End If
                
                Return
            End If
            

          
            Me.TotalPages = CategoriesTable.GetRecordCount(wc)
            If Me.DisplayLastPage Then
                Me.PageIndex = Me.TotalPages - 1
            End If
          
              
            ' Retrieve the record from the database.
            
            Dim orderBy As OrderBy = CreateOrderBy()
            Dim recList() As CategoriesRecord = CategoriesTable.GetRecords(wc, orderBy, BaseTable.MIN_PAGE_NUMBER, BaseTable.MAX_BATCH_SIZE)
            If recList.Length = 0 Then
                Me.PageIndex = 0
                Me.DataSource = New CategoriesRecord()
                Me.RecordUniqueId = Nothing
                If Not Panel is Nothing Then
                    Panel.visible = False
                End If
                Return
            Else If Me.PageIndex >= recList.Length Then
                Me.PageIndex = recList.Length - 1
            Else If Me.PageIndex < 0 Then
                Me.PageIndex = 0
            End If
              
            Me.DataSource = CategoriesTable.GetRecord(recList(Me.PageIndex).GetID.ToXmlString(), True)
                  
        End Sub

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

            MyBase.DataBind()

            ' Make sure that the DataSource is initialized.
            If Me.DataSource Is Nothing Then
                Return
            End If
        
            ' Setup the pagination controls.
            BindPaginationControls()
      
            Dim CategoryNameFilterselectedFilterItemList As ArrayList = Nothing
            Dim CategoryNameFiltersessionString As String = Me.GetFromSession(Me.CategoryNameFilter)
            If Not isNothing(CategoryNameFiltersessionString)
            Dim CategoryNameFilteritemListFromSession() As String = CategoryNameFiltersessionString.Split("$"c)
            For Each item As String In CategoryNameFilteritemListFromSession
                CategoryNameFilterselectedFilterItemList.Add(item)
            Next
            End If
            Me.PopulateCategoryNameFilter(GetSelectedValueList(Me.CategoryNameFilter, CategoryNameFilterselectedFilterItemList), 500)
                    
      
            ' 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.CategoryNameSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(CategoriesTable.CategoryName)
                Me.CategoryName.Text = formattedValue
              
            Else      
                Me.CategoryName.Text = CategoriesTable.CategoryName.Format(CategoriesTable.CategoryName.DefaultValue)
              
            End If
                    
            If Me.DataSource.DescriptionSpecified Then
                Dim formattedValue As String = Me.DataSource.Format(CategoriesTable.Description)
                Me.Description.Value = formattedValue
                Me.Description.DefaultLanguage = System.Threading.Thread.CurrentThread.CurrentUICulture.Name
              
            Else      
                Me.Description.DefaultLanguage = System.Threading.Thread.CurrentThread.CurrentUICulture.Name
                Me.Description.Value = CategoriesTable.Description.Format(CategoriesTable.Description.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
            
      End Sub

        
        Public Overridable Sub ResetControl()
        
          
              Me.CategoryNameFilter.ClearSelection()
            
              Me.CategoriesSearchArea.Text = ""
            
              Me.RecordUniqueId = Nothing
            
            Me.PageIndex = 0
            
            
            
          End Sub
        
        Protected Overridable Sub BindPaginationControls()

            ' Setup the pagination controls.

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

            ' Bind the pagination labels.
        
            If Me.TotalPages > 0 Then
                Me.CategoriesPagination.CurrentPage.Text = (Me.PageIndex + 1).ToString()
            Else
                Me.CategoriesPagination.CurrentPage.Text = "0"
            End If
            Me.CategoriesPagination.TotalPages.Text = Me.TotalPages.ToString()
        End Sub
        
      
        
        ' To customize, override this method in CategoriesRecordControl.
        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 Panel As System.Web.UI.WebControls.Panel = CType(MiscUtils.FindControlRecursively(Me, "CategoriesRecordControlPanel"), System.Web.UI.WebControls.Panel)

          If ((Not IsNothing(Panel)) AndAlso (Not Panel.Visible)) OrElse IsNothing(Me.DataSource) Then
              Return
          End If
          
              
            ' 2. Validate the data.  Override in CategoriesRecordControl to add custom validation.
            Me.Validate()

            ' 3. Set the values in the record with data from UI controls.  Override in CategoriesRecordControl 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
            
        End Sub

        ' To customize, override this method in CategoriesRecordControl.
        Public Overridable Sub GetUIData()
            
            Me.DataSource.Parse(Me.CategoryName.Text, CategoriesTable.CategoryName)
                          
                            Me.DataSource.Parse(Me.Description.Value, CategoriesTable.Description)
                          
        End Sub

        
        Public Overridable Function CreateOrderBy() As OrderBy
            Return Me.CurrentSortOrder
        End Function
        
      
        ' To customize, override this method in CategoriesRecordControl.
        Public Overridable Function CreateWhereClause() As WhereClause
        
            Dim wc As WhereClause
            CategoriesTable.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.

            
            If IsValueSelected(Me.CategoriesSearchArea) Then
                ' Strip "..." from begin and ending of the search text, otherwise the search will return 0 values as in database "..." is not stored.
                If Me.CategoriesSearchArea.Text.StartsWith("...") then
                    Me.CategoriesSearchArea.Text = Me.CategoriesSearchArea.Text.SubString(3,Me.CategoriesSearchArea.Text.Length-3)
                End If
                If Me.CategoriesSearchArea.Text.EndsWith("...") then
                    Me.CategoriesSearchArea.Text = Me.CategoriesSearchArea.Text.SubString(0,Me.CategoriesSearchArea.Text.Length-3)
                End If
                ' After stripping "..." see if the search text is null or empty.
                If IsValueSelected(Me.CategoriesSearchArea) Then
                      
                    ' These clauses are added depending on operator and fields selected in Control's property page, bindings tab.
                    Dim search As WhereClause = New WhereClause()
                    
                    search.iOR(CategoriesTable.CategoryName, BaseFilter.ComparisonOperator.Contains, MiscUtils.GetSelectedValue(Me.CategoriesSearchArea, Me.GetFromSession(Me.CategoriesSearchArea)), True, False)
        
                    wc.iAND(search)
                End If
            End If
                  
            If IsValueSelected(Me.CategoryNameFilter) Then
                
                Dim item As ListItem
                Dim filter As WhereClause = New WhereClause
                Dim selectedItemCount As Integer = 0
                For Each item In Me.CategoryNameFilter.Items
                    If item.Selected Then
                        selectedItemCount += 1
                        
                    End If
                Next
                For Each item In Me.CategoryNameFilter.Items
                    If item.Selected AndAlso (item.Value = "--ANY--" OrElse item.Value = "--PLEASE_SELECT--") AndAlso selectedItemCount > 1 Then
                        item.Selected = False
                    End If
                    If item.Selected Then
                        filter.iOR(CategoriesTable.CategoryName, BaseFilter.ComparisonOperator.EqualsTo, item.Value, False, False)
                    End If
                Next
                wc.iAND(filter)
                    
                
            End If
                       
            Dim BoolFlag As Boolean = False
                
            If IsValueSelected(Me.CategoriesSearchArea) OrElse _
        Me.InSession(Me.CategoriesSearchArea) Then
                BoolFlag = True
            End If
            
            If IsValueSelected(Me.CategoryNameFilter) OrElse _
        Me.InSession(Me.CategoryNameFilter) Then
                BoolFlag = True
            End If
            
            If BoolFlag Then
                Return wc
                
            End If 
                    
            ' Retrieve the record id from the URL parameter.
              
            Dim recId As String = Me.Page.Request.QueryString.Item("Categories")
                
            If Not recId Is Nothing AndAlso Not recId.Trim = "" Then
                HttpContext.Current.Session("QueryString in SelectEditCategoriesPage") = recId
              
                If KeyValue.IsXmlKey(recId) Then
                    Dim pkValue As KeyValue = KeyValue.XmlToKey(recId)
                
                wc.iAND(CategoriesTable.CategoryID, BaseFilter.ComparisonOperator.EqualsTo, pkValue.GetColumnValue(CategoriesTable.CategoryID).ToString())
                Else
                
                wc.iAND(CategoriesTable.CategoryID, BaseFilter.ComparisonOperator.EqualsTo, recId)
                End If
              
                Return wc
            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
            CategoriesTable.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.
          
            If IsValueSelected(searchText) and fromSearchControl = "CategoriesSearchArea" Then
                Dim formatedSearchText as String = searchText
                ' strip "..." from begin and ending of the search text, otherwise the search will return 0 values as in database "..." is not stored.
                If searchText.StartsWith("...") then
                    formatedSearchText = searchText.SubString(3,searchText.Length-3)
                End If
                If searchText.EndsWith("...") then
                    formatedSearchText = searchText.SubString(0,searchText.Length-3)
                End If
                'After stripping "...", trim any leading and trailing whitespaces 
                formatedSearchText = formatedSearchText.Trim()
                ' After stripping "..." see if the search text is null or empty.
                If IsValueSelected(formatedSearchText) Then
                      
                    ' These clauses are added depending on operator and fields selected in Control's property page, bindings tab.
                    Dim search As WhereClause = New WhereClause()
                    
                    If InvariantLCase(AutoTypeAheadSearch).equals("wordsstartingwithsearchstring") Then
                
                        search.iOR(CategoriesTable.CategoryName, BaseFilter.ComparisonOperator.Starts_With, formatedSearchText, True, False)
                        search.iOR(CategoriesTable.CategoryName, BaseFilter.ComparisonOperator.Contains, AutoTypeAheadWordSeparators & formatedSearchText, True, False)
                
                    Else
                        
                        search.iOR(CategoriesTable.CategoryName, BaseFilter.ComparisonOperator.Contains, formatedSearchText, True, False)
                    End If
                    wc.iAND(search)
                End If
            End If
                  
            Dim CategoryNameFilterSelectedValue As String = CType(HttpContext.Current.Session()(HttpContext.Current.Session.SessionID & appRelativeVirtualPath & "CategoryNameFilter_Ajax"), String)
            If IsValueSelected(CategoryNameFilterSelectedValue) Then
              
        If Not isNothing(CategoryNameFilterSelectedValue) Then
          Dim CategoryNameFilteritemListFromSession() As String = CategoryNameFilterSelectedValue.Split("$"c)
          Dim index As Integer = 0
                    Dim filter As WhereClause = New WhereClause
          For Each item As String In CategoryNameFilteritemListFromSession
            If index = 0 AndAlso _
              item.ToString.Equals("") Then
            Else
              filter.iOR(CategoriesTable.CategoryName, BaseFilter.ComparisonOperator.EqualsTo, item, False, False)
                        End If
            index += 1
          Next
          wc.iAND(filter)
        End If
                
            End If
                      
            ' Retrieve the record id from the session.
            Dim recId As String = DirectCast(HttpContext.Current.Session("QueryString in SelectEditCategoriesPage"), String)
            If Not recId Is Nothing AndAlso Not recId.Trim = "" Then
                If KeyValue.IsXmlKey(recId) Then
                    Dim pkValue As KeyValue = KeyValue.XmlToKey(recId)
                
                wc.iAND(CategoriesTable.CategoryID, BaseFilter.ComparisonOperator.EqualsTo, pkValue.GetColumnValue(CategoriesTable.CategoryID).ToString())
                Else
                
                wc.iAND(CategoriesTable.CategoryID, BaseFilter.ComparisonOperator.EqualsTo, recId)
                End If
            End If
              
       
          
            Return wc
        End Function
          
        Public Overridable Function GetAutoCompletionList_CategoriesSearchArea(ByVal prefixText As String, ByVal count As Integer) As String()
            Dim resultList As ArrayList = New ArrayList
            Dim wordList As ArrayList = New ArrayList
            Dim iteration As Integer = 0
            
            Dim wc As WhereClause = CreateWhereClause(prefixText,"CategoriesSearchArea", "WordsStartingWithSearchString", "[^a-zA-Z0-9]")
            While (resultList.Count < count AndAlso iteration < 5)
                ' Fetch 100 records in each iteration
                Dim records() As Training2.Business.CategoriesRecord = CategoriesTable.GetRecords(wc, Nothing, iteration, 100)
                Dim rec As CategoriesRecord = Nothing
                Dim resultItem As String = ""
                For Each rec In records
                    ' Exit the loop if recordList count has reached AutoTypeAheadListSize.
                    If resultList.Count >= count then
                        Exit For
                    End If
                    ' If the field is configured to Display as Foreign key, Format() method returns the 
                    ' Display as Forien Key value instead of original field value.
                    ' Since search had to be done in multiple fields (selected in Control's page property, binding tab) in a record,
                    ' We need to find relevent field to display which matches the prefixText and is not already present in the result list.
                
                    resultItem = rec.Format(CategoriesTable.CategoryName)
                    If resultItem IsNot Nothing AndAlso resultItem.ToUpper(System.Threading.Thread.CurrentThread.CurrentCulture).Contains(prefixText.ToUpper(System.Threading.Thread.CurrentThread.CurrentCulture))  Then
                        Dim isAdded as Boolean = FormatSuggestions(prefixText, resultItem, 50, "AtBeginningOfMatchedString", "WordsStartingWithSearchString", "[^a-zA-Z0-9]", resultList)
                        If isAdded Then
                            Continue For
                        End If
                    End If
      
                Next
                ' Exit the loop if number of records found is less as further iteration will not return any more records
                If records.Length < 100 Then
                    Exit While
                End If
                iteration += 1
            End While
            resultList.Sort()
            Dim result() As String = New String(resultList.Count - 1) {}
            Array.Copy(resultList.ToArray, result, resultList.Count)
            Return result
        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
        
        ' Get the filters' data for CategoryNameFilter
        Protected Overridable Sub PopulateCategoryNameFilter(ByVal selectedValue As ArrayList, ByVal maxItems As Integer)
                    
            ' Setup the WHERE clause, including the base table if needed.
                
            Dim wc As WhereClause = Me.CreateWhereClause_CategoryNameFilter()
                  
            Dim orderBy As OrderBy = New OrderBy(False, True)
            orderBy.Add(CategoriesTable.CategoryName, OrderByItem.OrderDir.Asc)

            Dim list() As String = CategoriesTable.GetValues(CategoriesTable.CategoryName, wc, orderBy, maxItems)
            
            Me.CategoryNameFilter.Items.Clear()
            Dim itemValue As String
            
             For Each itemValue In list
                ' Create the item and add to the list.
                Dim fvalue As String
                If ( CategoriesTable.CategoryName.IsColumnValueTypeBoolean()) Then
                    fvalue = itemValue
                Else
                    fvalue = CategoriesTable.CategoryName.Format(itemValue)
                End If
                Dim item As ListItem = New ListItem(fvalue, itemValue)
                Me.CategoryNameFilter.Items.Add(item)
            Next
                    
      ' Add the All item.
            Me.CategoryNameFilter.Items.Insert(0, New ListItem(Page.GetResourceValue("Txt:All", "Training2"), "--ANY--"))	
        
            ' Set the selected value.
            SetSelectedValue(Me.CategoryNameFilter, selectedValue)

                
            If Me.CategoryNameFilter.SelectedValue Is Nothing OrElse _
        isNothing(selectedValue) OrElse _
        selectedValue.Count = 0 Then
                Me.CategoryNameFilter.SelectedValue = "--ANY--"
            End If
                
        End Sub
            
    ' Create a where clause for the filter CategoriesSearchArea.
        Public Overridable Function CreateWhereClause_CategoriesSearchArea() As WhereClause
      
      return new WhereClause()
        
        End Function			
            
    ' Create a where clause for the filter CategoryNameFilter.
        Public Overridable Function CreateWhereClause_CategoryNameFilter() As WhereClause
      
      return new WhereClause()
        
        End Function			
            

        ' To customize, override this method in CategoriesRecordControl.
        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)
            CategoriesTable.DeleteRecord(pk)

          
        End Sub

        Private 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.
        
            Me.SaveToSession(Me.CategoriesSearchArea, Me.CategoriesSearchArea.Text)
                  
            Dim CategoryNameFilterselectedFilterItemList As ArrayList = GetSelectedValueList(Me.CategoryNameFilter, Nothing)
            Dim CategoryNameFilterSessionString As String = ""
            If Not CategoryNameFilterselectedFilterItemList is Nothing Then
            For Each item As String In CategoryNameFilterselectedFilterItemList
                CategoryNameFilterSessionstring = CategoryNameFilterSessionstring & "$" & item
            Next
            End If
            Me.SaveToSession(Me.CategoryNameFilter, CategoryNameFilterSessionstring)
                  
            
            ' 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())
            
        End Sub
        
        
        Protected  Sub SaveControlsToSession_Ajax()
            ' Save filter controls to values to session.
          
      Me.SaveToSession("CategoriesSearchArea_Ajax", Me.CategoriesSearchArea.Text)
              
            Dim CategoryNameFilterselectedFilterItemList As ArrayList = GetSelectedValueList(Me.CategoryNameFilter, Nothing)
            Dim CategoryNameFilterSessionString As String = ""
            If Not CategoryNameFilterselectedFilterItemList is Nothing Then
            For Each item As String In CategoryNameFilterselectedFilterItemList
                CategoryNameFilterSessionstring = CategoryNameFilterSessionstring & "$" & item
            Next
            End If
            Me.SaveToSession("CategoryNameFilter_Ajax", CategoryNameFilterSessionString)
          
            HttpContext.Current.Session("AppRelativeVirtualPath") = Me.Page.AppRelativeVirtualPath
         
        End Sub
        
            
        Protected Overrides Sub ClearControlsFromSession()
            MyBase.ClearControlsFromSession()

            ' Clear filter controls values from the session.
        
            Me.RemoveFromSession(Me.CategoriesSearchArea)
            Me.RemoveFromSession(Me.CategoryNameFilter)
            
            ' Clear table properties from the session.
            
            Me.RemoveFromSession(Me, "Page_Index")
            
        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 pageIndex As String = CType(ViewState("Page_Index"), String)
            If Not pageIndex Is Nothing Then
                Me.PageIndex = CInt(pageIndex)
            End If
            
            Dim orderByStr As String = CType(ViewState("CategoriesRecordControl_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
            
        End Sub

        Protected Overrides Function SaveViewState() As Object
            ViewState("IsNewRecord") = Me.IsNewRecord.ToString()
            ViewState("CheckSum") = Me.CheckSum
            
            ViewState("Page_Index") = Me.PageIndex
            
            If Not Me.CurrentSortOrder Is Nothing Then
                Me.ViewState("CategoriesRecordControl_OrderBy") = Me.CurrentSortOrder.ToXmlString()
            End If
            
            Return MyBase.SaveViewState()
        End Function
        
        
        ' Generate the event handling functions for pagination events.
            
        ' event handler for ImageButton
        Public Overridable Sub CategoriesPagination_FirstPage_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                DbUtils.StartTransaction
                
            Me.PageIndex = 0
            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 CategoriesPagination_LastPage_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                DbUtils.StartTransaction
                
            Me.DisplayLastPage = True
            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 CategoriesPagination_NextPage_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                DbUtils.StartTransaction
                
            Me.PageIndex += 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 LinkButton
        Public Overridable Sub CategoriesPagination_PageSizeButton_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Try
                DbUtils.StartTransaction
                
            Me.DataChanged = True
      
            Me.PageIndex = Integer.Parse(Me.CategoriesPagination.CurrentPage.Text) - 1
          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 CategoriesPagination_PreviousPage_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                DbUtils.StartTransaction
                
            If Me.PageIndex > 0 Then
                Me.PageIndex -= 1
                Me.DataChanged = 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
            
      
        ' Generate the event handling functions for filter and search events.
            
        ' event handler for FieldFilter
        Protected Overridable Sub CategoryNameFilter_SelectedIndexChanged(ByVal sender As Object, ByVal args As EventArgs)
           Me.DataChanged = True
        End Sub
            
        ' event handler for ImageButton
        Public Overridable Sub CategoriesNewButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Dim url As String = "../Categories/AddCategoriesPage.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 CategoriesCopyButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Dim url As String = "../Categories/AddCategoriesPage.aspx?Categories={PK}"
            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 CategoriesDeleteButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                DbUtils.StartTransaction
                
            If(Not Me.Page.IsPageRefresh) Then
        
            If IsNothing(Me.GetRecord()) Then
            Throw New Exception(Page.GetResourceValue("Err:NoRecSelected", "Training2"))
            End If
            Me.Delete()
            Me.DataChanged = True
            Me.ResetData = 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 CategoriesSaveButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                DbUtils.StartTransaction
                
              If (Not Me.Page.IsPageRefresh) Then            
                  Me.SaveData()              
              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 CategoriesRefreshButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                DbUtils.StartTransaction
                
            DirectCast(Me.Page.FindControlRecursively("CategoriesRecordControl"), CategoriesRecordControl).ResetData = 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 CategoriesResetButton_Click(ByVal sender As Object, ByVal args As ImageClickEventArgs)
        
            Try
                DbUtils.StartTransaction
                
              Me.CategoryNameFilter.ClearSelection
              Me.CategoriesSearchArea.Text = ""
              Me.RecordUniqueId = Nothing
            

        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 Button with Layout
        Public Overridable Sub CategoriesSearchButton_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Try
                DbUtils.StartTransaction
                
          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 Button with Layout
        Public Overridable Sub CategoriesFilterButton_Click(ByVal sender As Object, ByVal args As EventArgs)
              
            Try
                DbUtils.StartTransaction
                
          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
            
   
        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("BaseCategoriesRecordControl_Rec"), String)
            End Get
            Set(ByVal value As String)
                Me.ViewState("BaseCategoriesRecordControl_Rec") = value
            End Set
        End Property
        
        Private _DataSource As CategoriesRecord
        Public Property DataSource() As CategoriesRecord
            Get
                Return Me._DataSource
            End Get
            Set(ByVal value As CategoriesRecord)
                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
        
        
        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
        

#Region "Helper Properties"
        
        Public ReadOnly Property CategoriesTitle() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CategoriesTitle"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
        
        Public ReadOnly Property CategoriesSearchArea() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CategoriesSearchArea"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
        
        Public ReadOnly Property CategoriesSearchButton() As Training2.UI.IThemeButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CategoriesSearchButton"), Training2.UI.IThemeButton)
          End Get
          End Property
        
        Public ReadOnly Property CategoryNameFilter() As System.Web.UI.WebControls.ListBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CategoryNameFilter"), System.Web.UI.WebControls.ListBox)
            End Get
        End Property
        
        Public ReadOnly Property CategoryNameLabel() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CategoryNameLabel"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
        
        Public ReadOnly Property CategoriesFilterButton() As Training2.UI.IThemeButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CategoriesFilterButton"), Training2.UI.IThemeButton)
          End Get
          End Property
        
        Public ReadOnly Property CategoriesPagination() As Training2.UI.IPaginationShort
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CategoriesPagination"), Training2.UI.IPaginationShort)
          End Get
          End Property
        
        Public ReadOnly Property CategoriesNewButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CategoriesNewButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property CategoriesCopyButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CategoriesCopyButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property CategoriesDeleteButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CategoriesDeleteButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property CategoriesSaveButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CategoriesSaveButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property CategoriesRefreshButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CategoriesRefreshButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property CategoriesResetButton() As System.Web.UI.WebControls.ImageButton
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CategoriesResetButton"), System.Web.UI.WebControls.ImageButton)
            End Get
        End Property
        
        Public ReadOnly Property CategoryNameLabel1() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CategoryNameLabel1"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
        
        Public ReadOnly Property DescriptionLabel() As System.Web.UI.WebControls.Literal
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "DescriptionLabel"), System.Web.UI.WebControls.Literal)
            End Get
        End Property
        
        Public ReadOnly Property CategoryName() As System.Web.UI.WebControls.TextBox
            Get
                Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "CategoryName"), System.Web.UI.WebControls.TextBox)
            End Get
        End Property
            
              Public ReadOnly Property Description() As FredCK.FCKeditorV2.FCKeditor
              Get
              Return CType(BaseClasses.Utils.MiscUtils.FindControlRecursively(Me, "Description"), FredCK.FCKeditorV2.FCKeditor)
              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 CategoriesRecord = 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:NoRecSelected", "Training2"))
                    
            End If
            Return EvaluateExpressions(url, arg, rec, bEncrypt)
        End Function

        Public Overridable Function GetRecord() As CategoriesRecord
            If Not Me.DataSource Is Nothing Then
                Return Me.DataSource
            End If
            
            If Not Me.RecordUniqueId Is Nothing Then
                Return CategoriesTable.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

  

#End Region
    
  
End Namespace

  