Imports System.Data.OleDb
Imports AcggDoc.Acgg.dbClass
Imports System.IO



Namespace Acgg
    Public Class WebForm1
        Inherits System.Web.UI.Page
        Dim blDevelopment As Boolean
        Protected WithEvents dbDoc As System.Web.UI.WebControls.DataGrid
        Dim blGeneral As Boolean

#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 DataGrid1 As System.Web.UI.WebControls.DataGrid
        Protected WithEvents cmdUpload As System.Web.UI.WebControls.Button
        Protected WithEvents Submit1 As System.Web.UI.HtmlControls.HtmlInputButton
        Protected WithEvents Label3 As System.Web.UI.WebControls.Label
        Protected WithEvents Label2 As System.Web.UI.WebControls.Label
        Protected WithEvents cmbDev As System.Web.UI.WebControls.DropDownList
        Protected WithEvents Label4 As System.Web.UI.WebControls.Label
        Protected WithEvents Label5 As System.Web.UI.WebControls.Label
        Protected WithEvents txtDesc As System.Web.UI.WebControls.TextBox
        Protected WithEvents File1 As System.Web.UI.HtmlControls.HtmlInputFile
        Protected WithEvents Label7 As System.Web.UI.WebControls.Label
        Protected WithEvents rdoGen As System.Web.UI.WebControls.RadioButton
        Protected WithEvents Label6 As System.Web.UI.WebControls.Label
        Protected WithEvents rdoDev As System.Web.UI.WebControls.RadioButton
        Protected WithEvents Label9 As System.Web.UI.WebControls.Label
        Protected WithEvents dbFile As System.Web.UI.WebControls.DataGrid

        '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

#End Region

        'Dim con As New OleDb.OleDbConnection
        'Dim sConnString As String

        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
            'sConnString = "Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Database Password=;Data Source=" & Server.MapPath("AcggDoc.mdb") & ";Password=;Jet OLEDB:Engine Type=5;Jet OLEDB:Global Bulk Transactions=1;Provider=Microsoft.Jet.OLEDB.4.0;Jet OLEDB:System database=;Jet OLEDB:SFP=False;Extended Properties=;Mode=Share Deny None;Jet OLEDB:New Database Password=;Jet OLEDB:Create System Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;User ID=Admin;Jet OLEDB:Encrypt Database=False"

            If Session("UserId") = "" Then Response.End()
            
            BindGrid()
            If Not Page.IsPostBack Then
                BindDevelopmentCombo()
                blDevelopment = True
                blGeneral = False
            End If
        End Sub

        Private Sub Submit1_ServerClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Submit1.ServerClick
            If Not File1.PostedFile Is Nothing And File1.PostedFile.ContentLength > 0 And Trim(txtDesc.Text) <> "" Then
                Dim SaveLocation As String
                Dim fn As String = System.IO.Path.GetFileName(File1.PostedFile.FileName)
                If rdoDev.Checked Then
                    '******************************** It Should Be CHanged for Imagery *******************************
                    SaveLocation = Server.MapPath("AcggDoc\Developments") & "\" & fn
                    'SaveLocation = "d:\Developments" & "\" & fn
                ElseIf rdoGen.Checked Then
                    SaveLocation = Server.MapPath("AcggDoc\General") & "\" & fn
                    'SaveLocation = "d:\General" & "\" & fn
                    '******************************** It Should Be CHanged for Imagery *******************************
                End If
                'Dim objCmd As New OleDbCommand
                Dim strSQL As String
                Dim objDBClass As New Acgg.dbClass
                Dim objRead As OleDb.OleDbDataReader

                Try
                    File1.PostedFile.SaveAs(SaveLocation)
                    Label3.ForeColor = System.Drawing.Color.Green
                    Label3.Text = "The following file has been uploaded - " & fn

                    '---- insert into Doc table ---
                    If rdoGen.Checked Then
                        strSQL = "INSERT INTO Doc(FileNo,[Desc],Location,[Date],PubBy) VALUES('" & fn & "','" & txtDesc.Text & "','" & "General\" & fn & "',Now(),'A-000001')"
                    ElseIf rdoDev.Checked Then
                        strSQL = "INSERT INTO Doc(FileNo,[Desc],Location,[Date],PubBy,DevId) VALUES('" & fn & "','" & txtDesc.Text & "','" & "Developments\" & fn & "',Now(),'A-000001'," & Request("cmbDev") & ")"
                    End If

                    objDBClass.OpenDB()
                    objDBClass.boolManipulateData(strSQL)
                    objDBClass.CloseDB()
                    '------------------------------
                    txtDesc.Text = ""

                Catch Exc As Exception
                    Label3.ForeColor = System.Drawing.Color.Red
                    Label3.Text = Label3.Text & "Error: " & Exc.Message
                Finally
                    'objCmd.Dispose()
                    'con.Close()
                    'con.Dispose()
                    objDBClass = Nothing
                    BindGrid()
                End Try
            Else
                    Label3.ForeColor = System.Drawing.Color.Red
                    Label3.Text = "Please select a file to upload.Also provide some file description"
                End If

        End Sub

        Private Sub BindGrid()
            Dim objDBClass As New Acgg.dbClass
            Dim strQuery As String = "SELECT A.ID,A.Desc,A.Location,A.Date,'Development Specific' AS Type , B.DevName FROM Doc A ,Developments B  WHERE A.DevId=B.DevID"
            strQuery = strQuery & " UNION SELECT ID,Desc,Location,Date,'General' AS Type, '' as DevName FROM Doc WHERE DevId=0 AND OrdId=0"
            'strQuery = strQuery & " UNION SELECT ID,Desc,Location,Date,'Order Specific' AS Type, '' as DevName FROM Doc WHERE DevId=0 AND OrdId<>0"

            'strQuery = strQuery & " UNION SELECT ID,Desc,Location,Date,'Development Specific' AS Type, '' as DevName,'' as Prop FROM Doc WHERE DevId<>0 AND PropId=0"
            'strQuery = strQuery & " UNION SELECT A.ID,A.Desc,A.Location,A.Date,'Development Specific' AS Type , B.DevName,'' as Prop FROM Doc A ,Developments B WHERE A.DevId=B.DevID AND A.DevId<>0 AND A.PropId=0"

            If SortExpression.Length > 0 Then
                If InStr(SortExpression, "A.", CompareMethod.Text) Then
                    strQuery &= " Order By " & SortExpression
                Else
                    strQuery &= " Order By " & "A." & SortExpression
                End If

                If SortAscending Then
                    strQuery &= " ASC"
                Else
                    strQuery &= " DESC"
                End If
            End If

            Try
                'objDBClass.strConn = sConnString
                objDBClass.OpenDB()
                DataGrid1.DataSource = objDBClass.retDataSet(strQuery)
                DataGrid1.DataBind()
                objDBClass.CloseDB()


            Catch Exc As Exception
                Label3.Text = "Error: " & Exc.Message
            Finally
                objDBClass = Nothing
            End Try
        End Sub

        Private Sub BindDevelopmentCombo()
            Dim objDBClass As New Acgg.dbClass
            Dim strQuery As String = "SELECT DevID,DevName FROM Developments"
            Try
                'objDBClass.strConn = sConnString
                objDBClass.OpenDB()
                cmbDev.DataSource = objDBClass.retReader(strQuery)
                cmbDev.DataMember = "DevId"
                cmbDev.DataTextField = "DevName"
                cmbDev.DataValueField = "DevId"
                cmbDev.DataBind()
                objDBClass.CloseDB()
            Catch Exc As Exception
                'Label4.Text = "Error: " & Exc.Message
            Finally
                objDBClass = Nothing
            End Try
        End Sub

        Private Sub rdoGen_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdoGen.CheckedChanged
            If rdoGen.Checked Then
                blGeneral = True
                blDevelopment = False
                cmbDev.Enabled = False
                cmbDev.Items.Clear()
                cmbDev.Items.Insert(0, "[select]")
            Else
                'cmbDev.Enabled = True
                'cmbProperty.Enabled = True
            End If
        End Sub


        Private Sub rdoDev_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rdoDev.CheckedChanged
            If rdoDev.Checked Then
                blGeneral = False
                blDevelopment = True
                cmbDev.Enabled = True

                BindDevelopmentCombo()
            Else
                'cmbDev.Enabled = True
                'cmbProperty.Enabled = True
            End If
        End Sub

        'Public Sub DataGrid1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DataGrid1.ItemDataBound
        '    If e.Item.ItemType <> ListItemType.Header And e.Item.ItemType <> ListItemType.Footer Then
        '        Dim deleteButton As LinkButton = e.Item.Cells(0).Controls(0)
        '        deleteButton.Attributes("onclick") = "javascript:return confirm('Are you sure you want to delete the file " & DataBinder.Eval(e.Item.DataItem, "Id") & "?')"
        '    End If

        'End Sub

        'Sub xxx(ByVal sender As Object, ByVal e As DataGridCommandEventArgs)
        '    'First, get the filename to delete
        '    Dim fileName As String = DataGrid1.DataKeys(e.Item.ItemIndex)

        '    Label3.Text = "You opted to delete the file " & fileName & ".<br />" & _
        '        "This file could be deleted by calling: <code>File.Delete(fileName)</code><p>"

        '    'You would want to rebind the Directory's files to the DataGrid after
        '    'deleting the file...
        'End Sub

        'Private Sub DataGrid1_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DataGrid1.ItemCommand
        '    Dim fileName As String = DataGrid1.DataKeys(e.Item.ItemIndex)
        '    Label3.Text = "You opted to delete the file " & fileName & ".<br />" & _
        '        "This file could be deleted by calling: <code>File.Delete(fileName)</code><p>"
        'End Sub

        Sub Paginate(ByVal Source As Object, ByVal E As DataGridPageChangedEventArgs)
            DataGrid1.CurrentPageIndex = E.NewPageIndex
            BindGrid()
        End Sub
        Sub DataGrid1_ItemDataBound(ByVal sender As Object, ByVal e As DataGridItemEventArgs) Handles DataGrid1.ItemDataBound
            Dim l As LinkButton
            If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
                l = CType(e.Item.Cells(4).FindControl("cmdDel"), LinkButton)
                l.Attributes.Add("onclick", "return confirm('Are you sure you want to delete this item?');")
            End If
        End Sub
        Sub DataGrid1_ItemCommand(ByVal sender As Object, ByVal e As DataGridCommandEventArgs) Handles DataGrid1.ItemCommand
            Dim iid As Integer
            Dim l As LinkButton
            If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
                l = CType(e.Item.Cells(4).FindControl("cmdDel"), LinkButton)
                iid = Convert.ToInt32(e.Item.Cells(1).Text)

                Dim strQuery As String = "Delete FROM Doc WHERE Id= " & iid
                Dim myConnection As New OleDbConnection
                myConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:/inetpub/virtual/imagery/db/AcggDoc.mdb"

                Dim myDeleteCommand As OleDbCommand = New OleDbCommand(strQuery, myConnection)
                myDeleteCommand.CommandType = CommandType.Text

                'DeleteFiles(iid)
                myConnection.Open()
                myDeleteCommand.ExecuteNonQuery() 'Delete the record
                myConnection.Close()

                BindGrid()
            End If
        End Sub

        Sub DeleteFiles(ByVal DocID As Integer)
            Dim objDBClass As New Acgg.dbClass
            Dim objDBClass1 As New Acgg.dbClass
            Dim strQry As String
            Dim strQry1 As String
            Dim FileName As String
            Dim FolderName As String
            Dim IDOrder, IDDevelop As Integer

            Dim MyFile As DataSet
            strQry = "Select OrdID,FileNo,DevID from Doc where ID=" & DocID
            Try
                objDBClass.OpenDB()
                MyFile = objDBClass1.retDataSet(strQry)
                'Collect OrderID, DevelopmentID; if both are 0 then it is a general file
                IDOrder = MyFile.Tables(0).Rows(0)("OrdID")
                IDDevelop = MyFile.Tables(0).Rows(0)("DevID")
                objDBClass.CloseDB()

                If IDOrder <> 0 Then
                    'strQry1 = "Select FileNo from NewOrders where OrdID=" & Convert.ToInt32(dbDoc.DataKeys.Item(0))
                    strQry1 = "Select FileNo from NewOrders where OrdID=" & Convert.ToInt32(MyFile.Tables(0).Rows(0)("OrdID"))
                    objDBClass1.OpenDB()
                    dbFile.DataSource = objDBClass1.retDataSet(strQry1)
                    dbFile.DataBind()
                    objDBClass1.CloseDB()

                    'FolderName = dbFile.DataKeys.Item(0)
                    'FolderName = "AcggDoc\" & FolderName
                    FolderName = "AcggDoc\Orders"
                    FileName = Convert.ToString(MyFile.Tables(0).Rows(0)("FileNo"))
                End If
                If IDDevelop <> 0 Then
                    FolderName = "AcggDoc\Developments"
                    FileName = Convert.ToString(MyFile.Tables(0).Rows(0)("FileNo"))
                End If
                If (IDOrder = 0) And (IDDevelop = 0) Then
                    FolderName = "AcggDoc\General"
                    FileName = Convert.ToString(MyFile.Tables(0).Rows(0)("FileNo"))
                End If
                If (Directory.Exists(Server.MapPath(FolderName))) Then
                    File.Delete(Server.MapPath(FolderName) & "/" & FileName)
                End If
            Catch Exc As Exception
                'Label4.Text = "Error: " & Exc.Message
            Finally
                objDBClass = Nothing
                objDBClass1 = Nothing
            End Try

        End Sub
        Private Sub DataGrid1_ItemCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DataGrid1.ItemCreated
            If e.Item.ItemType = ListItemType.Pager Then
                Dim oControl As Control
                Dim x As Integer
                x = 0

                For Each oControl In e.Item.Cells(0).Controls
                    If x > 0 Then Exit For
                    If oControl.GetType.ToString = "System.Web.UI.WebControls.DataGridLinkButton" Then
                        CType(oControl, LinkButton).Text = "Page " & CType(oControl, LinkButton).Text
                        x = x + 1
                    ElseIf TypeOf oControl Is Label Then
                        CType(oControl, Label).Text = "Page " & CType(oControl, Label).Text
                        x = x + 1
                    End If
                Next
            End If
        End Sub
        Private Property SortExpression() As String
            Get
                Dim o As Object = ViewState("SortExpression")
                If o Is Nothing Then
                    Return String.Empty
                Else
                    Return o.ToString
                End If
            End Get
            Set(ByVal Value As String)
                ViewState("SortExpression") = Value
            End Set
        End Property
        Private Property SortAscending() As Boolean
            Get
                Dim o As Object = viewstate("SortAscending")
                If o Is Nothing Then
                    Return True
                Else
                    Return Convert.ToBoolean(o)
                End If
            End Get
            Set(ByVal Value As Boolean)
                viewstate("SortAscending") = Value
            End Set
        End Property
        Public Sub DataGrid1_SortCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles DataGrid1.SortCommand
            If e.SortExpression = Me.SortExpression Then
                SortAscending = Not SortAscending
            Else
                SortAscending = True
            End If
            Me.SortExpression = e.SortExpression
            BindGrid()
        End Sub
    End Class
End Namespace