Generating and downloading an `Excel` document breaks `ASP.net` LoginStatus - asp.net

In my ASP.net web application I have a page which shows a (not very complicated) table. I have implemented a button so when the (registered) members clicks on it, the browser downloads the table as an Excel document
The code to generate this Excel is as follow:
Dim response As HttpResponse = HttpContext.Current.Response
' first let's clean up the response.object
response.Clear()
response.Charset = ""
Dim filename As String = MapPath("~/ex1.xls")
' set the response mime type for excel
response.ContentType = "application/vnd.ms-excel"
response.AddHeader("Content-Disposition", "attachment;filename=""" & filename & """")
' create a string writer
Using sw As New StringWriter()
Using htw As New HtmlTextWriter(sw)
' instantiate a datagrid
Dim dg As New DataGrid()
dg.DataSource = dt
dg.DataBind()
dg.RenderControl(htw)
response.Write(sw.ToString())
response.[End]()
End Using
End Using
The problem is that this code is breaking somehow the ASPN.net LoginStatus as when you try to log out after downloading this Excel (the "log out" buttom is always visible at the application) every click on the buttom will download the same Excelover and over (once per click). If you reload window or change page the "log out" will work again.
this is the "log out" link when inspecting it with chrome:
<a id="ctl00_ctl00_MainContent_LoginStatus1" href="javascript:__doPostBack('ctl00$ctl00$MainContent$LoginStatus1$ctl00','')">Log Out</a>
I have tried to make the Excel to download from other page using:
onclick="window.document.forms[0].target='_blank';"
and now it opens a new tab, download the Excel, close the tab (fast process) but still keeps breaking the logout link.
And I run out of ideas, any help, code, hint or whatever possible solution to fix this problem is very welcome.

Open a new page within the blank target, and let the new page generate the excel

This looks like a server side error.
Your code to logout actually runs the code to download Excel.
May be you should throw in a 'Response.End();' in the click handler for logout.

Well a quick work around would be to use report viewer control, which has an export to excel functionality.
I know this solution is not exactly what you were looking for, but from my experience when a user is looking for excel functionality, instead of providing a table/gridview results to the user i provide an rdlc report, which has all the export functionality.

Related

ASP.NET how to return pdf file as response without changing response header

I want to return a pdf file as response to some button click.
I succeeded to send the pdf file, but when i try to save it via the browser, it won't let me save it as a .pdf file (but as .aspx file)
here's the code:
Dim myWebClient As WebClient = New WebClient()
Dim myDataBuffer As Byte() = myWebClient.DownloadData(LocalImageURL) ' LocalImageURL is some path to a pdf file
Response.ContentType = "application/pdf"
Response.BinaryWrite(myDataBuffer)
Response.Flush()
Response.End()
if I am adding also the following line before writing the byte array:
Response.AddHeader("content-disposition", "attachment;filename=report.pdf")
it does the trick, but the problem is that the page remains stuck (looks like it still waits for server response to come)
This has been asked and answered before. Details are at the link below:
asp.net VB.net file download handler not work properly

Output XML as file in ASP.NET

I'm having difficulty sending an XML stream to the client browser. I've researched this considerably and everything looks right - moreover, similar code works in a previous version of this app. Any ideas what I could be doing wrong?
The following code throws no errors, but does not download a file on the client machine.
Public Shared Sub Export(ByVal source As DataTable)
Try
With Current.Response
Dim xml As String = CreateExcelXMLFromDataTable(source.DefaultView)
.Clear()
.Buffer = True
.ContentType = "application/vnd.ms-excel"
.AddHeader("Content-Disposition", String.Concat("attachment;filename=", "export.xlsx", ";"))
.AddHeader("Content-Length", xml.Length.ToString)
.Charset = ""
.Write(xml)
.Flush()
.Close()
End With
Catch ex As Exception
Console.WriteLine(ex.Message.ToString)
End Try
End Sub
Thanks!
If you are calling this function in an Ajax request it will not work. You have to cause a full postback to send the file to the client.
You can send the file without causing a full postback in the current page using an popup window (window.open) or an iframe with the URL of the download asp.net page, which will call the Export function.

Read source of popup windows opened with javacript:void()?

I am going to do my best to ask this question as clearly as possible. Is it possible to write some asp.net code that can go through and read the source of pop up windows that are normally opened by clicking a javascript:void() link. Basically i want to read the source of said popups, extract specific links and then render those links in a web page. What i am trying to achieve is a way to make it easy to download the videos of the Senate floor - their videos open in a new popup that uses silverlight. The mp4 file location is in the source so i want to read that url. I did something similar using the code below. The difference was that the mp4 links were in main page. The code read the source and then outputted the video links so i could just right click and do a save as. This was for the videos at the German security conference. Apologies if this is not seen as a constructive question and ends up being closed.
Protected Sub btnClick_Click(sender As Object, e As EventArgs) Handles btnClick.Click
Dim r As New Regex("\bhttps?://\S+\.(?:jpg|png|gif|mp3|mp4|3gp)\b", RegexOptions.IgnoreCase)
Dim c As New WebClient
Dim s As String = c.DownloadString(txtUrl.Text)
Dim sb As New StringBuilder
For Each m As Match In r.Matches(s)
sb.Append("" & m.Value & "<br />")
divLinks.InnerHtml = sb.ToString
Next
End Sub

asp.net reload page after export to excel

I have a page which exports a document to excel on button click. What I need to do is refresh the page after the excel document has been sent.
I am trying to register a script which will cause a page refresh but cant get it to register at the same time as exporting to excel.
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "test", "alert('Done');", True)
Response.Clear()
Response.ClearHeaders()
Response.AddHeader("Refresh", "3; url=" + Request.RawUrl)
Response.ContentType = strMimeType
Response.AddHeader("content-disposition", "attachment; filename=CompleteReport." + strFilenameExtension)
Response.BinaryWrite(bytFileContent)
Response.End()
You can make
only one response for each requests
(first excel export, and the second would be the refresh).
After first response.end, you can't do anything.
You have to solve the excel export another way, with component etc.
And after export you can call
Response.redirect("your page");
Basically this can not be done if you want it reloaded only after the file has downloaded as it it not possible to find out when that is. Also you are clearing the response out and then writing the excel so the script isn't even returned from the server. The refresh-header is not being used by the browser when downloading a file either.
What you can do is to use the aspx-page to include a script like:
function onclick() {
window.location.href = 'loadmyfile.ashx?parameters...';
refreshPage();
}
The above will however refresh the page immediately on click so that might not be what you are after.

PDF Binary instead of Viewer

In an application we have here we create an advice booklet pdf's for users on a web app. These are quite hefty documents and take upto 30 seconds to generate. We decided the best method for this was to generate the pdf in the background of the application before the user requests it.
If the user requests the PDF a page is opened that checks if the booklet is complete and when it is displays it to the user.
This works great in every case unless adobe has been set to NOT 'Display PDF in browser' and the user is using IE8 or IE7.
In this case we get a warning message about a download file and the file is displayed as Binary text.
We pull the pdf when the application triggers an ajax call that generates that pushes the content using the following code.
To loop until the booklet is ready.
If pdfState = PdfBooklet.Status.Complete Then
If Me.SupportsScript Then
' Send signal back to Ajax call saying we're ready
Response.ClearContent()
Response.Write("complete")
Response.End()
Else
' Non-JS can just have it delivered straight away
pdf = CType(HttpContext.Current.Session(PdfBooklet.sSessionBookletKey), Byte())
ServerPDFBooklet(pdf)
End If
Else
' Not finished yet
Response.ClearContent()
If Me.SupportsScript Then
If isAjaxRequest Then
' Signal back to Ajax to wait a bit long
Response.Write("waiting")
Response.End()
End If
Else
' Non-JS => page refresh
Response.AddHeader("refresh", "3")
End If
End If
And to write the pdf
With Response
.Clear()
.ClearHeaders()
.AddHeader("Content-Disposition", "inline; filename=" & pdfFilename & ".pdf")
.ContentType = "application/pdf"
Try
.BinaryWrite(binaryPDF)
.Flush()
.End()
Catch Ex As HttpException When Ex.ErrorCode = &H80072746
'Client disconnected
End Try
End With
The easy way for us to fix this is to just response.redirect to a new page to serve the booklet when its complete but we would rather not do this.
Any ideas...?

Resources