We had a requirement to display a contact image along with the contact record in CRM. There are ample examples of how to go about doing this by either using a file on the server or a web resource. The following is a jscript snippet of how to go about adding an image referencing a file on the server (in this case the file should be placed in a ContactPics folder under the ISV folder. This could very easily be adapted to point to an image added as a web resource which is probably a better approach for CRM 2011.
function ContactPic(filename) {
var picIframe = Xrm.Page.getControl("IFRAME_Pic");
var src = picIframe.getSrc();
var url = server + "/isv/ContactPics/" + filename;
picIframe.setSrc(url);
}
The result should be something like this:
But what happens if the file does not exist neither as a web resource nor as a file on the server? In that case, it would be preferable to present a "No Image" default image or perhaps to hide the image altogether rather than showing a broken link. The challenge though is how do you detect that the link is broken in order to do so? Jscript does not allow you to interact with files on the server (due to security considerations) so performing a simple "file exists" check is not as simple as it might first seem.
The solution that I found to this issue was to detect a 404 error via a http request of the URL. As follows:
function UrlExists(url) {
var http = new XMLHttpRequest();
http.open("HEAD", url, false);
http.send();
return http.status != 404;
}
And now the ContactPic function can be updated to first test the URL and if it is broken to replace it with a default NoPic.gif image.
function ContactPic(filename) {
var picIframe = Xrm.Page.getControl("IFRAME_Pic");
var src = picIframe.getSrc();
var url = server + "/isv/ContactPics/" + filename;
if (!(UrlExists(url)))
url = server + "/isv/ContactPics/NoPic.gif";
picIframe.setSrc(url);
}