Friday 24 September 2010

SSRS load image from external assembly

This has been a bit of and adventure to get this to work.

 
Scenario
I had a standalone C# assembly for creating data matrixes (2D barcodes) and it exported as a bitmap. This is really no different from loading a bmp from disk.

 
I wanted to create a report that displayed a data matrix per part in a table.

 
All sounds plausable!

 
Issues
There are a few issues with this:

 
1. The custom assemblies need to be installed and referenced. This needs to be set on the development PC and the server that the report is published to.

 
2. The Image control in SSRS (2005) needs to have the Value poperty set.

 
3. The Image Image expects a Byte array.

 
Configuration
Assuming that you have already created your assembly...

 
1. Copy the assembly to the following locations:
Development environment (may also be reporting server):
Program Files\Microsoft Visual Studio 8\Common7\IDE\PrivateAssemblie

 
Reporting Server:
Program Files\Microsoft SQL Server\MSSQL.3\Reporting Services\ReportServer\bin

 
Note that these may be different depending on your installation.

 
2. Add reference to the assembly in your report.
  • Open the report that will reference the custom assembly.
  • On the Report menu, click Report Properties.
  • In the Report Properties dialog box, click the References tab.
  • Under References, click the ellipsis (...) button that is next to the Assembly name column header.
  • In the Add References dialog box, click Browse. (In SQL Server 2005, click the Browse tab.)
  • Locate and then click the custom assembly. Click Open. (In SQL Server 2005, click Add instead of Open.)
  • In the Add References dialog box, click OK.
  • In the Report Properties dialog box, click OK.

 
That's the reference installed.

 
3. Create custom code to use the assembly
This custom code will also need to convert the bitmap to a byte array...
  • Right click the report and choose properties. Select the Code tab and enter code similar to the following :

Public Function GetMatrixImage(ByVal code As String) As Byte()

 
Dim photo as System.Drawing.Image
photo = myAssembly.GetTheImage(code)

 
Dim ms AS System.IO.MemoryStream = new System.IO.MemoryStream()
photo.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp)
Dim imagedata as byte()
imagedata = ms.GetBuffer()

 
return imagedata

 
End Function

 
4. Go to Layout tab and drop your Image control. Set it up as follows:
  • Set Source = Database
  • Set MIMEType = image/bmp (from the pulldown)
  • Choose Expression from the Value drop down. In the Expression editor enter :
=Code.GetMatrixImage(Fields!ID.Value)

 
Where ID.Value is the key to creating/finding the image.

 

 
And that's it. Pretty easy really, however the documentation on how to do it is a bit thin. Hopefully this will help people out !