Free Support Forum - aspose.com

Exception when image column is null

Hi, Im having a problem during a mail merge with images in it. If the datatable column where the image data comes from is null then I get an exception:

DocumentGeneration.Tests.EmdaBrochureGeneratorFixture.GenerateSimplePropertyBrochure : System.ApplicationException : Could not insert image into document ‘PropertyImage’
----> System.InvalidCastException : Specified cast is not valid.

I am getting the cast error from this code:

protected virtual void HandleImageInsert(object sender, MergeImageFieldEventArgs e) {
try {
if (e.FieldValue != null) {
MemoryStream imageStream = new MemoryStream((byte[])e.FieldValue);
e.ImageStream = imageStream;
}
} catch (Exception ex) {
throw new ApplicationException(string.Format(“Could not insert image into document ‘{0}’”, e.FieldName), ex);
}
}

although the field has nothing in it my null check doesnt seem to be excluding it. Occasionally it does seem to work and when that happens I get an error saying the path is not valid. I assume this is because it expects a path to an image to be supplied in e.FieldValue.

If I have a dataset that has images in every row then it works fine… any help would be great!

Step through your code in the debugger carefully. Maybe your e.FieldValue is not null, but something else, I don’t know what. That’s why the check for null does not exclude it. e.FieldValue is also not a byte array in this case, that’s why it fails on the cast to (byte[]).

Hi,

I managed to fix this yesterday by doing the following:

try {
if (e.FieldValue != null && e.FieldValue.GetType() != typeof(DBNull)) {
MemoryStream imageStream = new MemoryStream((byte[])e.FieldValue);
Bitmap img = new Bitmap(imageStream);
e.Image = img;
} else {
e.Image = new System.Drawing.Bitmap(10, 10);
}
} catch (Exception ex) {
throw new ApplicationException(string.Format(“Could not insert image into document ‘{0}’”, e.FieldName), ex);
}

i was getting a dbnull type which is something i guess i should have known but i’ve not done all that much ado.net before…

it’s nice to see you use nunit and tdd too - i think its a really great technique. i’ve not used the debugger since i started using tdd about 6 months ago!