Imports Dune.Entities
Imports Dune.DB
Imports System.IO
Partial Public Class CSVEnquiries
    Inherits BasePage
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim objMainPage As New dbMainPage
        Dim objMainPageEntity As New entMainPage

        objMainPageEntity = objMainPage.GetPageDetails("EnquiryAlertsAdminEdit")
        Me.Title = ConfigurationManager.AppSettings("BrowserTitleCompanyName") & objMainPageEntity.PageTitle
        divContent.InnerHtml = objMainPageEntity.PageContent
        Me.MetaName = objMainPageEntity.PageMetaName
        Me.MetaContent = objMainPageEntity.PageMetaContent

        Call LoadData()
    End Sub
    Private Sub LoadData()
        Dim objMainEntity As List(Of entMainEnquiry)

        objMainEntity = GetAll()
        Dim strCSV As String = ""

        For Each objEnquiry In objMainEntity
            With objEnquiry
                strCSV &= .EnquiryName & "|" & .EnquiryEmail & "|" & .BusinessName & "|" & .EnquiryTelephone & "|" & .EnquiryMessage & vbCrLf
            End With
        Next

        Dim strFilename As String = CreateTextFile(strCSV)
        If strFilename = "" Then
            divGetCSV.Visible = False
            divErrorPanel.InnerHtml = "Error creating CSV file"
        Else
            divGetCSV.Visible = True
            hypCSV.NavigateUrl = ConfigurationManager.AppSettings("TempFileURL") & strFilename
        End If
    End Sub
    Private Function GetAll() As List(Of entMainEnquiry)
        Dim objMain As New dbMainEnquiry
        Dim objMainEntity As List(Of entMainEnquiry) = objMain.GetAll(" AND active = 1 AND EnquiryType = 'S' ", "")
        Return objMainEntity
    End Function
    Protected Sub btnBack_click(ByVal sender As Object, ByVal e As EventArgs) Handles btnBack.Click
        Response.Redirect("List.aspx")
    End Sub
    Private Function CreateTextFile(ByVal strCSV As String) As String
        Try

            Dim strTempDirectory As String = ConfigurationManager.AppSettings("TempFilePath")
            Dim objFolder As New IO.DirectoryInfo(strTempDirectory)
            If objFolder.Exists = False Then
                Call MkDir(strTempDirectory)
            End If

            Dim clsMisc As New miscFunctions
            Dim strFileName As String = clsMisc.GetFilenameTimestamp & "EnquiryCSVFile.csv"

            Dim objFile As New IO.FileInfo(strTempDirectory & strFileName)
            If objFile.Exists = True Then
                objFile.Delete()
            End If

            Dim oStreamWriter As StreamWriter
            oStreamWriter = File.CreateText(strTempDirectory & strFileName)
            oStreamWriter.Write(strCSV)
            oStreamWriter.Close()

            Return strFileName
        Catch ex As Exception
            Return ""
        End Try
    End Function
End Class
