Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Xml
Imports Sorting.DateHeap
Imports System.Collections.Generic
Imports CharterDotCom.CommonEntities.Library
Imports CharterDotCom.CommonEntities.Library.Enumerations
Imports CharterDotCom.CommonEntities.Library.EntityMemberServices
'Imports CharterDotCom.CommonEntities.Library.EntityEBSServices
Imports CharterDotCom.CommonEntities.Library.EntitySupport
Imports CharterDotCom.CommonEntities.Library.EntitySearch
Imports CharterDotCom.CommonEntities.Library.EntityWebConfig
Imports CharterDotCom.CommonEntities.Library.EntityG2BServices
Imports CharterDotCom.WebSite.Library
Imports CharterDotCom.CommonEntities.Library.Common
Imports Sorting


Partial Class LoadTest_ErrorLogReport
    Inherits CharterCMSPage

	Public dt As DataTable = New System.Data.DataTable("ErrorTable")
	'Dim ascending As Boolean = True





    Private Sub BuildTable()
        SetPageTitle("Error Log Report")
        Try
            dt.Rows.Clear()
            '###########################################
            'LOGG THE ERROR MESSAGE TO THE ERROR QUEUE
            '###########################################
            Dim tempErrorQLoc As String = ConfigurationManager.AppSettings("ErrorQueueLocation")
            Dim ErrorQueueLocation As String = Environment.MachineName & tempErrorQLoc
            Dim lMessageQComponent As New MessageQComponent
            Dim lmessages As System.Messaging.Message() = lMessageQComponent.GetAllMessages(ErrorQueueLocation)


            Dim errMessageObject As ErrorLog
            Dim _errorMsg As String
            Dim _innerMsg As String
            Dim _date As String



            Dim colError As DataColumn = New DataColumn("Error")
            colError.DataType = System.Type.GetType("System.String")

            Dim colInnerError As DataColumn = New DataColumn("InnerError")
            colInnerError.DataType = System.Type.GetType("System.String")

            Dim colDate As DataColumn = New DataColumn("Date")
            colDate.DataType = System.Type.GetType("System.String")

            dt.Columns.Add(colError)
            dt.Columns.Add(colInnerError)
            dt.Columns.Add(colDate)

            Dim drnew As DataRow

            If Not lmessages Is Nothing Then
                If lmessages.Length > 0 Then
                    grdErrorLog.Visible = True
                    For Each lmessage As System.Messaging.Message In lmessages

                        Dim buffIn(lmessage.BodyStream.Length) As Byte
                        lmessage.BodyStream.Position = 0
                        lmessage.BodyStream.Read(buffIn, 0, lmessage.BodyStream.Length)
                        Dim data = System.Text.Encoding.ASCII.GetString(buffIn)
                        'Response.Write(data)
                        errMessageObject = New ErrorLog(data)
                        _errorMsg = errMessageObject.Err
                        _innerMsg = errMessageObject.InnerError
                        _date = errMessageObject.ErrorDate


                        drnew = dt.NewRow()
                        drnew("Error") = _errorMsg
                        drnew("InnerError") = _innerMsg
                        drnew("Date") = _date
                        dt.Rows.Add(drnew)

                    Next

                    grdErrorLog.DataSource = dt
                    grdErrorLog.DataBind()



                    'Dim ltextbox As New TextBox
                    'ltextbox.Width = "600"
                    'ltextbox.Rows = "3"
                    'ltextbox.TextMode = TextBoxMode.MultiLine
                    'ltextbox.Text = 
                    'Panel1.Controls.Add(ltextbox)
                    'Next
                Else
                    '############
                    'NO MESSAGES
                    '############
                    dt.Rows.Clear()
                    dt.Clear()
                    grdErrorLog = New GridView()
                    grdErrorLog.DataSource = dt
                    grdErrorLog.DataBind()



                    Dim noMsgLable As New Label
                    noMsgLable.Text = "There is No messages to display. . ." + grdErrorLog.Rows.Count.ToString()
                    Panel1.Controls.Add(noMsgLable)
                End If
            Else
                '############
                'NO MESSAGES
                '############

                dt.Rows.Clear()
                dt.Clear()
                grdErrorLog = New GridView()
                grdErrorLog.DataSource = dt
                grdErrorLog.DataBind()


                Dim noMsgLable As New Label
                noMsgLable.Text = "There is No messages to display. . ." + grdErrorLog.Rows.Count.ToString()
                Panel1.Controls.Add(noMsgLable)

            End If



        Catch ex As Exception
            '##########################################
            'IF THIS FAILS, JUST SKIP THE LOGGING PART
            '##########################################
            Response.Write(ex.Message + ex.StackTrace)

        End Try
    End Sub

    Protected Sub GetErrorMessages_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles GetErrorMessages.Click
        BuildTable()
    End Sub

    Protected Sub PurgeErrorMessages_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles PurgeErrorMessages.Click
        Try
            '###########################################
            'LOGG THE ERROR MESSAGE TO THE ERROR QUEUE
            '###########################################
            Dim tempErrorQLoc As String = ConfigurationManager.AppSettings("ErrorQueueLocation")
            Dim ErrorQueueLocation As String = Environment.MachineName & tempErrorQLoc
            Dim lMessageQComponent As New MessageQComponent
            lMessageQComponent.PurgeAllMessages(ErrorQueueLocation)

            Response.Write("<h1>Messages for server " & Environment.MachineName & " have been purged.<h1>")

            dt.Rows.Clear()
            dt.Clear()
            grdErrorLog = New GridView()
            grdErrorLog.DataSource = dt
            grdErrorLog.DataBind()


        Catch ex As Exception
            '##########################################
            'IF THIS FAILS, JUST SKIP THE LOGGING PART
            '##########################################
            Response.Write(ex.Message)
        End Try
    End Sub

   

    


	Protected Sub grdErrorLog_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdErrorLog.PageIndexChanging
		grdErrorLog.PageIndex = e.NewPageIndex
		BuildTable()
	End Sub

	Protected Sub grdErrorLog_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles grdErrorLog.Sorting
        BuildTable()

        'Dim _list As List(Of DateTime) = New List(Of DateTime)
        'Dim i As Integer = 0

        'For Each row As DataRow In dt.Rows
        '	Dim dTime As DateTime = DateTime.Parse(row("Date"))
        '          _list.Add(dTime)
        '      Next

        '      Dim _dtlist() As DateTime = _list.ToArray()
        '      Response.Write(_dtlist.Length.ToString())


        '      Dim dtree As Sorting.DateHeap = New Sorting.DateHeap(_dtlist, _dtlist.Length - 1)
        



        Dim _list As List(Of DateTime) = New List(Of DateTime)
        Dim _rows As List(Of DataRow) = New List(Of DataRow)


		'*******************************************************************************************************************
		
		Dim _rowcount As Integer = dt.Rows.Count
		Dim _dateArray(_rowcount, 2) As String
		Dim _innerErrorArray(_rowcount, 2) As String
		Dim _errorArray(_rowcount, 2) As String
		Dim _count As Integer = 0

		'*********************************************************************************************************************



        Dim dTime As DateTime
        For Each row As DataRow In dt.Rows
            dTime = DateTime.Parse(row("Date").ToString().Trim())

						'**************************************************
							_dateArray(_count, 0) = _count.ToString()
							_innerErrorArray(_count, 0) = _count.ToString()
							_errorArray(_count, 0) = _count.ToString()

							_dateArray(_count, 1) = CType(row("Date"), String)
							_innerErrorArray(_count, 1) = CType(row("InnerError"), String)
							_errorArray(_count, 1) = CType(row("Error"), String)

							_count = _count + 1
			
						'**************************************************

            _list.Add(dTime)
						_rows.Add(row)
        Next


        Dim _dlist() As DateTime = _list.ToArray()
        Console.WriteLine("Unsorted:")
        For Each i As DateTime In _dlist
            Console.WriteLine(i)
        Next
		'Response.Write(_dlist.Length.ToString())

		Dim bh As DateHeap = New DateHeap(_dlist, _dlist.Length)
		Dim ascending As Boolean = CType(Session("sortindex"), Boolean)
		If ascending Then
			Sorting.DateHeap.HeapSortMin(bh)
			Session("sortindex") = False
			'Response.Write("in ascending")
		Else
			Sorting.DateHeap.HeapSortMax(bh)
			Session("sortindex") = True
			'Response.Write("in descending")

		End If
		'     If grdErrorLog.SortDirection = SortDirection.Ascending Then
		'Sorting.DateHeap.HeapSortMin(bh)
		'     Else
		'Sorting.DateHeap.HeapSortMax(bh)

		'     End If

        'add rows back to tabl ein sorted order
        dt.Clear()

        For Each row As DataRow In _rows
            dt.Rows.Add(row)
        Next

						'*********************************************************
		Dim sortedTable As DataTable = New DataTable("sortedTable")
		Dim errCol As DataColumn = New DataColumn("Error")
		errCol.DataType = System.Type.GetType("System.String")
		sortedTable.Columns.Add(errCol)

		Dim innerErrCol As DataColumn = New DataColumn("InnerError")
		innerErrCol.DataType = System.Type.GetType("System.String")
		sortedTable.Columns.Add(innerErrCol)

		Dim dateCol As DataColumn = New DataColumn("Date")
		dateCol.DataType = System.Type.GetType("System.String")
		sortedTable.Columns.Add(dateCol)


		Dim j As Integer
		Dim k As Integer
		Dim drnew As DataRow

		For j = 0 To _dlist.Length - 1 Step 1
			For k = 0 To _dateArray.Length - 1 Step 1
				If _dlist(j).ToString() = _dateArray(k, 1) Then

					drnew = sortedTable.NewRow()
					drnew("Date") = _dateArray(k, 1).ToString()
					drnew("InnerError") = _innerErrorArray(k, 1).ToString()
					drnew("Error") = _errorArray(k, 1).ToString()
					sortedTable.Rows.Add(drnew)
					Exit For
				End If
			Next k
		Next j


		'*********************************************************


		'grdErrorLog.DataSource = _dlist
		grdErrorLog.DataSource = sortedTable
		grdErrorLog.DataBind()


	End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub
End Class
