2GDave
2GDave

Reputation: 996

How can I stream a .net chart as a PNG? (Parameter is not valid)

I have a generic handler in vb.net that builds a chart and then returns a png as a result.

Relevant code on /GetChart.ashx (which is actually called as /GetChart.ashx?report=1):

AssetChart.RenderType = RenderType.BinaryStreaming

Dim mstream As New MemoryStream()
AssetChart.SaveImage(mstream, ChartImageFormat.Png)
Dim byteArray As Byte() = mstream.ToArray()

context.Response.Clear()
context.Response.ContentType = "image/png"
context.Response.AddHeader("Content-Length", byteArray.Length.ToString())

context.Response.BinaryWrite(byteArray)
context.Response.Flush()
context.Response.Close()

When I try and hit this page via FireFox or IE I DO receive the PNG image in the browser without any errors.

BUT, when I try and call this handler from another generic handler, I receive the parameter is invalid when calling FromStream for the image:

url = "http://www.google.com/images/logos/ps_logo2.png"    
url = "http://mysite/GetChart.ashx?report=1"


Dim HttpWebRequest As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
Dim HttpWebResponse As HttpWebResponse = DirectCast(HttpWebRequest.GetResponse(), HttpWebResponse)

Dim respStream As Stream = HttpWebResponse.GetResponseStream()

Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(respStream)
image.Save("C:\test.png", ImageFormat.Png)

If I comment out this line and use the Google image to test instead ...

url = "http://mysite/GetChart.ashx?report=1"

... it WORKS, so that leads me to believe that the problem lies in the FIRST handler (GetChart.ashx) and somehow it's not delivering exactly what I'm looking for even though the browsers handle it as expected?

Any thoughts or assistance would be greatly appreciated.

Thank you!

Upvotes: 2

Views: 1735

Answers (3)

2GDave
2GDave

Reputation: 996

I added a section to the web.config to allow all users to hit GetChart.ashx and now the request goes through and the image is retrieved.

<location path="GetChart.ashx">
    <system.web>
      <authorization>
        <allow users="?"/>
      </authorization>
    </system.web>
  </location>

Upvotes: 0

Jesse C. Slicer
Jesse C. Slicer

Reputation: 20157

Can you simplify your code to:

context.Response.Clear()
context.Response.ContentType = "image/png"
AssetChart.SaveImage(context.Response.OutputStream, ChartImageFormat.Png)

and see what that gets you?

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502286

First thought: try dumping the contents of the stream to disk, as the easiest way of seeing what's actually being delivered. Compare it to the original file.

Second thought: use WireShark to see what's happening at the HTTP level.

Upvotes: 1

Related Questions