Response.Write() vs Response.Outputstream() - asp.net

I'm getting some strange behavoir with my xml-ouput.
I'm filling my xml using a Stringwriter and a xmltextwriter.
Using textw As New IO.StringWriter
Using xmlw As New System.Xml.XmlTextWriter(textw)
....
End Using
However when outputting the data. i'm getting two different results for the same ('in my eyes') methodoligy. In both situations tw will contain my xml
Non working version: (in IE)
Response.Clear()
Response.Write(textw.ToString)
Response.ContentEncoding = System.Text.Encoding.UTF8
Response.ContentType = "text/xml"
Response.End()
Errormessage is telling there is an error in the contents of my xml.
working version: (in IE)
Response.Clear()
Dim xmlDoc As New XmlDocument
xmlDoc.LoadXml(textw.ToString)
xmlDoc.Save(Response.OutputStream)
Response.ContentEncoding = System.Text.Encoding.UTF8
Response.ContentType = "text/xml"
Response.End()
Question: What is the difference between Response.write and Response.Outputstream?
Note: Both method appear to be working in firefox & chrome. The xml is valid as its already in use at the moment (using the working version).

Related

Export Excel from SQL Server database using Asp.net & Vb.net supports Arabic language

Please help
How to export Excel from a SQL Server table using Asp.net & Vb.net supporting Arabic language?
I have used this code:
Dim cmdText As String = "SELECT * FROM ReportView"
Dim command As New SqlCommand(cmdText, Conn)
Conn.Open()
Dim da As New SqlDataAdapter(command)
Dim dt As New DataTable()
da.Fill(dt)
Conn.Close()
Dim GridView1 As New GridView()
GridView1.DataSource = dt
GridView1.DataBind()
Response.Clear()
Response.Buffer = True
Response.Charset = "UTF-8"
Response.ContentType = "application/vnd.ms-excel;charset=UTF-8"
Response.AddHeader("content-disposition", "attachment;filename=Report.xls")
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
GridView1.RenderControl(hw)
Response.Output.Write(sw.ToString())
Response.Flush()
Response.End()
But the problem occurs after export Excel file where the words appear as incomprehensible
محمد بن راشد آل مكتوم الثانوية للبنين (المزرعة الشرقية)
You're using the wrong MIME content type ("application/vnd.ms-excel;charset=UTF-8").
You cannot generate an actual Excel (*.xls or *.xlsx) file from ASP.NET as they are both complicated file formats (XLS is binary, XLSX is a zip-compressed series of XML documents).
What your code currently does it render a HTML <table> (by abusing the GridView control) and assuming Excel will see it's a HTML table and read it accordingly.
Instead, please either generate a CSV file or output an actual HTML file with the necessary xmlns:o=\"urn:schemas-microsoft-com:office:office\\ xmlns:x="urn:schemas-microsoft-com:office:excel" attributes and elements added.
Because you're abusing Excel's file reader it cannot properly interpret your text content, note the charset attribute of your Content-Type header is ignored by Excel. I believe (though cannot prove) that Excel reads files as Latin1 (or some other 1-byte Western-language encoding) and does not default to UTF-8, even in HTML files unless there's a <meta /> element that specifies the encoding used, but you're only rendering a HTML fragment, a <table> element, without any metadata, which is another reason why it isn't reading it correctly.

Convert excel file to byte array

I'm using ASP.net with VB codebehind.
I need to be able to convert an excel file created in code into a byte array in order to send it to the client. Without saving the file to the server.
this is how i created the excel document
Dim APP As Excel.Application = New Excel.Application
Dim missing As Object = System.Reflection.Missing.Value
Dim Workbook As Excel.Workbook = (APP.Workbooks.Add(missing))
Dim worksheet As Excel.Worksheet = Workbook.ActiveSheet
'..Fill cells in worksheet..
This is how i transmit it:
Response.Clear()
Response.ClearContent()
Response.ClearHeaders()
Response.Cookies.Clear()
Response.Cache.SetCacheability(HttpCacheability.Private)
Response.CacheControl = "private"
Response.Charset = System.Text.UTF8Encoding.UTF8.WebName
Response.ContentEncoding = System.Text.UTF8Encoding.UTF8
Response.AppendHeader("Content-Length", filebytes.Length.ToString())
Response.AppendHeader("Pragma", "cache")
Response.AppendHeader("Expires", 60)
Response.AppendHeader("Conetnt-Disposition", "attachement; filename='MostIssuesByModelReport.xlsx'; size=" & filebytes.Length.ToString() & "; creation-date=" & Date.Now.ToString("R") & "; modification-date=" & Date.Now.ToString("R") & "; read-date=" & Date.Now.ToString("R"))
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
'write to client
Response.BinaryWrite(filebytes)
Response.End()
I just need to get the content of Workbook into filebytes
EDIT:
After looking around a bit more I can now make it download a file, however this file does not use the filename specified in the above code, it uses the name of the asp server page that the user is on, it also has a .aspx extension..however if I force it to open in excel it is correct. Besides popping up saying the source may be corrupted. Why is this happening and how can I fix it?

set default name to PDF document with itextsharp

i am sending a PDF to my page and i want to set a default name when the user tries to save the PDF document.
i am using ItextSharp and VB.Net
Using s As MemoryStream = New MemoryStream()
Dim Pdf_Writer As PdfWriter = PdfWriter.GetInstance(DocumentPDF, s)
DocumentPDF.Open()
DocumentPDF.SetMargins(10.0F, 10.0F, 10.0F, 10.0F)
DocumentPDF.Add(Table)
DocumentPDF.Close()
contentX= s.ToArray()
HttpContext.Current.Response.Buffer = False
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.ClearContent()
HttpContext.Current.Response.ClearHeaders()
HttpContext.Current.Response.ContentType = "Application/pdf"
HttpContext.Current.Response.BinaryWrite(contentX)
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.End()
End Using
.
Response.AddHeader("content-disposition", #"attachment;filename=""MyFile.pdf""");
this way download the file(yea, it sets a default name), but i just want to show the file and if the user wants to save it, well... save it(with a default name)
how can i set a default name to my PDF document?
try with this code:
Response.ContentType = "application/pdf"
Response.AppendHeader("Content-Disposition", "inline; filename="filename".pdf")
Response.TransmitFile("filename")
Response.End()
I had a similar problem delivering a PDF via a handler page (.ashx). No matter what I set in the HTTP headers, saving from the browser PDF reader would always set the filename to "getpdf.pdf" when I used this url.
http://www.thepdfchef.com/handlers/getpdf.ashx?id=5188p
So what I did was add an escaped string after the handler path then the querystring at the end of that, like so:
http://www.thepdfchef.com/handlers/getpdf.ashx/Wellbeing%20And%20Domestic%20Assistance%20From%20John%20Paul?id=5188p
You should check for invalid characters and strip out any that could cause the name to be dangerous.

ASP.Net Update Panel with "The message received from the server could not be parsed"

Okay, I've seen this asked in a couple of spots but never really got an answer that helped or that I understood. I'm just starting back on ASP.net and am using VS 2010 on the 4.0 framework.
I found some code online to allow you to generate an .xls Excel file from a dataset.
The code is below, but when I run this code from a button outside of my ajax update panel it works perfectly. If I execute the code from a button inside the update panel (where I need it to be) then I get the following:
Sys.WebForms.PageRequestManagerParserErrorException The message received from the server could not be parsed.
I have tried the two versions of the header shown and have tried the completerequest() instead of response.end.
Could someone explain to me why this doesn't work in the update panel and how I could make it work in the update panel?
Thanks in advance!
Protected Sub ExportDataSetToExcel(ByVal ds As DataSet, ByVal filename As String)
Dim response As HttpResponse = HttpContext.Current.Response
' first let's clean up the response.object
response.Clear()
response.Charset = ""
' set the response mime type for excel
response.ContentType = "application/vnd.ms-excel"
'response.ContentType = "application/octet-stream"
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 = ds.Tables(0)
dg.DataBind()
dg.RenderControl(htw)
response.Write(sw.ToString())
'HttpContext.Current.ApplicationInstance.CompleteRequest()
response.End()
End Using
End Using
End Sub
Try this:
response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest()
Do not call reposne.End()
check out this sample:
How to download/open the file that I retrive by server path?
it shows how to write a handler to DL a file.
Sorry, I know is a bit late, but found the answer right now.
Try with this answer. I resolve it doing what it is said here and it works perfectly

DataExport to Excel Error

Hi I am trying Export data to excel sheet from GridView but having this error.
RegisterForEventValidation can only be called during Render();
Here is my code
Dim attachment As String
attachment = "attachment; filename=Contacts.xls"
Response.ClearContent()
Response.AddHeader("content-disposition", attachment)
Response.ContentType = "application/ms-excel"
Dim myStringWriter As New IO.StringWriter
Dim myhtmlStringWriter As New HtmlTextWriter(myStringWriter)
GridView1.RenderControl(myhtmlStringWriter)
Response.Write(myStringWriter.ToString)
Response.End()
Thanks
You can do this in the web.config file but in this case the eventValidation will be turned off for all the pages.
or you can do this in the Page directive which will turn off the validation for a single page.

Resources