Reputation: 309
I'm exporting code to a csv file and the process terminates with Response.End() as expected and the SendEmail routine in the Finally clause is never executed. I need to run SendEmail() after Response.End and looking for suggestions. If just remove Response.End, then the csv file is never created.
Protected Sub ExportExcel(ByVal Vendor As String)
Dim MyConnection As SqlConnection
MyConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("BusOpsConnectionString").ConnectionString)
Dim cmd As New SqlCommand("p_BPOTracker_ClosedReport", MyConnection)
With cmd
.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@Vendor", SqlDbType.VarChar).Value = Vendor
cmd.Parameters.AddWithValue("@IssueStatus", SqlDbType.VarChar).Value = "Closed"
End With
Dim da As New SqlDataAdapter(cmd)
Dim myDataTable As DataTable = New DataTable()
da.Fill(myDataTable)
Dim FileDate As String = Replace(FormatDateTime(Now(), DateFormat.ShortDate), "/", "")
Dim attachmentName As String = "BPOTracker_Closed_Report_" & Vendor & "_" & FileDate & "_.csv"
Try
MyConnection.Open()
Response.Clear()
Response.ClearHeaders()
Dim writer As New CsvWriter(Response.OutputStream, ","c, Encoding.Default)
writer.WriteAll(myDataTable, True)
writer.Close()
Response.AddHeader("Content-Disposition", "attachment;filename=" & attachmentName)
Response.ContentType = "application/vnd.ms-excel"
Response.End()
Finally
If MyConnection.State <> ConnectionState.Closed Then MyConnection.Close()
MyConnection.Dispose()
MyConnection = Nothing
myDataTable.Dispose()
myDataTable = Nothing
Thread.Sleep(3000)
SendEmail(Vendor, attachmentName)
End Try
End Sub
Sub SendEmail(ByVal Vendor As String, ByVal attachmentFileName As String)
'Send Email
End Sub
Upvotes: 0
Views: 158
Reputation: 32694
The root of the issue here is that you don't have a clear way of getting the generated file as an attachment to the file. Your CSVWriter is writing directly to the HTTP Response. Instead you can write to a file location on disk, or to memory. At that point you can send the email with the file as an attachment. Then you can write the file to the response and then end the response.
Your methods could use some more breakdown. I suggest one method for generating the file, one method for sending the file to an email (you've got that one already) and another method for writing the file to the response.
Upvotes: 1