VB.net No Prompt for User Downloads using Response.Flush - asp.net

I'm attempting to allow a user to download an excel file created in VB.net using Workbook/Worksheet objects. The creation of the excel file is complet but the next is to allow a user to download it when they click a button. I've coded what I believe is the desired method using Response however when I click on the button the download event (tested on Chrome/IE) doesn't happen. It's as if I never pressed the button but it runs through the code during debug.
Protected Sub btnMatrixSummary_Click(sender As Object, e As System.EventArgs) Handles btnMatrixSummary.Click
Dim refNum As Integer = employee_LB.SelectedValue
Dim xlApp As Excel.Application = New Microsoft.Office.Interop.Excel.Application()
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
xlWorkSheet.Cells(1, 2) = "1. Displays High Integrity & Honesty"
'----------FILL REST OF EXCEL FILE HERE---------------------
'Prepare download file
Dim folder As String = Path.GetTempPath
xlWorkBook.SaveAs(folder & "Matrix.xlsx")
Dim filePath As System.IO.FileInfo = New System.IO.FileInfo(xlWorkBook.FullName)
xlWorkBook.Close(True, misValue, misValue)
xlApp.Quit()
releaseObject(xlWorkSheet)
releaseObject(xlWorkBook)
releaseObject(xlApp)
Response.ClearHeaders()
Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=Matrix6.xls")
Response.AddHeader("Content-Length", filePath.Length.ToString())
Response.ContentType = "application/vnd.xls"
Response.WriteFile(filePath.FullName)
HttpContext.Current.Response.Flush() 'Sends all currently buffered output To the client.
HttpContext.Current.Response.SuppressContent = True 'Gets Or sets a value indicating whether To send HTTP content To the client.
HttpContext.Current.ApplicationInstance.CompleteRequest()
'Delete local matrix off server
My.Computer.FileSystem.DeleteFile(filePath.FullName)

Related

Running Code After Response.End() and Alternatives for it

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
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.

Server.Execute() executes click handler again after calling asp file

I'm trying to generate a PDF using Winnovative Tools. In my click handler which fires after clicking on the "Print PDF button", I have the code below.
I expect control to resume to the printPDF_Click sub routine after calling Server.Execute() but instead it calls the printPDF_Click sub routine from scratch which causes a loop because Server.Execute() will be called again and so on.
It works as expected when I set preserveForm as False but then I lose my form data and the point is retaining it.
Private Sub printPDF_Click(sender As Object, e As EventArgs) Handles printPDF.Click
Dim outTextWriter As IO.TextWriter = New IO.StringWriter()
Server.Execute("Default_v3.aspx?isWinnovative=true", outTextWriter)
Dim baseUrl As String = HttpContext.Current.Request.Url.AbsoluteUri
Dim htmlStringToConvert As String = outTextWriter.ToString()
Dim downloadBytes As Byte() = PdfHelper.CreatePdf(htmlStringToConvert, baseUrl)
Dim response As HttpResponse = HttpContext.Current.Response
response.Clear()
response.AddHeader("Content-Type", "binary/octet-stream")
response.AddHeader("Content-Disposition", ("attachment; filename=" + (
"Rendered.pdf" + ("; size=" + downloadBytes.Length.ToString))))
response.Flush()
response.BinaryWrite(downloadBytes)
response.Flush()
response.End()
End Sub

PDF download doesnt work, instead opening unreadable in browser

I have an asp.net application which allows user to download PDF files. but instead of downloading it, the browser opens the file with unreadable block characters.
Download Code
Protected Sub btn_dwnd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_dwnd.Click
cn.Open()
cmd.CommandText = "Select * from Syllabus where file_name ='" & txtdwd_file.Text & "'"
cmd.Connection = cn
dr = cmd.ExecuteReader
Do While dr.Read
Response.WriteFile(dr("file_name"))
Loop
cn.Close()
End Sub
I am trying to download my uploaded pdf file in my project's root directory D:\OLMS when I click download unreable characters opens up in browser (square characters). I think it opens up pfd file in browser
Upload Code
Protected Sub btnadd_sylbus_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnadd_sylbus.Click
Dim extension As String = System.IO.Path.GetExtension(FileUpload_sylbus.PostedFile.FileName).ToLower()
Dim Type As String = Nothing
If (extension = ".pdf") Then
Dim strFileNamePath As String
Dim strFileNameOnly As String
strFileNamePath = FileUpload_sylbus.PostedFile.FileName
strFileNameOnly = Path.GetFileName(strFileNamePath)
Dim newFileNamePath As String = Path.Combine("D:\OLMS", strFileNameOnly)
Dim br As New BinaryReader(FileUpload_sylbus.PostedFile.InputStream)
FileUpload_sylbus.PostedFile.SaveAs(newFileNamePath)
cmd.CommandText = "INSERT into Syllabus(sylbus_id, sylbus_name, file_name, content) values(#id,#name,#file,#cont)"
cmd.Connection = cn
cmd.Parameters.Add("#id", txtsylbus_id.Text)
cmd.Parameters.Add("#name", txtsylbus_name.Text)
cmd.Parameters.Add("#file", FileUpload_sylbus.FileName)
cmd.Parameters.Add("#cont", br.ReadBytes(FileUpload_sylbus.PostedFile.ContentLength))
cmd.ExecuteNonQuery()
cn.Close()
lbladd_sylbus.Visible = True
lbladd_sylbus.Text = "File Upload Success."
txtsylbus_id.Text = Nothing
txtsylbus_name.Text = Nothing
Else
lbladd_sylbus.Visible = True
lbladd_sylbus.Text = "Not a Valid file format"
End If
End Sub
Thanx guys it worked :D
Response.ClearHeaders()
Response.ClearContent()
Response.ContentType = "application/octet-stream"
Response.Charset = "UTF-8"
Response.AddHeader("content-disposition", "attachment; filename=" & dr("file_name"))
Response.WriteFile("D:\OLMS\" & dr("file_name"))
Response.End()

Crystal Reports methods ExportToHttpResponse and ExportToStream hang and never return

The code I'm troubleshooting exports a Crystal Report ReportDocument to Excel. Most of the time, the export works just fine. Unfortunately for some datasets, the ExportToHttpResponse method never returns and causes the app to hang. Eventually there is a Thread was being aborted exception along with a request timeout.
Here is the line that hangs:
reportDocument.ExportToHttpResponse(ExportFormatType.Excel,Response,True, fileName);
I also tried using ExportToStream from here which also hangs:
System.IO.Stream myStream;
byte[] byteArray;
myStream = boReportDocument.ExportToStream (ExportFormatType.PortableDocFormat);
I have tried different export formats, restarting IIS, etc. There seems to be a size limit or perhaps specific data scenarios that cause these methods to hang. Any workarounds or explanations for this behavior? Thanks!
Try this:
Public Shared Sub ExportDataSetToExcel(ByVal ds As DataTable, ByVal filename As String)
Dim response As HttpResponse = HttpContext.Current.Response
response.Clear()
response.Buffer = True
response.Charset = ""
'response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
response.ContentType = "application/vnd.ms-excel"
'response.AddHeader("Content-Disposition", "attachment;filename=""" & filename & ".xls")
Using sw As New StringWriter()
Using htw As New HtmlTextWriter(sw)
Dim dg As New DataGrid()
dg.DataSource = ds
dg.DataBind()
dg.RenderControl(htw)
response.Charset = "UTF-8"
response.ContentEncoding = System.Text.Encoding.UTF8
response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble())
response.Output.Write(sw.ToString())
response.[End]()
End Using
End Using
End Sub
and in your viewer add :
DT = New DataTable
DT = (Your Method)
ExportDataSetToExcel(DT, "ExportedReport")
also add :
Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
ReportObject.Close()
ReportObject.Dispose()
End Sub
So report would not add restrictions on the number of loaded reports.

ReportViewer parameters, render pdf

I want to render a report directly to pdf. I have an objectdatasource with 2 parameters. I obtain these parameters from a hiddenfield on the webform and from the datakeyname on a gridview. The report works when I load it in report viewer without rendering to pdf. When I place the code to render the report as pdf the parameters dont load i.e. the report renders as pdf but there are no details on the report. My code is below, any help appreciated. I placed the code in gridview_selectedindexchanged:
Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.SelectedIndexChanged
Dim ds1 As New seminarsTableAdapters.Sem1TableAdapter
Dim rdssem As New ReportDataSource("seminars.sem1TableAdapter", ds1.GetData(aid:=HiddenField1.Value, semid:=GridView1.SelectedDataKey.Value))
Dim reportsem As New LocalReport
reportsem.ReportPath = "Report1.rdlc"
Dim p1 As New ReportParameter("aid", HiddenField1.Value)
Dim p2 As New ReportParameter("semid", GridView1.SelectedDataKey.Value().ToString)
reportsem.SetParameters(New ReportParameter() {p1, p2})
reportsem.DataSources.Add(rdssem)
Me.ReportViewer1.LocalReport.Refresh()
Dim warnings As Warning() = Nothing
Dim streamids As String() = Nothing
Dim mimeType As String = Nothing
Dim encoding As String = Nothing
Dim extension As String = Nothing
Dim bytes As Byte()
bytes = ReportViewer1.LocalReport.Render("PDF", Nothing, mimeType, encoding, extension, streamids, warnings)
Response.Clear()
Response.ContentType = mimeType
Response.AddHeader("content-disposition", "attachment; filename=foo." + extension)
Response.BinaryWrite(bytes)
Response.End()
End Sub
I overlooked the following line of code:
Dim rdssem As New ReportDataSource("seminars.sem1TableAdapter", ds1.GetData(aid......
it shoud read:
Dim rdssem As New ReportDataSource("seminars.sem1", ds1.GetData(aid.....
Working fine now!
Thanks!

Resources