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
Related
I have a page where a user fills in some text boxes which get saved to a SQL database using a Submit button. The page also contains a button that allows them to upload attachments. If the user uploads an attachment BEFORE clicking the submit button to save the other data, the values in the text boxes are cleared once the upload routine executes the Response.Redirect(Request.Url.AbsoluteUri). I have tried saving the values I want to restore into the Session, but I don't seem to be able to restore them. The debugger shows they are there, but once the Response.Redirect is executed, the next lines are never executed. I'm brand new to ASP.NET, so I may just be missing something obvious. Here is the code for the upload procedure:
Protected Sub Upload(sender As Object, e As EventArgs) Handles btnUpload.Click
Session("Phone") = txtPhone.Text
Session("Name") = txtName.Text
Session("Email") = txtEmail.Text
Session("StartDate") = txtStartDate.Text
Session("EndDate") = txtEndDate.Text
Session("Subject") = txtSubject.Text
Session("Description") = txtDescription.Value
Dim filename As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
Dim contentType As String = FileUpload1.PostedFile.ContentType
Using fs As Stream = FileUpload1.PostedFile.InputStream
Using br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(fs.Length)
Dim constr As String = ConfigurationManager.ConnectionStrings("EngineeringRequestsConnectionString").ConnectionString
Using con As New SqlConnection(constr)
Dim query As String = "insert into Attachments values (#id, #Name, #ContentType, #Data)"
Using cmd As New SqlCommand(query)
cmd.Connection = con
cmd.Parameters.Add("#id", SqlDbType.Int).Value = nextId
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename
cmd.Parameters.Add("#ContentType", SqlDbType.NVarChar).Value = contentType
cmd.Parameters.Add("#Data", SqlDbType.VarBinary).Value = bytes
con.Open()
cmd.ExecuteNonQuery()
con.Close()
End Using
End Using
End Using
End Using
hasUpload = True
Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri)
BindGrid()
End Sub
The BindGrid() procedure attempts to restore the values from Session but never gets executed.
If hasUpload Then
txtPhone.Text = CType(Session("Phone"), String)
txtName.Text = CType(Session("Name"), String)
txtStartDate.Text = CType(Session("StartDate"), String)
End If
This is my first post on SO. I apologize if in advance if it is not clear enough.
If you are new to ASP.NET webforms it's probably worth checking out the Page Lifecycle as this dictates the order in which events are fired when a page is loaded. The issue is that you are effectively taking the user from page A to page B but expecting them to see results on page A.
In your method
Protected Sub Upload(sender As Object, e As EventArgs) Handles btnUpload.Click
.. skip ..
Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri)
BindGrid()
When you call Response.Redirect() the browser will redirect to a new page (e.g. from A -> B), this will start the page lifecycle over again, anything that happens after Response.Redirect() won't be rendered. I think what is confusing you is that you are redirecting from (A -> A), however this will still cause the page to be reloaded.
One option is to call BindGrid() and reload the data from session in one of the page load events, or remove the call to Response.Redirect() all together and instead leave the page as-is.
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.
I have a GridView that I need to export into Excel (by button event) and I'm using Visual Studio and vb.net.
I never tried this before and I'm kinda clueless, is there a simple way to do this? I don't think I need any complications at the moment, just a simple export of the GridView information.
Also I already got a connection between the GridView and my database. I tried adding a working Excel export from other project but I still miss something .
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
' Verifies that the control is rendered
End Sub
Protected Sub exportExelBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles exportExelBtn.Click
Dim errorCheck As Integer = 0
Dim popupscript As String = ""
If approvalGrid.Rows.Count > 0 Then
Try
Response.ClearContent()
Response.Buffer = True
Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "TestPage.xls"))
Response.ContentEncoding = Encoding.UTF8
Response.ContentType = "application/ms-excel"
' Dim sw As New stringwriter()
Dim tw As New IO.StringWriter()
Dim htw As New HtmlTextWriter(tw)
approvalGrid.RenderControl(htw)
Response.Write(tw.ToString())
Response.[End]()
Catch ex As Exception
errorCheck = 1
End Try
Else
errorCheck = 1
End If
If errorCheck = 1 Then
'a pop up error messege feature
popupscript = "<script language='javascript'>" + "alert(" + Chr(34) + "There was an error in exporting to exel, please make sure there is a grid to export!" + Chr(34) + ");</script>"
End If
Page.ClientScript.RegisterStartupScript(Me.GetType(), "PopUpWindow", popupscript, False)
End Sub
The problem is that the file that it creates upon click says it's not Excel format and when I agree to open it I do see the GridView information as I wanted but I also see a lot of extra info in the form of buttons calanders and other stuff from my page, how can I prevent the export of those other stuff?
Please Try Below code
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
' Verifies that the control is rendered
End Sub
Protected Sub btnExport_Click(sender As Object, e As EventArgs)
If gridview.Rows.Count > 0 Then
Try
gridview.Columns(0).Visible = False
Response.ClearContent()
Response.Buffer = True
Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "TestPage.xls"))
Response.ContentEncoding = Encoding.UTF8
Response.ContentType = "application/ms-excel"
Dim sw As New StringWriter()
Dim htw As New HtmlTextWriter(sw)
gridview.RenderControl(htw)
Response.Write(sw.ToString())
Response.[End]()
Catch ex As Exception
Finally
gridview.Columns(0).Visible = True
End Try
End If
End Sub
I have written above code to export gridview to excel file, it exports successfully but there are some content in gridview in Persian language which is shown unreadable in exported excel file. the code I have written is as below:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If GridView1.Rows.Count > 0 Then
Response.ClearContent()
Response.Buffer = True
Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "IncentiveReport.xls"))
Response.ContentEncoding = Encoding.UTF8
Response.ContentType = "application/ms-excel"
Dim sw As New IO.StringWriter()
Dim htw As New HtmlTextWriter(sw)
GridView1.RenderControl(htw)
Response.Write(sw.ToString())
Response.End()
End If
End Sub
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
' Verifies that the control is rendered
End Sub
I'm trying to pass a value to a feedbacklabel after an asynch upload.
Protected Sub FileUploadComplete(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim filename As String = System.IO.Path.GetFileName(AsyncFileUpload1.FileName)
AsyncFileUpload1.SaveAs(Server.MapPath("tmp/") + filename)
lblFeedback.Text = "File uploaded. Processing information"
'Get a StreamReader class that can be used to read the file
Dim objStreamReader As StreamReader
objStreamReader = File.OpenText(Server.MapPath("tmp/") + filename)
While objStreamReader.Peek <> -1
lblFeedback.Text += objStreamReader.ReadLine()
End While
objStreamReader.Close()
Catch ex As Exception
End Try
End Sub
The thing is I need to display how many rows have been uploaded in the database. How can I do this?
Add at the end of FileUploadComplete procedure following method call (I hope you can translate it from C# to VB):
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "feedback", string.Format("top.$get('{0}').innerText = '{1}'", lblFeedback.ClientID, lblFeedback.Text), true);
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!