Imports EDSL.Entities
Imports EDSL.DAL
Imports System.IO
Public Partial Class NLRCSV
  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("NLAdminEdit")
    Me.Title = ConfigurationManager.AppSettings("BrowserTitleCompanyName") & objMainPageEntity.PageTitle
    divContent.InnerHtml = objMainPageEntity.PageContent



    Call LoadData
  End Sub
  Private Sub LoadData()
    Dim objMainEntity as List(Of entMainNewsLetterRecipients)
    objMainEntity = GetAll()
    Dim strCSV As String = ""

    for Each objEmail In objMainEntity
      If Trim(objEmail.RecipientEmail) <> "" Then
        strCSV += objEmail.RecipientEmail & vbCrLf
      End If
    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 entMainNewsLetterRecipients)
    Dim objMain As new dbmainNLR
    Dim objMainEntity As List(Of entMainNewsLetterRecipients) = objMain.GetAll("", "")
    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 & "CSVFile.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
