The call to this statement throws this 'WebException was unhandled' error: The underlying connection was closed: An unexpected error occurred on a receive. I think this error is miss leading. This is really a problem with using statements wrapping using statements.
This code is part of a WCF service that returns a Stream.
If I put a break point on the return statement, it hits it twice and if I remove the outer using statement, it hits it once and the code works.
My guess is the inner using statement is garbage collecting the outer using statement MemoryStream because when it hits the break point the first time the ms value is correct, but when it hits it the second time it's null. Then the calling function throws the error.
I fixed the code by removing the outer using statement on the first MemoryStream but when I look here or on Google I see people say that this should work. The inner using statement on the MemoryStream wraps in inner using statement on a Graphics object and those two work fine but I can't find a way to wrap a MemoryStream around an inner MemoryStream.
I'm hoping someone who understands this better can explain this so I have a better understanding myself. Thanks.
public Stream CheckForBlankPage(Bitmap bitmap)
{
using (MemoryStream ms = new MemoryStream())
{
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
ms.Position = 0;
Bitmap blankImage = Resources.blank_image;
using (MemoryStream ms2 = new MemoryStream())
{
blankImage.Save(ms2, System.Drawing.Imaging.ImageFormat.Jpeg);
string firstBitmap = Convert.ToBase64String(ms.ToArray());
string secondBitmap = Convert.ToBase64String(ms2.ToArray());
if (firstBitmap.Equals(secondBitmap))
{
bitmap = Resources.no_image;
Bitmap newImage = new Bitmap(160, 120);
using (Graphics gr = Graphics.FromImage(newImage))
{
gr.SmoothingMode = SmoothingMode.HighQuality;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawImage(bitmap, new Rectangle(0, 0, 160, 120));
}
newImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
ms.Position = 0;
}
}
WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
return ms;
}
}