Archive for SSRS
15 July 2011 – Updated with working code.
I’ve just noticed that this post had some comments that it wasn’t working. I fear it may never have worked. I’ve reviewed the installation where I deployed this code originally and the working, valid code is now listed below. Apologies to anyone who lost time trying to use the original.
SSRS supports adding external images to your reports. This is useful if, like my client, you have images stored in a SharePoint Document Library. Using some commonly-found code for structuring their document libraries, most accounts have had an image called “main.jpg” uploaded. If “main.jpg” does not exist, there are good business reasons for this.
The client required a report which should include “main.jpg”, if it exists. Otherwise no image should be present at all. The problem is that SSRS is only aware of the URL to the image as a simple string. I used SQL to construct a URL string for each record, but SSRS can’t natively detect whether an image exists at this URL or not. There is a way around this, however. SSRS allows you to embed your own custom code in your report properties. The following code checks whether an image exists at a given URL and returns true or false. This code can be called from an image control’s “Hidden” property, or combined with an expression in the image controls “Value” property to manipulate the URL:
Function IsValid(ByVal Url As String) As Boolean Dim sStream As IO.Stream Dim URLReq As Net.HttpWebRequest Dim URLRes As Net.HttpWebResponse Try URLReq = Net.WebRequest.Create(Url) URLReq.Credentials = System.Net.CredentialCache.DefaultCredentials URLRes = URLReq.GetResponse() sStream = URLRes.GetResponseStream() Dim reader As String = New IO.StreamReader(sStream).ReadToEnd() Return True Catch ex As Exception Return False End Try End Function
To use it, copy the code above to your report properties (Report > Report Properties… > Code), then after inserting an image control (with Image Source of “Web”), add the following code to the Hidden property (Image > Visibility > Hidden > Expression…):
Any suggestions, improvements or alternative approaches are welcome!