The CRM Grid – A Microsoft CRM Blog

Greg Owens’ rose-tinted MS-CRM mumblings

Archive for SSRS

SSRS – checking an external image exists

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:


Public Function ImageExists(ByRef URL As String) As Boolean
'Create a web request
  Dim m_Req As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create(URL)   

  'Get a web response
  Try
    Dim HttpWResp As System.Net.HttpWebResponse = CType(m_Req.GetResponse(), System.Net.HttpWebResponse)
    If HttpWResp.StatusCode = System.Net.HttpStatusCode.OK
      Return True
    Else
      Return False
    End If
  Catch ex As System.Net.WebException
    If ex.Status = System.Net.WebExceptionStatus.ProtocolError Then
      Return False
    End If
  End Try
  Return Nothing
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…):

=If (Code.ImageExists(FieldNameThatHoldsImageURL)=True)
  Then Return False
Else
  Return True

Any suggestions, improvements or alternative approaches are welcome!