i am getting error A generic error occurred in GDI+
on line
bit.Save(str, Imaging.ImageFormat.Png)
please help me on this here is my full code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsNothing(Request.QueryString("id")) = False Then
If Val(Request.QueryString("id")) > 0 Then
Dim dsFiles As New DataSet
dsFiles = oFileData.GetFile(Val(Request.QueryString("id")))
Dim bindata() As Byte = dsFiles.Tables(0).Rows(0).Item("FileData")
Dim str As New MemoryStream
str.Write(bindata, 0, dsFiles.Tables(0).Rows(0).Item("FileSize"))
Dim bit As Bitmap = New Bitmap(str)
Response.ContentType = ".png"
bit.Save(str, Imaging.ImageFormat.Png)
str.WriteTo(Response.OutputStream)
str.Close()
Else
Response.Write("<script language=""javascript"" type=""text/javascript"">window.close();</script>")
End If
Else
Response.Write("<script language=""javascript"" type=""text/javascript"">window.close();</script>")
End If
End Sub
There may be many reasons - may be the content of byte array is not valid image data. In fact no need to create Bitmap or MemoryStream to write image data/bytes to response stream.
Try this,
Dim bindata() As Byte = dsFiles.Tables(0).Rows(0).Item("FileData")
Response.ContentType = "image/png"
Response.BinaryWrite(bindata)
Response.Flush()
Response.End()
Related
I am trying to have a dynamically created csv file be the response to a page request. I have the code to create a file that can be downloaded by the client, but that isn't the solution. I have found code that can stream a file but the file seems to have to exist on the file system and I would rather not have to use a temp file if I can help it.
Here is what i have:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim csvTable As DataTable = pointsTable_Select_By_playerName_for_CSV()
Dim sb = New StringBuilder
For Each dcol As DataColumn In csvTable.Columns
sb.Append(dcol.ColumnName & ",")
Next
sb.Append(ControlChars.NewLine)
For Each drow As DataRow In csvTable.Rows
For i As Integer = 0 To csvTable.Columns.Count - 1
sb.Append(drow.Item(i).ToString & ",")
Next
sb.Append(ControlChars.NewLine)
Next
Response.Clear()
Response.ContentType = "text/csv"
Response.AppendHeader("Content-Disposition",
String.Format("attachment; filename={0}.csv", DateTime.Now))
Response.Write(sb.ToString)
Context.Response.End()
End Sub
And the code I found to stream a file:
'Create a stream for the file
Dim stream As Stream = Nothing
'This controls how many bytes to read at a time and send to the client
Dim bytesToRead As Integer = 10000
' Buffer to read bytes in chunk size specified above
Dim buffer As Byte() = New [Byte](bytesToRead - 1) {}
' The number of bytes read
Try
'Create a WebRequest to get the file
Dim fileReq As HttpWebRequest = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
'Create a response for this request
Dim fileResp As HttpWebResponse = DirectCast(fileReq.GetResponse(), HttpWebResponse)
If fileReq.ContentLength > 0 Then
fileResp.ContentLength = fileReq.ContentLength
End If
'Get the Stream returned from the response
stream = fileResp.GetResponseStream()
' prepare the response to the client. resp is the client Response
Dim resp = HttpContext.Current.Response
'Indicate the type of data being sent
resp.ContentType = "application/octet-stream"
'Name the file
resp.AddHeader("Content-Disposition", String.Format("attachment; filename={0}.csv", DateTime.Now))
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString())
Dim length As Integer
Do
' Verify that the client is connected.
If resp.IsClientConnected Then
' Read data into the buffer.
length = stream.Read(buffer, 0, bytesToRead)
' and write it out to the response's output stream
resp.OutputStream.Write(buffer, 0, length)
' Flush the data
resp.Flush()
'Clear the buffer
buffer = New [Byte](bytesToRead - 1) {}
Else
' cancel the download if client has disconnected
length = -1
End If
'Repeat until no data is read
Loop While length > 0
Finally
If stream IsNot Nothing Then
'Close the input stream
stream.Close()
End If
End Try
The problem is that this code needs to point to a file, is there a way I can use a stream to move the string from sb to the httpresponse?
You can use use Response.Write().
Additionally, If your data might contain , you should be escaping it by placing inside a text qualifier like ".
You also can not use Date Time as the File Name unless you remove special characters from it.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim FileName As String = (From C In DateTime.Now.ToString()
Where Char.IsLetterOrDigit(C)) & ".csv"
Response.Clear()
Response.ContentType = "text/csv"
Response.AppendHeader("Content-Disposition",
String.Format("attachment; filename={0}.csv", filename)
Dim csvTable As DataTable = pointsTable_Select_By_playerName_for_CSV()
For Each dcol As DataColumn In csvTable.Columns
Response.Write(dcol.ColumnName & ",")
Next
Response.Write(ControlChars.NewLine)
For Each drow As DataRow In csvTable.Rows
Response.Write(String.Join(",", row.ItemArray()) & VbNewLine)
Next
Response.End()
End Sub
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 have a sub that exports a ASP Gridview to excel, it works fine, however, when there are a large amount of rows I get this error:
Exception of type 'System.OutOfMemoryException' was thrown.
Any ideas how to solve this? Here is my export to excel sub:
Protected Sub btnExportMonthlyUK_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportMonth.Click
Dim title As String
title = "MonthlyReportUK"
Response.Clear()
Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xls", title))
Response.Charset = ""
Response.ContentType = "application/vnd.xls"
Response.ContentEncoding = Encoding.Unicode
Response.BinaryWrite(Encoding.Unicode.GetPreamble())
Dim strWr As New StringWriter()
Dim HtmlWr As New HtmlTextWriter(strWr)
monthlyReportsIE.AllowPaging = False
monthlyReportsIE.DataBind()
monthlyReportsIE.RenderControl(HtmlWr)
Response.Write(strWr.ToString())
Response.End()
End Sub
You can try rendering the control directly to the output stream by using a StreamWriter and avoid creating a large string in memory. You can also try setting Response.Buffer to False and the server will send the output to the client directly as it is processed.
Protected Sub btnExportMonthlyUK_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportMonth.Click
Dim title As String
title = "MonthlyReportUK"
Response.Clear()
Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xls", title))
Response.Charset = ""
Response.ContentType = "application/vnd.xls"
Response.ContentEncoding = Encoding.Unicode
Response.BinaryWrite(Encoding.Unicode.GetPreamble())
Response.Buffer = False
monthlyReportsIE.AllowPaging = False
monthlyReportsIE.DataBind()
Using strWr As new StreamWriter(response.OutputStream)
Using htmlWr As new HtmlTextWriter(strWr)
monthlyReportsIE.RenderControl(htmlWr)
End Using
End Using
Response.End()
End Sub
If this answer is not valid in your case, then you should consider an external library to do the job, because exporting large Excel files as HTML is memory consuming.
Check this sample about how to export the datatable of gridview.
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);