Option Explicit On 

Imports System.IO
Imports System.Data
Imports System.Data.SqlClient

Public Class AdminFileManager
    Inherits System.Web.UI.Page
    Protected resultDirs As SqlDataReader
    Protected resultFiles As SqlDataReader
    Protected WithEvents FolderNameTB As System.Web.UI.WebControls.TextBox
    Protected WithEvents NewFolderBtn As System.Web.UI.WebControls.Button
    Protected WithEvents Textbox1 As System.Web.UI.WebControls.TextBox
    Protected WithEvents FolderDescTB As System.Web.UI.WebControls.TextBox
    Protected WithEvents RFV1 As System.Web.UI.WebControls.RequiredFieldValidator
    Protected WithEvents ErrorLbl As System.Web.UI.HtmlControls.HtmlGenericControl
    Protected WithEvents Requiredfieldvalidator1 As System.Web.UI.WebControls.RequiredFieldValidator

    'Protected directoryListing As DataList
#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents Directory_listing As System.Web.UI.WebControls.DataList

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub
    Protected WithEvents display_name2 As System.Web.UI.WebControls.TextBox
    Protected WithEvents display_name1 As System.Web.UI.WebControls.TextBox
    Protected WithEvents display_name3 As System.Web.UI.WebControls.TextBox
    Protected WithEvents display_name4 As System.Web.UI.WebControls.TextBox
    Protected WithEvents display_name5 As System.Web.UI.WebControls.TextBox
    Protected WithEvents uploadedFile1 As System.Web.UI.HtmlControls.HtmlInputFile
    Protected WithEvents uploadedFile2 As System.Web.UI.HtmlControls.HtmlInputFile
    Protected WithEvents uploadedFile3 As System.Web.UI.HtmlControls.HtmlInputFile
    Protected WithEvents uploadedFile4 As System.Web.UI.HtmlControls.HtmlInputFile
    Protected WithEvents uploadedFile5 As System.Web.UI.HtmlControls.HtmlInputFile
    Protected WithEvents upload_files As System.Web.UI.WebControls.Button
    Protected WithEvents dirid As System.Web.UI.WebControls.ListBox

#End Region
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        If Not Page.IsPostBack Then
            getAllDirs() 'for populating list box
            Dim listItem As System.Web.UI.WebControls.ListItem
            While resultDirs.Read()
                listItem = New System.Web.UI.WebControls.ListItem
                listItem.Text = resultDirs.Item("name")
                listItem.Value = resultDirs.Item("id")
                dirid.Items.Add(listItem)
            End While
            getAllDirs() 'for home dirs
            getFilesCount()
            If Request.QueryString("del_file") <> "" Then
                DeleteFile(Request.QueryString("del_file"))
                'Response.Redirect("TeachersFileManager.aspx")
            End If
            If Request.QueryString("down_file") <> "" Then
                DownloadFile(Request.QueryString("down_file"))
                Response.End()
                'Response.Redirect("TeachersFileManager.aspx")
            End If
            If Request.QueryString("del_dir") <> "" Then
                DeleteDir(Request.QueryString("del_dir"))
                'Response.Redirect("TeachersFileManager.aspx")
            End If
        End If
    End Sub

    Private Sub DeleteFile(ByVal id As Int32)
        'Create Instance of Connection and Command Object
        Try
            Dim myConnection As SqlConnection
            myConnection = New SqlConnection
            myConnection.ConnectionString = ConfigurationSettings.AppSettings("sConnection")
            Dim myCommand As SqlCommand
            myCommand = New SqlCommand("as_DelFile", myConnection)
            'Mark the Command as a SPROC
            myCommand.CommandType = CommandType.StoredProcedure
            'Add Parameters to SPROC
            Dim parameterClassId As SqlParameter
            parameterClassId = New SqlParameter("@id", SqlDbType.Int)
            parameterClassId.Value = id
            myCommand.Parameters.Add(parameterClassId)

            'Execute the command			
            myConnection.Open()
            myCommand.ExecuteNonQuery()
            myConnection.Close()
        Catch ex As Exception
            Response.Write(ex.ToString())
        End Try
    End Sub
    Private Sub DeleteDir(ByVal id As Int32)
        'Create Instance of Connection and Command Object
        Try
            Dim myConnection As SqlConnection
            myConnection = New SqlConnection
            myConnection.ConnectionString = ConfigurationSettings.AppSettings("sConnection")
            Dim myCommand As SqlCommand
            myCommand = New SqlCommand("as_DelDir", myConnection)
            'Mark the Command as a SPROC
            myCommand.CommandType = CommandType.StoredProcedure
            'Add Parameters to SPROC
            Dim parameterClassId As SqlParameter
            parameterClassId = New SqlParameter("@id", SqlDbType.Int)
            parameterClassId.Value = id
            myCommand.Parameters.Add(parameterClassId)

            'Execute the command			
            myConnection.Open()
            myCommand.ExecuteNonQuery()
            myConnection.Close()
        Catch ex As Exception
            Response.Write(ex.ToString())
        End Try
    End Sub
    Private Sub DownloadFile(ByVal id As Int32)
        'Create Instance of Connection and Command Object
        Try
            Dim myConnection As SqlConnection
            myConnection = New SqlConnection
            myConnection.ConnectionString = ConfigurationSettings.AppSettings("sConnection")
            Dim myCommand As SqlCommand
            myCommand = New SqlCommand("as_GetFile", myConnection)
            'Mark the Command as a SPROC
            myCommand.CommandType = CommandType.StoredProcedure
            'Add Parameters to SPROC
            Dim parameterClassId As SqlParameter
            parameterClassId = New SqlParameter("@id", SqlDbType.Int)
            parameterClassId.Value = id
            myCommand.Parameters.Add(parameterClassId)

            'Execute the command			
            myConnection.Open()
            'Assign to datareader 
            Dim result As System.Data.SqlClient.SqlDataReader
            result = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
            If result.Read() Then
                Dim filepath As String = Server.MapPath("..") & "\contents\teachers\" & _
                    result.Item("classid") & "\" & result.Item("dirid") & "\" & result.Item("actualname")
                If System.IO.File.Exists(filepath) Then
                    Dim filename As String = System.IO.Path.GetFileName(filepath)
                    Response.Clear()
                    Response.ContentType = "application/octet-stream"
                    Response.AddHeader("Content-Disposition", _
                      "attachment; filename=""" & filename & """")
                    Response.Flush()
                    Response.WriteFile(filepath)
                End If
            End If
        Catch ex As Exception
            Response.Write(ex.ToString())
        End Try
    End Sub
    Private Sub getAllDirs()
        'Create Instance of Connection and Command Object
        Try
            Dim myConnection As SqlConnection
            myConnection = New SqlConnection
            myConnection.ConnectionString = ConfigurationSettings.AppSettings("sConnection")
            Dim myCommand As SqlCommand
            myCommand = New SqlCommand("as_GetAllDirs", myConnection)
            'Mark the Command as a SPROC
            myCommand.CommandType = CommandType.StoredProcedure
            'Add Parameters to SPROC
            Dim parameterDirType As SqlParameter
            parameterDirType = New SqlParameter("@DirType", SqlDbType.VarChar, 255)
            parameterDirType.Value = "admin"
            myCommand.Parameters.Add(parameterDirType)
            'Execute the command			
            myConnection.Open()
            'Assign to datareader 
            resultDirs = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
        Catch ex As Exception
            Response.Write(ex.ToString())
        End Try
    End Sub
    Private Function getFilesCount() As System.Data.SqlClient.SqlDataReader
        'Create Instance of Connection and Command Object
        Try
            Dim myConnection As SqlConnection
            myConnection = New SqlConnection
            myConnection.ConnectionString = ConfigurationSettings.AppSettings("sConnection")
            Dim myCommand As SqlCommand
            myCommand = New SqlCommand("as_GetFilesCount", myConnection)
            'Mark the Command as a SPROC
            myCommand.CommandType = CommandType.StoredProcedure
            'Add Parameters to SPROC
            Dim parameterClassId As SqlParameter
            parameterClassId = New SqlParameter("@ClassId", SqlDbType.Int)
            parameterClassId.Value = Int32.Parse(Session("ClassPageID").ToString())
            myCommand.Parameters.Add(parameterClassId)
            'Execute the command			
            myConnection.Open()
            'Assign to datareader 
            Dim result As System.Data.SqlClient.SqlDataReader
            result = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
            Return result
        Catch ex As Exception
            Response.Write(ex.ToString())
        End Try
    End Function
    Public Function getFileCount(ByVal dirid As Int32) As Int32
        Dim result As System.Data.SqlClient.SqlDataReader = getFilesCount()
        If Not result Is Nothing Then
            If result.HasRows = True Then
                While result.Read()
                    If result.Item("dirid") = dirid Then
                        Return result.Item("total")
                    End If
                End While
            End If
        End If
    End Function
    Public Sub getFiles(ByVal dirid As Int32)
        'Create Instance of Connection and Command Object
        Try
            Dim myConnection As SqlConnection
            myConnection = New SqlConnection
            myConnection.ConnectionString = ConfigurationSettings.AppSettings("sConnection")
            Dim myCommand As SqlCommand
            myCommand = New SqlCommand("as_GetFiles", myConnection)
            'Mark the Command as a SPROC
            myCommand.CommandType = CommandType.StoredProcedure
            'Add Parameters to SPROC
            Dim parameterClassId As SqlParameter
            parameterClassId = New SqlParameter("@ClassId", SqlDbType.Int)
            parameterClassId.Value = Int32.Parse(Session("ClassPageID").ToString())
            myCommand.Parameters.Add(parameterClassId)

            Dim parameterDirId As SqlParameter
            parameterDirId = New SqlParameter("@DirId", SqlDbType.Int)
            parameterDirId.Value = dirid
            myCommand.Parameters.Add(parameterDirId)
            'Execute the command			
            myConnection.Open()
            'Assign to datareader 
            resultFiles = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
        Catch ex As Exception
            Response.Write(ex.ToString())
        End Try
    End Sub
    Private Sub upload_files_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles upload_files.Click
        Dim filename As Array

        If uploadedFile1.PostedFile.FileName.ToString() <> "" Then
            filename = uploadedFile1.PostedFile.FileName.Split(Chr(92))
            upload_file(display_name1.Text, uploadedFile1.PostedFile, Int32.Parse(dirid.SelectedItem.Value), Int32.Parse(Session("ClassPageID").ToString()), filename(filename.Length - 1))
        End If
        If uploadedFile2.PostedFile.FileName.ToString() <> "" Then
            filename = uploadedFile2.PostedFile.FileName.Split(Chr(92))
            upload_file(display_name2.Text, uploadedFile2.PostedFile, Int32.Parse(dirid.SelectedItem.Value), Int32.Parse(Session("ClassPageID").ToString()), filename(filename.Length - 1))
        End If
        If uploadedFile3.PostedFile.FileName.ToString() <> "" Then
            filename = uploadedFile3.PostedFile.FileName.Split(Chr(92))
            upload_file(display_name3.Text, uploadedFile3.PostedFile, Int32.Parse(dirid.SelectedItem.Value), Int32.Parse(Session("ClassPageID").ToString()), filename(filename.Length - 1))
        End If
        If uploadedFile4.PostedFile.FileName.ToString() <> "" Then
            filename = uploadedFile4.PostedFile.FileName.Split(Chr(92))
            upload_file(display_name4.Text, uploadedFile4.PostedFile, Int32.Parse(dirid.SelectedItem.Value), Int32.Parse(Session("ClassPageID").ToString()), filename(filename.Length - 1))
        End If
        If uploadedFile5.PostedFile.FileName.ToString() <> "" Then
            filename = uploadedFile5.PostedFile.FileName.Split(Chr(92))
            upload_file(display_name5.Text, uploadedFile5.PostedFile, Int32.Parse(dirid.SelectedItem.Value), Int32.Parse(Session("ClassPageID").ToString()), filename(filename.Length - 1))
        End If
        Response.Redirect("AdminFileManager.aspx")
    End Sub
    Private Sub upload_file(ByRef name As String, ByRef postedFile As System.Web.HttpPostedFile, ByRef dirid As Int32, ByRef classid As Int32, ByVal actualname As String)
        Dim savePath As String = Server.MapPath("..") & "\contents\teachers\"

        If Not Directory.Exists(savePath & classid.ToString()) Then
            'create teacher's level directory
            Directory.CreateDirectory(savePath & classid.ToString())
        End If
        If Not Directory.Exists(savePath & classid.ToString() & "\" & dirid.ToString()) Then
            'create document level directory
            Directory.CreateDirectory(savePath & classid.ToString() & "\" & dirid.ToString())
        End If
        savePath = savePath & classid.ToString() & "\" & dirid.ToString() & "\"
        Dim filename As String
        If Not (postedFile Is Nothing) Then
            Try
                filename = Path.GetFileName(postedFile.FileName)
                postedFile.SaveAs(savePath & filename)
                'now save the file record into the DB also
                save_file(name, dirid, classid, actualname)
            Catch ex As Exception
                Response.Write(ex.ToString())
            End Try
        End If
    End Sub

    Private Sub save_file(ByRef filename As String, ByRef dirid As Int32, ByRef classid As Int32, ByVal actualname As String)
        Try
            Dim myConnection As SqlConnection
            myConnection = New SqlConnection
            myConnection.ConnectionString = ConfigurationSettings.AppSettings("sConnection")
            Dim myCommand As SqlCommand
            myCommand = New SqlCommand("as_InsertDocumentFile", myConnection)
            'Mark the Command as a SPROC
            myCommand.CommandType = CommandType.StoredProcedure
            'Add Parameters to SPROC
            Dim parameterFileName As SqlParameter
            parameterFileName = New SqlParameter("@FileName", SqlDbType.VarChar, 255)
            If filename = "" Then
                filename = actualname
            End If
            parameterFileName.Value = filename
            myCommand.Parameters.Add(parameterFileName)

            Dim parameterClassId As SqlParameter
            parameterClassId = New SqlParameter("@ClassId", SqlDbType.Int)
            parameterClassId.Value = classid
            myCommand.Parameters.Add(parameterClassId)

            Dim parameterDirId As SqlParameter
            parameterDirId = New SqlParameter("@DirId", SqlDbType.Int)
            parameterDirId.Value = dirid
            myCommand.Parameters.Add(parameterDirId)

            Dim parameterActualName As SqlParameter
            parameterActualName = New SqlParameter("@ActualName", SqlDbType.VarChar, 255)
            parameterActualName.Value = actualname
            myCommand.Parameters.Add(parameterActualName)

            'Execute the command			
            myConnection.Open()
            'Assign to datareader 
            myCommand.ExecuteNonQuery()
            myConnection.Close()
        Catch ex As Exception
            Response.Write(ex.ToString())
        End Try
    End Sub

    Private Sub NewFolderBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewFolderBtn.Click

        If FolderNameTB.Text.Trim().Equals("") = False Then
            ErrorLbl.InnerText = ""
            Dim Conn As New SqlConnection(ConfigurationSettings.AppSettings("sConnection"))
            Try
                Dim cmd As New SqlCommand
                Dim query As String = ""

                Dim _name As String = FolderNameTB.Text.Trim().Replace("'", "''")
                Dim _desc As String = FolderDescTB.Text.Trim().Replace("'", "''")

                query = "insert into as_DocumentDirs values('" & _name & "','" & _desc & "','admin')"

                If (query <> "") Then
                    If Conn.State = ConnectionState.Closed Then
                        Conn.ConnectionString = ConfigurationSettings.AppSettings("sConnection")
                    End If

                    With cmd
                        .CommandText = query
                        .CommandType = CommandType.Text
                        If Conn.State = ConnectionState.Closed Then Conn.Open()
                        .Connection = Conn
                        .ExecuteNonQuery()
                    End With

                    If Conn.State = ConnectionState.Open Then Conn.Close()
                    getAllDirs()
                    'Response.Redirect("AdminFileManager.aspx")
                End If
            Catch ex As Exception
                If Conn.State = ConnectionState.Open Then Conn.Close()
                Response.Write(ex.Message)
            End Try
        Else
            getAllDirs()
            ErrorLbl.Style.Add("font-size", "10px;")
            ErrorLbl.InnerText = "Folder name is required"
        End If
    End Sub
End Class
