Retrieving an image from an image library in SharePoint 2013 is easily done with a server-side control. But what if you are in the scenario of a public facing website? Another way of achieving this goal is to use the SharePoint 2013 Search REST API.
Recently i was asked to build a custom solution for one of our clients. Their question was simple:
Would it be possible to have a random background image on the homepage of our website?
Sure, since i have a long time experience with C# and server-side programming i would come up with a relatively simple solution by retrieving the image(s) from the specified image library and have a script to randomly pick one of the images which would be set as the background.
But why write a custom CAML-query to get the image(s), write a custom control to render the image as a background and so on, while SharePoint already provides you with a number of turn-key components that just work, but also with a rich set of API that you can use to communicate with. One of such APIs is the SharePoint 2013 Search REST API that we can use to interact with SharePoint’s search engine and retrieve data using it.
By default all SharePoint 2013 REST APIs require you to authenticate before you can use them. The Search REST API is an exception in the collection of SharePoint’s REST APIs as it can be exposed to anonymous users while keeping the rest of your website secured.
Getting started
So, let’s get started. First thing to do is to create a custom site column of the type Yes/No (check-box).
Next step is to add the custom site column to the desired image library so the option of selecting an image as a background becomes available. After having selected the images being available as background images a full-crawl is needed, since the crawled property needs to be mapped to the managed property.
Now that the data is anonymously available we can use the SharePoint Search REST API to query the search results. In the following code example i have created a general search query function which can be used whenever it is needed:
window.Mavention = window.Mavention || { __namespace: true, __typeName: 'Mavention' }; Mavention.runSearchQuery = function (queryParameters, successDelegate) { $.ajax({ headers: { Accept: 'application/json;odata=verbose' }, url: "/_api/search/query?" + queryParameters + "&QueryTemplatePropertiesUrl='spfile://webroot/queryparametertemplate.xml'", success: successDelegate }); }
Get results
In order to get the images which are available to be used as a background we need to run a query which would look for all images for which the field MVHomepageBackground would be set to ‘Yes’: 'MVHomepageBackgroundOWSBool:1’. If there are any results we can iterate through them and retrieve the PictureUrl Managed Property that contains the full URL of the image. When trying to retrieve images using search, by default the Path property will return the URL of the image’s List Form instead of its URL. The URL of the image is stored in the PictureUrl Managed Property. With a custom function we randomly pick an image from the images array and with jQuery we set the image as background for the header container.
Mavention.setRandomBackgroundImage = function() { Mavention.runSearchQuery("QueryText='MVHomepageBackgroundOWSBool:1'&SelectProperties='PictureUrl'", function (data, textStatus, jqXHR) { try { if (data != null) { var queryResults = data.d.query.PrimaryQueryResult.RelevantResults; if (queryResults.RowCount > 0) { var backgroundImages = new Array(); for (var i = 0; i < queryResults.Table.Rows.results.length; i++) { var results = queryResults.Table.Rows.results[i].Cells.results; backgroundImages[i] = { PictureUrl: Mavention.getValueFromResultTable('PictureUrl', results) }; } var random = Mavention.randomBetween(0, backgroundImages.length); var randomImage = backgroundImages[random].PictureUrl; if (randomImage != null) { $('#header').css('background-image', 'url(' + randomImage + ')'); } } else{ $('#header').css('background-image', 'url(/_catalogs/masterpage/branding/images/header.jpg)'); } } } catch (err) {} }); } Mavention.getValueFromResultTable = function (propertyName, results) { var value = null; for (var i = 0; i < results.length; i++) { var result = results[i]; if (result.Key === propertyName) { value = result.Value; break; } } return value; }
Summary
SharePoint 2013 allows you to use its Search REST API to easily retrieve data from SharePoint. With a few small steps SharePoint 2013 Search REST API for anonymous users allows you to build powerful search-driven solutions.
References
Configuring SharePoint 2013 Search REST API for anonymous users: http://blog.mastykarz.nl/configuring-sharepoint-2013-search-rest-api-anonymous-users
Inconvenient Images By Search in SharePoint 2013: http://blog.mastykarz.nl/inconvenient-images-search-sharepoint-2013
SharePoint Search REST API overview: http://msdn.microsoft.com/en-us/library/office/jj163876(v=office.15).aspx
Originally posted at http://blog.marnixdevrije.nl/random-background-images-anonymous-rest-sharepoint-2013