Imports Microsoft.Practices.EnterpriseLibrary.Data
Imports System.Data.Common
Imports System.Data
Imports System.Collections.Generic


Partial Class Configurations_RedirectManagement
    Inherits AdminPage


    Private _cmd As DbCommand
    Private _db As Database
    Private RedirectPageCollection As New Dictionary(Of String, SiteRedirect)




    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        Me.DB = DatabaseFactory.CreateDatabase("Charter.Website.WS.CommerceEngineConnectionString")
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            If Session("user") Is Nothing Then
                '#####################################
                'SESSION EXPIRED, SEND TO MAIN PAGE
                '#####################################
                Response.Redirect(Me.UnAuthorizedUserRedirectPath())
            End If



            '#########################################################################
            'RIGHT NOW ONLY SITE ADMINS SHOULD BE USING THIS PAGE SO ALLOW ONLY THEM
            '#########################################################################
            Select Case True
                Case Me.IsInRole("ContentAdmin")
                    '#####################################
                    'CONTINUE ON AND GIVE ACCESS TO PAGE
                    '#####################################
                Case Else
                    Response.Redirect(Me.UnAuthorizedUserRedirectPath())
            End Select

            '################################################
            'CLEAR THE DISPLAY MESSAGE USED FOR ALL METHODS
            '################################################
            lblMessage.Text = ""
            lblMessage.ForeColor = Drawing.Color.Black
            btnOk.Visible = False

            If Not IsPostBack Then
                Call dataLoad()

                If ListBox1.SelectedIndex < 0 Then
                    ListBox1.DataSource = RedirectPageCollection.Keys
                    ListBox1.DataBind()
                    ListBox1.SelectedIndex = 0
                Else
                    '#################################
                    'USER HAS ALREADY SELECTED VALUE
                    '#################################

                End If

                Call loadForm()

            End If

            btnAddNewRedirect.Enabled = False
            btnCancelAddNewRedirect.Enabled = False

        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private ReadOnly Property UnAuthorizedUserRedirectPath() As String
        Get
            Select Case Environment.MachineName.ToLower
                Case "kstlmcc2p01"
                    '#######
                    'PROD WEB
                    '#######
                    Return "http://www.Charter.com/Visitors/Home.aspx"
                Case "kstlmcc2p02"
                    '#######
                    'PROD WEB 
                    '#######
                    Return "http://www.Charter.com/Visitors/Home.aspx"
                Case "kstlmweb66"
                    '#######
                    'UAT WEB 
                    '#######
                    Return "http://cc2uatx.chartercom.com/Visitors/Home.aspx"
                Case "kstlmweb67"
                    '#######
                    'UAT WEB 
                    '#######
                    Return "http://cc2uatx.chartercom.com/Visitors/Home.aspx"
                Case "kstlmcc2p03"
                    '#######
                    'PROD APP 
                    '#######
                    Return "http://cc2prda"
                Case "kstlmcc2p04"
                    '#######
                    'PROD APP 
                    '#######
                    Return "http://cc2prda"
                Case "kstlmweb68"
                    '#######
                    'UAT APP 
                    '#######
                    Return "http://cc2uata"
                Case "kstlmweb69"
                    '#######
                    'UAT APP
                    '#######
                    Return "http://cc2uata"
                Case "kstlmweb65"
                    '#######
                    'DEV WEB AND APP
                    '#######
                    Return "http://KSTLMWEB65:8080"
                Case "kstlintcncegenm"
                    '#######
                    'DEV WEB AND APP
                    '#######
                    Return "http://localhost/bl.remotinghost/login.aspx"
                Case Else
                    '#####################################
                    'THIS SHOULD ONLY BE LOCALHOST STUFF HERE.
                    '#####################################
                    Return "http://www.Charter.com/Visitors/Home.aspx"
            End Select
        End Get
    End Property

    Private Property DB() As Database
        Get
            Return _db
        End Get
        Set(ByVal value As Database)
            _db = value
        End Set
    End Property
    Private Property CMD() As DbCommand
        Get
            Return _cmd
        End Get
        Set(ByVal value As DbCommand)
            _cmd = value
        End Set
    End Property

    Sub dataLoad()
        Dim strSQL As String = "SELECT * FROM [Admin].[URL_REDIRECT_MAPPING] ORDER BY REQUEST_URL"
        Me.CMD = Me.DB.GetSqlStringCommand(strSQL)
        Dim DS As DataSet = DB.ExecuteDataSet(Me.CMD)

        If Not (DS Is Nothing) Then
            If DS.Tables.Count() > 0 Then

                '#############################################
                '#############################################

                For Each row As Data.DataRow In DS.Tables(0).Rows
                    Dim lRecord As New SiteRedirect
                    If Not (row.Item("ID") Is System.DBNull.Value) Then
                        If Not (row.Item("ID") Is Nothing) Then
                            lRecord.DBTableID = CType(row.Item("ID"), Integer)
                        End If
                    End If
                    If Not (row.Item("REQUEST_URL") Is System.DBNull.Value) Then
                        If Not (row.Item("REQUEST_URL") Is Nothing) Then
                            lRecord.RequestURL = CType(row.Item("REQUEST_URL").ToString().Trim().ToLower(), String)
                        End If
                    End If
                    If Not (row.Item("REDIRECT_URL") Is System.DBNull.Value) Then
                        If Not (row.Item("REDIRECT_URL") Is Nothing) Then
                            lRecord.RedirectURL = CType(row.Item("REDIRECT_URL").ToString().Trim().ToLower(), String)
                        End If
                    End If
                    '############################################################
                    'MODIFICATION   ROD COPELAND    7/18/2008   ISSUE ID 2374
                    'ADDING THE SEARCH ENGINE OPTIMIZATION USAGE INDICATOR
                    '############################################################
                    If Not (row.Item("SEOUse") Is System.DBNull.Value) Then
                        If Not (row.Item("SEOUse") Is Nothing) Then
                            lRecord.SEOUse = CType(row.Item("SEOUse"), Boolean)
                        End If
                    End If
                    '############################################################
                    If Not (row.Item("CREATE_DATE") Is System.DBNull.Value) Then
                        If Not (row.Item("CREATE_DATE") Is Nothing) Then
                            lRecord.CreateDate = CType(row.Item("CREATE_DATE"), Date)
                        End If
                    End If
                    If Not (row.Item("MODIFY_DATE") Is System.DBNull.Value) Then
                        If Not (row.Item("MODIFY_DATE") Is Nothing) Then
                            lRecord.ModifyDate = CType(row.Item("MODIFY_DATE"), Date)
                        End If
                    End If

                    If Not RedirectPageCollection.ContainsKey(lRecord.RequestURL) Then
                        RedirectPageCollection.Add(lRecord.RequestURL, lRecord)
                    End If
                Next

                '#############################################
                '#############################################


                '########################################################################################
                'THE USE OF THE SESSION OBJECT WAS DONE AFTER THE FACT.  THIS WASN'T THE PREFERED 
                'METHOD OF PERSISTANCE BECAUSE THE APPLICATION SERVERS DONT USE THE STICKY SESSIONS.
                'NO STICKY SESSIONS MEANS YOU DONT KNOW WHAT SERVER YOU'LL END UP ON, USING SESSION 
                'OBJECT WOULDN'T BE DEPENDABLE IT BEING THERE.
                'USING THE VIEWSTATE TO HOLD THE COLLECTION WAS RECOMMENDED.  THIS APPROACH WOULD BE 
                'FINE IF IT WASN'T FOR THE LARGE AMOUNT OF TEXT IN THE "PAGE SEARCH TEXT" FIELD BEING 
                'NEEDED AS PART OF THE COLLECTION AND STORING THE WHOLE COLLECTION IN VIEWSTATE. 
                'FOR PERFORMANCE REASONS, WE'LL USE THE SESSION OBJECT FOR NOW AND WHEN THE SESSION 
                'OBJECT IS NOTHING THEN WE'LL JUST MAKE ANOTHER CALL OUT TO GET IT AGAIN.  NOT A BIG 
                'DEAL FOR LESS THAN 5 USERS AT A TIME.
                '########################################################################################
                Session("RedirectPageCollection") = RedirectPageCollection

            Else
                If lblMessage.Text.Trim() = "" Then
                    lblMessage.Text = "No tables returned from the Redirect Management table"
                    lblMessage.ForeColor = Drawing.Color.Red
                    btnOk.Visible = True
                    btnOk.Focus()
                End If
            End If
        Else
            lblMessage.Text = "No tables returned from the Redirect Management table"
            lblMessage.ForeColor = Drawing.Color.Red
            btnOk.Visible = True
            btnOk.Focus()
        End If

    End Sub

    Private Function formIsValid() As Boolean
        Dim field1 As String = txtRequestURL.Text.Trim().ToLower()

        If Not field1.StartsWith("/") Then
            lblMessage.Text = "Request URL should begin with a forward slash '/'"
            lblMessage.ForeColor = Drawing.Color.Red
            btnOk.Visible = True
            btnOk.Focus()
            Return False
        End If
        If Not (field1.EndsWith(".aspx")) Then
            'If Not (field1.EndsWith(".asp")) Then
            '    If Not (field1.EndsWith(".htm")) Then
            '        If Not (field1.EndsWith(".html")) Then
            '            If Not (field1.EndsWith(".swf")) Then
            lblMessage.Text = "Request URL should end with a file extension of '.aspx'.  For Example, /yourFolderName/default.aspx"
            lblMessage.ForeColor = Drawing.Color.Red
            btnOk.Visible = True
            btnOk.Focus()
            Return False
            '            End If
            '        End If
            '    End If
            'End If
        End If

        Return True
    End Function

    Private Function Add_Update_Redirect() As Integer
        Dim returnCode As Integer
        Try
            If formIsValid() Then
                CMD = DB.GetStoredProcCommand("[Admin].[uspUpdateOrAddRedirectRecord]")

                If Not (Session("RedirectPageCollection") Is Nothing) Then
                    RedirectPageCollection = Session("RedirectPageCollection")
                Else
                    '############################
                    'LOAD SESSION FROM DB CALL 
                    '############################
                    Call dataLoad()
                End If


                If hiddenRequestURL.Value.Trim() = "" Then
                    If RedirectPageCollection.ContainsKey(txtRequestURL.Text.Trim().ToLower()) Then
                        '#####################################
                        'RECORD ALREADY EXISTS IN COLLECTION
                        '#####################################
                        lblMessage.Text = "The value for Request URL already exists in the Redirect Collection."
                        lblMessage.ForeColor = Drawing.Color.Red
                        btnOk.Visible = True
                        btnOk.Focus()
                        Return 9999
                    End If
                End If



                If RedirectPageCollection.ContainsKey(hiddenRequestURL.Value.Trim().ToLower()) Then
                    Dim lRedirect As SiteRedirect = RedirectPageCollection(hiddenRequestURL.Value.Trim().ToLower())
                    If Not (lRedirect Is Nothing) Then
                        DB.AddInParameter(CMD, "@ID", DbType.Int32, lRedirect.DBTableID)
                    End If
                End If
                If txtRequestURL.Text <> Nothing And txtRequestURL.Text.Trim() <> "" Then
                    DB.AddInParameter(CMD, "@REQUEST_URL", DbType.String, txtRequestURL.Text.Trim().ToLower())
                End If
                If txtRequestURL.Text <> Nothing And txtRequestURL.Text.Trim() <> "" Then
                    DB.AddInParameter(CMD, "@REDIRECT_URL", DbType.String, txtRedirectURL.Text.Trim().ToLower())
                End If

                '############################################################
                'MODIFICATION   ROD COPELAND    7/18/2008   ISSUE ID 2374
                'ADDING THE SEARCH ENGINE OPTIMIZATION USAGE INDICATOR
                '############################################################
                DB.AddInParameter(CMD, "@SEOUse", DbType.Boolean, chkSEORedirect.Checked)

                returnCode = DB.ExecuteScalar(CMD)

                Return returnCode
            Else
                Return 9999
            End If


        Catch ex As Exception
            Throw ex
        Finally
            If Not CMD Is Nothing Then
                CMD.Dispose()
            End If
        End Try
    End Function

    Protected Sub btnDeleteRedirect_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDeleteRedirect.Click

        Dim retCode As Integer
        Try
            Dim urlToDelete As String = ListBox1.SelectedValue.Trim()

            If urlToDelete.Trim() <> "" Then
                CMD = DB.GetStoredProcCommand("[Admin].[DELETE_REDIRECT_FROM_REDIRECT_MANAGEMENT]")


                If Not (Session("RedirectPageCollection") Is Nothing) Then
                    RedirectPageCollection = Session("RedirectPageCollection")
                Else
                    '############################
                    'LOAD SESSION FROM DB CALL 
                    '############################
                    Call dataLoad()
                End If


                If RedirectPageCollection.ContainsKey(urlToDelete.Trim().ToLower()) Then
                    Dim lRecord As SiteRedirect = RedirectPageCollection(urlToDelete.Trim().ToLower())
                    If Not (lRecord Is Nothing) Then
                        If Not (lRecord Is Nothing) Then
                            DB.AddInParameter(CMD, "@ID", DbType.Int32, lRecord.DBTableID)
                            retCode = DB.ExecuteScalar(CMD)

                            Response.Redirect("RedirectManagement.aspx")
                        Else
                            lblMessage.Text = "Cant find Request URL in Redirect Collection, this is needed to delete a URL."
                            lblMessage.ForeColor = Drawing.Color.Red
                            btnOk.Visible = True
                            btnOk.Focus()
                        End If
                    Else
                        lblMessage.Text = "Cant find Request URL in Redirect Collection, this is needed to delete a URL."
                        lblMessage.ForeColor = Drawing.Color.Red
                        btnOk.Visible = True
                        btnOk.Focus()
                    End If
                Else
                    lblMessage.Text = "Cant find Request URL in Redirect Collection, this is needed to delete a URL."
                    lblMessage.ForeColor = Drawing.Color.Red
                    btnOk.Visible = True
                    btnOk.Focus()
                End If
            Else
                lblMessage.Text = "No value selected in the URL list box, this is needed to delete a URL."
                lblMessage.ForeColor = Drawing.Color.Red
                btnOk.Visible = True
                btnOk.Focus()
            End If

        Catch ex As Exception
            Throw ex
        Finally
            If Not CMD Is Nothing Then
                CMD.Dispose()
            End If
        End Try

    End Sub

    Sub loadForm()
        '########################################################################################
        'THE USE OF THE SESSION OBJECT WAS DONE AFTER THE FACT.  THIS WASN'T THE PREFERED 
        'METHOD OF PERSISTANCE BECAUSE THE APPLICATION SERVERS DONT USE THE STICKY SESSIONS.
        'NO STICKY SESSIONS MEANS YOU DONT KNOW WHAT SERVER YOU'LL END UP ON, USING SESSION 
        'OBJECT WOULDN'T BE DEPENDABLE IT BEING THERE.
        'USING THE VIEWSTATE TO HOLD THE COLLECTION WAS RECOMMENDED.  
        'FOR PERFORMANCE REASONS, WE'LL USE THE SESSION OBJECT FOR NOW AND WHEN THE SESSION 
        'OBJECT IS NOTHING THEN WE'LL JUST MAKE ANOTHER CALL OUT TO GET IT AGAIN.  NOT A BIG 
        'DEAL FOR LESS THAN 5 USERS AT A TIME.
        '########################################################################################
        If (Session("RedirectPageCollection") Is Nothing) Then
            '############################
            'LOAD SESSION FROM DB CALL 
            '############################
            Call dataLoad()
        End If


        If Not (Session("RedirectPageCollection") Is Nothing) Then
            RedirectPageCollection = Session("RedirectPageCollection")

            If RedirectPageCollection.ContainsKey(ListBox1.SelectedValue) Then
                Dim lRecord As SiteRedirect = RedirectPageCollection(ListBox1.SelectedValue)

                If Not (lRecord Is Nothing) Then
                    lblTableID.Text = lRecord.DBTableID

                    If (lRecord.CreateDate = Nothing) Then
                        lblCreateDate.Text = ""
                    Else
                        lblCreateDate.Text = lRecord.CreateDate
                    End If
                    If (lRecord.ModifyDate = Nothing) Then
                        lblModifyDate.Text = ""
                    Else
                        lblModifyDate.Text = lRecord.ModifyDate
                    End If

                    '############################################################
                    'MODIFICATION   ROD COPELAND    7/18/2008   ISSUE ID 2374
                    'ADDING THE SEARCH ENGINE OPTIMIZATION USAGE INDICATOR
                    '############################################################
                    chkSEORedirect.Checked = lRecord.SEOUse

                    hiddenRequestURL.Value = lRecord.RequestURL
                    txtRequestURL.Text = lRecord.RequestURL
                    txtRequestURL.Columns = lRecord.RequestURL.Length()
                    txtRedirectURL.Text = lRecord.RedirectURL
                    txtRedirectURL.Columns = lRecord.RedirectURL.Length()
                End If

            End If
        Else
            '############################
            'LOAD SESSION FROM DB CALL 
            '############################
            Call dataLoad()
        End If
    End Sub
    Private Sub validateSEORedirectURL()
        If chkSEORedirect.Checked Then
            Select Case True
                Case txtRedirectURL.Text.Contains("kstlm"), txtRedirectURL.Text.Contains(".com"), txtRedirectURL.Text.Contains(".net"), txtRedirectURL.Text.Contains("https://"), txtRedirectURL.Text.Contains("http://")
                    Throw New Exception("SEO Redirect URLs can contain only relative paths.</br> Example: /visitors/products.aspx?menuitem=2. </br> Not allowed: http://www.charter.com/visitors/products.aspx?menuitem=2")
            End Select
            If Not txtRequestURL.Text.Trim().Contains("default.aspx") Then
                Throw (New Exception("SEO Request URLs must use a default.aspx.</br> Example: /moxi/default.aspx"))
            End If
            If Not txtRedirectURL.Text.Trim().Substring(0, 1).Contains("/") Then
                Throw (New Exception("SEO Redirect URLs must begin with a forward slash.</br>  Example: /" & txtRedirectURL.Text))
            End If
        End If
    End Sub

    Protected Sub btnUpdateRedirect_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpdateRedirect.Click
        Try
            Me.validateSEORedirectURL()

            Dim returnCode As Integer = Add_Update_Redirect()
            If returnCode <> 0 Then
                '###########################
                'SOMETHING BAD HAS HAPPENED.
                '###########################
                If lblMessage.Text.Trim() = "" Then
                    lblMessage.Text = "Doesnt appear that the Update of the existing record was successful. Return Code: " & returnCode
                    lblMessage.ForeColor = Drawing.Color.Red
                    btnOk.Visible = True
                    btnOk.Focus()
                End If
            Else
                '#################
                'GOOD RESPONSE
                '#################
                Response.Redirect("RedirectManagement.aspx")
            End If

        Catch ex As Exception
            lblMessage.Text = ex.Message.ToString()
            lblMessage.ForeColor = Drawing.Color.Red
            btnOk.Visible = True
            btnOk.Focus()
        End Try
    End Sub
    Protected Sub btnCreateNewRedirect_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCreateNewRedirect.Click
        '###################################
        'HIDE BUTTONS THAT ARE NOT NEEDED.
        '###################################
        btnCreateNewRedirect.Enabled = False
        btnDeleteRedirect.Enabled = False
        btnUpdateRedirect.Enabled = False

        '###################################
        'CLEAR THE WEBFORM
        '###################################
        lblCreateDate.Text = ""
        lblTableID.Text = ""

        '############################################################
        'MODIFICATION   ROD COPELAND    7/18/2008   ISSUE ID 2374
        'ADDING THE SEARCH ENGINE OPTIMIZATION USAGE INDICATOR
        '############################################################
        chkSEORedirect.Checked = False

        lblModifyDate.Text = ""
        hiddenRequestURL.Value = ""
        txtRequestURL.Text = "/root_folder1/subfolder2/default.aspx"
        txtRedirectURL.Text = "http://www.charter.com/visitors/support.aspx"

        '####################
        'DISABLE THE LISTBOX
        '####################
        ListBox1.Enabled = False

        '###################
        'APPLY FORMATTING
        '###################
        txtRequestURL.Columns = txtRequestURL.Text.Length()


        '#######################
        'ENABLE THE ADD BUTTON
        '#######################
        btnAddNewRedirect.Enabled = True
        btnCancelAddNewRedirect.Enabled = True


        txtRequestURL.Focus()

    End Sub
    Protected Sub btnAddNewRedirect_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddNewRedirect.Click
        Try
            Me.validateSEORedirectURL()

            Dim returnCode As Integer = Add_Update_Redirect()
            If returnCode <> 0 Then
                '###########################
                'SOMETHING BAD HAS HAPPENED.
                '###########################
                If lblMessage.Text.Trim() = "" Then
                    lblMessage.Text = "Doesnt appear that the Addition of the new record was successful. Return Code: " & returnCode
                    lblMessage.ForeColor = Drawing.Color.Red
                    btnOk.Visible = True
                    btnOk.Focus()
                End If
            Else
                '#################
                'GOOD RESPONSE
                '#################
                Response.Redirect("RedirectManagement.aspx")
            End If
        Catch ex As Exception
            lblMessage.Text = ex.Message.ToString()
            lblMessage.ForeColor = Drawing.Color.Red
            btnOk.Visible = True
            btnOk.Focus()
        End Try
    End Sub
    Protected Sub btnCancelAddNewRedirect_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancelAddNewRedirect.Click
        '###############
        'RESET PAGE
        '###############
        Response.Redirect("RedirectManagement.aspx")
    End Sub
    Protected Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
        Call loadForm()

    End Sub

    Protected Sub btnOk_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnOk.Click
        Response.Redirect("RedirectManagement.aspx")
    End Sub
End Class
