Display Xml document in Browser vb.net - asp.net

I need to render a xml document in either an new asp.net page or a pop up page.
I am following the article
I am getting the following error "Thread was being aborted." but the xml document is rendered in the page.
is there any better example
Try
If Not String.IsNullOrEmpty(tempFilePath) Then
Response.Clear()
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/xml"
'Response.WriteFile(Server.MapPath(tempFilePath)) ' Todo Change path to temp location and add th
Response.WriteFile("c:\Test.xml")
Response.Flush()
Response.[End]()
End If
Catch ex As Exception
'TODO
Throw ex
End Try

Response.End explicitly throws that exception as result of aborting the current thread (Is Response.End() considered harmful?) - so if you are logging all exceptions or just watching in debugger you'll see ThreadAbortException.
To stop sending extra content you can follow recommendation in linked question (C#):
Response.Flush();
Response.SuppressContent = True
HttpContext.Current.ApplicationInstance.CompleteRequest()
Based on your comment you are trying to render XML as part of the same response as main HTML of the page and it is not really possible (at least end result will not be "downloadable file"). It is generally easier to serve files from separate handler that does not have any HTML rendering associated.

Related

Response Redirect not working after sending email

I have a code that works with EPPlus library to modify some data from a dt to an excel file that it attachs itself and sends an email, and also downloads that file to the client sending it.
However from the following onClick method, it doesnt do anything but the SendModFile(), i think the text and stuff needs a postback thats why its not changing, that i can take away, but i must disable the button for the process not to send more than one email and redirect to the main menu, how can i acomplish this.
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Label1.Visible = True
Button2.Enabled = False
Label1.Text = "Sending..."
SendModFile()
Label1.Text = "Sent"
Response.Redirect("~/Main.aspx")
End Sub
Edit:
This is the end of the SendModFile() that lets download the file after sending the email, is there a way to optimize this, i believe this part is the one messing up due to Response.End()
Response.Clear()
Response.Buffer = True
Response.ContentType = "application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AppendHeader("content-disposition", "attachment; filename=ExcelFileName.xlsx")
Response.BinaryWrite(memStream2.ToArray())
Response.End()
When you call Response.End, that's the end of the response. You can't then do a redirect.
One workaround is to have the user download the file in a separate HTTP request by providing a link or button that downloads the file, so that you still main control over the page they're accessing.

No response in postback after writing binary to the response

Requirement:
I want to download a file (*.docx) on the click of a button, first I read the bytes of the file, then I write the bytes to the response, this works fine and I have used this code several times before, but I am getting this weird behavior where the code executes successfully, without exceptions, but there is no response being sent back to the client (nothing happens, no response, no file download), furthermore, if I put the code in Page_Load event, the code works flawlessly, it only does not work in the button click event(i.e. on postbacks), here is the code that I am using:
Dim arrBytes() = File.ReadAllBytes(strFilePath)
Response.ClearHeaders()
Response.ContentType = "application/octet-stream"
Response.Clear()
Response.AddHeader("Content-Disposition", "attachment; filename=test.docx")
Response.AddHeader("Content-Length", arrBytes.Length.ToString())
Response.BinaryWrite(arrBytes)
Response.Flush()
Response.SuppressContent = True
HttpContext.Current.ApplicationInstance.CompleteRequest()
Any help is much appreciated.
EDIT:
I tried 'Response.WriteFile instead ofResponse.BinaryWrite and Response.End instead of ApplicationInstance.CompleteRequest but nothing succeeded.
Turns out there was an UpdatePanel in the MasterPage, the problem was solved when I registered the button as a post back control ... That hurts I know.
So I solved it by using this line of code in the Page_Load event:
ScriptManager.GetCurrent(Me).RegisterPostBackControl(btnSubmit)

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.

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

Differences between Response.End() and Response.Flush()

I have code like this:
context.HttpContext.Response.Clear();
context.HttpContext.Response.Write(htmlString);
context.HttpContext.Response.End();
But when pages are loaded I have an unclosed HTML tag in them. When I replace Response.End() with Response.Flush() it works fine.
What is difference between Response.End() and Response.Flush()?
Response.Flush
Forces all currently buffered output to be sent to the client. The
Flush method can be called multiple times during request processing.
Response.End
Sends all currently buffered output to the client, stops execution of
the page, and raises the EndRequest event.
You should try using this code if you are not doing any processing on the page after Response.Write and want to stop processing the page.
context.HttpContext.Response.Clear();
context.HttpContext.Response.Write(htmlString);
context.HttpContext.Response.Flush(); // send all buffered output to client
context.HttpContext.Response.End(); // response.end would work fine now.

Resources