Imports System.IO

Partial Class _CMS_Management_Backend_CMS_Management
    Inherits System.Web.UI.Page


    Private _CurrentDirectoryPath As String
    Private _CurrentFileName As String

    Private ReadOnly Property CurrentDirectoryPath() As String
        Get
            Return TreeView1.SelectedValue.Replace("/", "\")
        End Get
    End Property
    Private ReadOnly Property CurrentFileName() As String
        Get
            Return ListBox1.SelectedValue
        End Get
    End Property
    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/Visitors/Home.aspx"
                Case Else
                    '#####################################
                    'THIS SHOULD ONLY BE LOCALHOST STUFF HERE.
                    '#####################################
                    Return "http://www.Charter.com/Visitors/Home.aspx"
            End Select
        End Get
    End Property

    Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load
        Try
            Dim populatePage As Boolean = False

            '####################################################################################
            'TO DISABLE THIS PAGE UNTIL ITS NEEDED, REMOVE THIS VALUE 
            'RELEVANT_CONTENT_UPLOAD_PATH_ADMIN FROM THE DB TABLE AND THE 
            'PAGE SHOULD FAIL, NOT ALOWING THE CMS FUNCTIONALITY TO BE EXPOSED.
            'TO USE THIS PAGE, JUST ENTER THE VALUE IN THE DB TABLE AND RESET SITE SETTINGS
            '####################################################################################
            If (Application("RELEVANT_CONTENT_UPLOAD_PATH_ADMIN") Is Nothing) Or (Application("RELEVANT_CONTENT_UPLOAD_PATH_ADMIN").ToString().Trim() = "") Then
                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(ConfigurationManager.AppSettings("SiteAdminRoleName"))
            '        populatePage = True
            '    Case Else
            '        Response.Redirect(Me.UnAuthorizedUserRedirectPath())
            'End Select

            'If populatePage Then
            '##########################################
            'RESET COLOR FOR INITIAL LOAD OF THE PAGE,
            'CLEAR OUT ANY OLD MESSAGES.
            '##########################################
            lblStatusMessage.Text = ""
            lblStatusMessage.ForeColor = Drawing.Color.Black

            If Not IsPostBack Then
                PopulateTree()
            End If
            'End If
        Catch ex As Exception
            lblStatusMessage.Text = ex.Message
            lblStatusMessage.ForeColor = Drawing.Color.Red
        End Try

    End Sub

    Private Sub PopulateTree()
        Try
            Dim rootFolder As DirectoryInfo
            '#############################################################
            'POPULATE THE TREE BASED ON THE SUBFOLDERS OF THE SPECIFIED
            'VIRTUALIMAGEROOT
            '#############################################################
            rootFolder = New DirectoryInfo(Application("RELEVANT_CONTENT_UPLOAD_PATH_ADMIN"))
            Dim root As TreeNode = AddNodeAndDescendents(rootFolder, Nothing)

            '#############################################################
            'ADD THE ROOT TO THE TREEVIEW
            '#############################################################
            TreeView1.Nodes.Clear()
            TreeView1.Nodes.Add(root)
        Catch ex As Exception
            Throw New Exception(ex.Message)
        End Try

    End Sub

    Sub UploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Try
            '#################################################
            ' BEFORE ATTEMPTING TO SAVE THE FILE, VERIFY
            ' THAT THE FILEUPLOAD CONTROL CONTAINS A FILE.
            '#################################################
            If (FileUpload1.HasFile) Then
                '#################################################
                'ALL GOOD: CALL A HELPER METHOD ROUTINE TO SAVE THE FILE.
                '#################################################
                SaveFile(FileUpload1.PostedFile)
            Else
                '#################################################
                'A PROBLEM: NOTIFY THE USER THAT A FILE WAS NOT UPLOADED.
                '#################################################
                FileUpload1.Focus()
                lblStatusMessage.ForeColor = Drawing.Color.Red
                lblStatusMessage.Text = "You did not specify a file to upload."
            End If
        Catch ex As Exception
            lblStatusMessage.Text = ex.Message
            lblStatusMessage.ForeColor = Drawing.Color.Red
        End Try
    End Sub

    Sub SaveFile(ByVal file As HttpPostedFile)
        Try
            '#############################################################
            ' CHECK TO SEE IF A FILE ALREADY EXISTS WITH THE
            ' SAME NAME AS THE FILE TO UPLOAD.      
            '#############################################################
            If (System.IO.File.Exists(Me.CurrentDirectoryPath & FileUpload1.FileName)) Then
                FileUpload1.Focus()
                lblStatusMessage.ForeColor = Drawing.Color.Red
                lblStatusMessage.Text = "A file with the same name already exists at this location.  File not saved."
            Else
                '#############################################################
                ' CALL THE SAVEAS METHOD TO SAVE THE UPLOADED
                ' FILE TO THE SPECIFIED DIRECTORY.
                '#############################################################
                FileUpload1.SaveAs(Me.CurrentDirectoryPath & FileUpload1.FileName)

                '#############################################################
                ' NOTIFY THE USER THAT THE FILE WAS SAVED SUCCESSFULLY.
                '#############################################################
                lblStatusMessage.ForeColor = Drawing.Color.Green
                lblStatusMessage.Text = "Your file was uploaded successfully."

            End If

            '#############################################################
            'REFRESH LIST
            '#############################################################
            DisplayFilesInFolder(Me.CurrentDirectoryPath)

        Catch ex As Exception
            Throw New Exception(ex.Message)
        End Try
    End Sub

    Private Function AddNodeAndDescendents(ByVal folder As DirectoryInfo, ByVal parentNode As TreeNode) As TreeNode
        Try

            '##########################################################
            'THIS FOLDER AND SUBFOLDERS IS HUGE AND NEVER CHANGES.
            'IT SLOWS THE PAGE LOAD DOWN, SINCE NOTHING CHANGES IN 
            'IT, JUST SKIP IT.
            '##########################################################
            If (folder.FullName.ToLower().Contains("fckeditor")) Then
                Return Nothing
            End If

            '#############################################################
            'ADD THE TREENODE, DISPLAYING THE FOLDER'S NAME AND 
            'STORING THE FULL PATH TO THE FOLDER AS THE VALUE...
            '#############################################################
            Dim virtualFolderPath As String
            If parentNode Is Nothing Then
                virtualFolderPath = Application("RELEVANT_CONTENT_UPLOAD_PATH_ADMIN")
            Else
                virtualFolderPath = parentNode.Value & folder.Name & "/"
            End If

            Dim node As New TreeNode(folder.Name, virtualFolderPath)
            '#############################################################
            'RECURSE THROUGH THIS FOLDER'S SUBFOLDERS
            '#############################################################
            Dim subFolders As DirectoryInfo() = folder.GetDirectories()
            For Each subFolder As DirectoryInfo In subFolders
                Dim child As TreeNode = AddNodeAndDescendents(subFolder, node)
                If Not child Is Nothing Then
                    node.ChildNodes.Add(child)
                End If
            Next

            Return node

        Catch ex As Exception
            Throw New Exception(ex.Message)
        End Try
    End Function


    Protected Sub PictureTree_SelectedNodeChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TreeView1.SelectedNodeChanged
        Try
            '#############################################################
            'REFRESH THE DATALIST WHENEVER A NEW NODE IS SELECTED
            '#############################################################
            DisplayFilesInFolder(Me.CurrentDirectoryPath)

        Catch ex As Exception
            lblStatusMessage.Text = ex.Message
            lblStatusMessage.ForeColor = Drawing.Color.Red
        End Try
    End Sub

    Private Sub DisplayFilesInFolder(ByVal virtualFolderPath As String)
        Try
            '#############################################################
            'GET INFORMATION ABOUT THE FILES IN THE SPECIFIED FOLDER
            '#############################################################
            Dim folder As DirectoryInfo = New DirectoryInfo(virtualFolderPath)
            Dim fileList As FileInfo() = folder.GetFiles()

            ListBox1.DataSource = fileList
            ListBox1.DataBind()
        Catch ex As Exception
            Throw New Exception(ex.Message)
        End Try

    End Sub

    Protected Sub btnDeleteFile_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDeleteFile.Click
        Try
            'Dim lpath As String
            '#############################
            'VERIFY WE HAVE A FILE PATH
            '#############################
            If Not (TreeView1.SelectedValue Is Nothing Or TreeView1.SelectedValue = "") Then
                '#############################
                'VERIFY WE HAVE A FILE NAME
                '#############################
                If Not (Me.CurrentFileName Is Nothing Or Me.CurrentFileName = "") Then
                    '##########################
                    'DO THE DELETE
                    '##########################
                    File.SetAttributes(Me.CurrentDirectoryPath & Me.CurrentFileName, FileAttributes.Normal)
                    File.Delete(Me.CurrentDirectoryPath & Me.CurrentFileName)

                    '###################################
                    'DISPLAY A SUCCESS CONFIRMATION
                    '###################################
                    lblStatusMessage.Text = Me.CurrentFileName & " was deleted successfully."
                    lblStatusMessage.ForeColor = Drawing.Color.Green

                    '#############################################################
                    'REFRESH LIST
                    '#############################################################
                    DisplayFilesInFolder(Me.CurrentDirectoryPath)
                Else
                    '#######################
                    'SELECT A FILE NAME
                    '#######################
                    ListBox1.Focus()
                    lblStatusMessage.Text = "Please select a file name to delete."
                    lblStatusMessage.ForeColor = Drawing.Color.Red
                End If
            Else
                '###################################
                'SELECT A PATH IN THE FILE SYSTEM
                '###################################
                TreeView1.Focus()
                lblStatusMessage.Text = "Please select a file path to delete a file from."
                lblStatusMessage.ForeColor = Drawing.Color.Red
            End If
        Catch ex As Exception
            lblStatusMessage.Text = ex.Message
            lblStatusMessage.ForeColor = Drawing.Color.Red
        End Try

    End Sub

    Protected Sub btnRemoveSelectedDir_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRemoveSelectedDir.Click
        Try
            '######################################################
            'VERIFY WE HAVE A PATH SELECTED IN THE TREE CONTROL
            '######################################################
            If Not (TreeView1.CheckedNodes Is Nothing) Then
                If TreeView1.CheckedNodes.Count > 0 Then
                    For Each TreeItem As TreeNode In TreeView1.CheckedNodes
                        '#############################################
                        'DELETE FROM FILE SYSTEM ALL CHILD FOLDERS 
                        'AND FILES UNDER THE SELECT DIRECTORIES.
                        '#############################################
                        Dim lDirectory As DirectoryInfo
                        lDirectory = New DirectoryInfo(TreeItem.Value)

                        Call DeleteFoldersAndFiles(lDirectory)
                    Next

                    '##########################################################
                    'CLEAR PAGE, FOR NOW JUST REDIRECT TO THIS PAGE TO RESET.
                    '##########################################################
                    Response.Redirect("Backend_CMS_Management.aspx")
                Else
                    '##########################################################
                    'SELECT A PATH IN THE FILE SYSTEM
                    '##########################################################
                    TreeView1.Focus()
                    lblStatusMessage.Text = "Please Check-Mark the directories to delete. Directories and files within select directory will be deleted also."
                    lblStatusMessage.ForeColor = Drawing.Color.Red
                End If

            Else
                '##########################################################
                'SELECT A PATH IN THE FILE SYSTEM
                '##########################################################
                TreeView1.Focus()
                lblStatusMessage.Text = "Please select a directory to delete."
                lblStatusMessage.ForeColor = Drawing.Color.Red
            End If

        Catch ex As Exception
            lblStatusMessage.Text = ex.Message
            lblStatusMessage.ForeColor = Drawing.Color.Red
        End Try
    End Sub

    Sub DeleteFoldersAndFiles(ByVal FolderFrom As DirectoryInfo)
        Try
            Dim Files() As String = Directory.GetFiles(FolderFrom.FullName)
            Dim SF() As String = Directory.GetDirectories(FolderFrom.FullName)

            '###################
            'DELETE FILES
            '###################
            Dim strFile As String
            For Each strFile In Files
                File.SetAttributes(strFile, FileAttributes.Normal)
                File.Delete(strFile)
            Next strFile


            '###################
            'DELETE FOLDERS
            '###################
            Dim strFolder As String
            For Each strFolder In SF
                Dim tempDirectory As New DirectoryInfo(strFolder)
                '#######################################
                'DO A RECURSIVE CALL DOWN TO THIS SUB AGAIN.
                '#######################################
                DeleteFoldersAndFiles(tempDirectory)
            Next strFolder


            '###################
            'DELETE THIS FOLDER
            '###################
            Directory.Delete(FolderFrom.FullName)

        Catch ex As Exception
            Throw New Exception(ex.Message)
        End Try

    End Sub

    Protected Sub btnCreateNewDirectory_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCreateNewDirectory.Click
        Try
            Dim lpath As String
            '#############################
            'VERIFY WE HAVE A DIRECTORY PATH
            '#############################
            If txtNewDirectoryName.Text.Trim() <> "" Then
                If Not (TreeView1.SelectedValue Is Nothing Or TreeView1.SelectedValue = "") Then
                    lpath = Me.CurrentDirectoryPath & txtNewDirectoryName.Text.ToString().Trim()

                    If Directory.Exists(lpath) Then
                        txtNewDirectoryName.Focus()
                        lblStatusMessage.Text = "Directory name entered already exists.  Directory not created."
                        lblStatusMessage.ForeColor = Drawing.Color.Red
                    Else
                        Directory.CreateDirectory(lpath)
                        lblStatusMessage.Text = Me.CurrentFileName & " was created successfully."
                        lblStatusMessage.ForeColor = Drawing.Color.Green


                        '##########################################################
                        'CLEAR PAGE, FOR NOW JUST REDIRECT TO THIS PAGE TO RESET.
                        '##########################################################
                        Response.Redirect("Backend_CMS_Management.aspx")
                    End If
                Else
                    TreeView1.Focus()
                    lblStatusMessage.Text = "Please select a directory as the root directory so you can create your new directory in."
                    lblStatusMessage.ForeColor = Drawing.Color.Red
                End If

            Else
                '####################################
                'SELECT A PATH IN THE FILE SYSTEM
                '####################################
                txtNewDirectoryName.Focus()
                lblStatusMessage.Text = "Please enter a directory name to create."
                lblStatusMessage.ForeColor = Drawing.Color.Red
            End If
        Catch ex As Exception
            lblStatusMessage.Text = ex.Message
            lblStatusMessage.ForeColor = Drawing.Color.Red
        End Try
    End Sub
End Class
