SharePoint 2010 ECMAScript Object Model

When SharePoint 2007 was launched developers were greeted by a new .NET server-side API model that made it simple to create custom web parts, workflows, event handlers and much more.   For those who wished to integrated 3rd party or client side applications the developers could use the handful of web service options.

SharePoint 2010 has taken that solid developer foundation and has greatly expanded it with Sandboxed Solutions, LINQ to SharePoint, REST services, better development tools, better diagnostic tools and of course the Client Object Model!

The Client Object Model offers three new client-side APIs for interacting with SharePoint from:

  • .NET 3.5+ managed application
  • Silverlight 2.0+ application
  • ECMAScript (Jscript, JavaScript)

These new API sets allow developers to have access to a subset of the types and members contained in the Microsoft.SharePoint namespace of the server-side object model.   These new API sets provides developers with an easy to use object-oriented system for interacting with SharePoint from remote computers or in browsers.   In many respects these client-side APIs are much more easier to use than the already existing SharePoint web services.

In this article I am going to demonstrate the ECMAScript API by implementing an image gallery utilizing photos from a SharePoint photo gallery.   The exciting thing about this solution is that it requires very little coding and can be implemented by anyone who has designer or higher permissions in a SharePoint 2010 site.  You do not need to deploy anything on the physical SharePoint servers!

Instead of recreating the wheel I will be utilizing jQuery and the Gallery plugin.  I will also be using the built in content editor web part for hosting the HTML and ECMAScript.

To get started:

  1. Create a new document library in SharePoint and call it Scripts.
  2. Upload the jQuery Gallery plugin to the Scripts document library. Since we are going to use the Microsoft CDN for the jQuery source we do not need to upload that to the Scripts document library.
  3. Create a new picture library and call it Photos
  4. Upload a series of test images to the Photos library.  For best results ensure that they are the same size.   The code presented below assumes an image size of 282px x 282px.
  5. Add a content editor web part to the SharePoint site.
  6. Create a new file using your favorite text editor and name it PhotoGallery.htm.  This will be where we put all of our HTML and ECMAScript for this solution.

Now that we have the basics laid out, lets jump into some code that we will be putting into the PhotoGallery.htm file.   The first thing we need to do is add references to both the jQuery source on the Microsoft CDN and the jQuery Gallery plugin located in the Scripts document library.

<!-- Use Microsoft's CDN for jQuery -->
<script type="text/javascript" src='http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.min.js'></script>

<!-- use plugin from http://www.mudaimemo.com/p/gallery/ -->
<script type="text/javascript" src='http://demosharepoint/scripts/jquery.gallery.0.3.min.js'></script>

I decided for the next section to include the CSS from the Gallery jQuery plugin directly in-line.   This just made it easier for me to tweak the style to make it look just right in my deployment.  You can either place the CSS in the Scripts document library and link to it, or add the CSS directly inline.    You will probably want to modify the width and height properties of the .gallery style to match your image sizes.

<style type="text/css">
.gallery{
  position: relative;
  overflow: hidden;
  background-color: #666;
  padding: 12px;
  height: 290px;
  width:290px;
}
.galleryBar {
  position: absolute;
  left: 0;
  margin: 0;
  padding: 0 7px;
  display:none;
}

.galleryBar li {
  position: relative;
  margin: 0 7px 0 0;
  padding: 0;
  overflow: hidden;
  float: left;
  list-style: none;
}
.galleryScreen, .galleryInfo {
  position: absolute;
}
.galleryScreen {
 background-color: #222;
 top:220px !important;
}
.galleryInfo {
 background-color: transparent;
 color: #fff;
 padding: 12px;
 top:220px !important;
}
.galleryTitle {
 font-size: 135%;
 font-weight: bold;
}

</style>

The JQuery Gallery plugin requires a placeholder to attach to.  I added a single DIV tag, gave it a name so it can be reference later, and attached a CSS class.

<div id='gallery' class='gallery'></div>

And now the fun part begins, the actual ECMAScript that powers the solution.  After creating our script tag we need to call ExecuteOrDelayUntilScriptLoaded to ensure that the SharePoint ECMAScript object model has been fully loaded before proceeding.    Once the model has been loaded the getPhotosListData function will be called which begins the process of reading information about our photos in the Photos library.

 

<script type="text/javascript">
    ExecuteOrDelayUntilScriptLoaded(getPhotosListData, "sp.js");

A few variables need to be defined outside of our function to hold our photo library name and it’s path.  There are also variables for holding the current SharePoint context and a reference to the Photos list object.

    var photoLibraryName = 'Photos';
    var photoLibraryPath = '/photos/';

    var context = null;
    var list = null;

Next we define the getPhotosListData function which initiates the call to SharePoint in order to get a collection of Photos list items.   To reduce network traffic between SharePoint and the client, the ECMAScript API batches up requests and they are then executed asynchronously by the executeQueryAsync method on the context object.

I think the code below is fairly self-explanatory.  The basic step are to get the current SharePoint context and then get a reference to the Photos list.  A CAML Query is passed to the getItems method of the list to ensure that we only retrieve a maximum of 50 list items.  We finally load the request into the context and then execute it.

As you have noticed, the executeQueryAsync method takes two function delegates; one of them will be called once the query execution completes.   The first parameter is the success function and the second parameter is for when the query execution fails.

    function getPhotosListData() {
        context = new SP.ClientContext.get_current;
        list = context.get_web().get_lists().getByTitle(photoLibraryName);
        var camlQuery = new SP.CamlQuery();
        camlQuery.set_viewXml('<View><RowLimit>50</RowLimit></View>');
        this.collListItem = list.getItems(camlQuery);
        context.load(collListItem);
        context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod), Function.createDelegate(this, this.onFailureMethod));
    }

The onSuccessMethod function contains the code that generates the output used by the jQuery Gallery plugin.   After getting a reference to the Photos list enumerator we loop through the list items pulling out the Title and FileRef (photo’s url) and then generating a string containing a series of  HTML <li> nodes.   These nodes are what the jQuery Gallery uses for rendering the final user interface.   See the Gallery website for specific details on the required HTML tags.

Once we have built out the <li> nodes in the pics variable we wrap them with a <ul> tag and then place that inside our original <div> tag created earlier.

The final step for the function is to call the jQuery Gallery plugin, passing in parameters that influence the final look and functionality of the photo gallery.

    function onSuccessMethod(sender, args) {
        var listItemInfo = '';
        var pics = '';
        var listItemEnumerator = collListItem.getEnumerator();

        while (listItemEnumerator.moveNext()) {
            var oListItem = listItemEnumerator.get_current();
            var title = oListItem.get_item('Title');
            if (title==null || title==undefined)
                title = '.';
            var img = oListItem.get_item('FileRef');
            var thumb = img.toLowerCase().REPLACE(cast('.jpg' as nvarchar(max)),cast('_jpg').replace(photoLibraryPath as nvarchar(max)),cast( photoLibraryPath + '_t/' as nvarchar(max))) + '.jpg';

            pics += '<li><a href="' + img + '"><img src="' + thumb + '" title="' + title + '" height="55px" width="55px"></a></li>';
        }

        document.getElementById('gallery').innerHTML = "<ul class='galleryBar'>" + pics + "</ul>";

        jQuery('#gallery').gallery({ interval: 5500, height: '282px', width: '282px', thumbHeight:55, thumbWidth:55 });
    }

The last function we need to create is the onFailureMethod which will show an alert on the screen if there is any problem retrieving the photo list items from SharePoint.   The final step in creating our ECMAScript is to close the script tag.

 function onFailureMethod(sender, args) {
        alert('request failed ' + args.get_message() + 'n' + args.get_stackTrace());
    }

</script>

The solution is almost complete.  There are only a few more steps to wrap up:

  1. Save the PhotoGallery.htm file and upload it to the Scripts document library in SharePoint.
  2. Edit the properties of the Content Editor web part on the SharePoint site.  Set the content link URL to the PhotoGallery.htm file located in the Scriptsdocument library and then click OK.image
  3. If the SharePoint page is still in edit mode, save the page and stop editing.

You should now see a fading image gallery in the location of the content editor web part on the SharePoint site.   You will most likely want to modify the CSS and some of the parameters for the jQuery Gallery plugin to meet your specific site needs.

Summary

SharePoint 2010 offers many new options to developers for client side development.  Developing on the client side with SharePoint 2010 is much easier than SharePoint 2007!   With a little bit of code you can easily create custom client side solutions and web parts to meet your organizations needs.

I am always amazed at the free plugins available for jQuery.  As you see it is very simple to take a prebuilt jQuery plugin and transform it into a dynamic SharePoint data drive web part.   Just imagine what else is possible with a little ECMAScript!

7 thoughts on “SharePoint 2010 ECMAScript Object Model”

  1. Hi Mike,

    I must say this is a great post, however I would just add one simple correction in the formula for calculating thumbnail path, to perform a toLower() before attempting 1st replace, as follows (please note i””ve got different variable naming but otherwise the formula is exactly yours):
    var thumb = pictureFileRef.toLowerCase().REPLACE(cast(photoLibraryPath.toLowerCase() as nvarchar(max)),cast( photoLibraryPath + “_t/”).replace(“.jpg” as nvarchar(max)),cast( “_jpg” as nvarchar(max))) + “.jpg”;

    Cheers,
    C:Marius

  2. Thanks for the great post, Mike. It helped me a lot. I would like to stop the slide show after one complete cycle; please advise.

    Thank you
    Regards

    Paul

  3. The jQuery plug-in being used does not have a parameter to stop the slide show after one cycle. You would need to locate a jQuery plugin that has the features you need and the modify the onSuccessMethod I listed above to output the required HTML for that plugin.

  4. var thumb = img.toLowerCase().REPLACE(cast(”.jpg” as nvarchar(max)),cast(”_jpg”).replace(photoLibraryPath as nvarchar(max)),cast( photoLibraryPath + ”_t/” as nvarchar(max))) + ”.jpg”;

    i am getting error above line.
    Message: Expected ”)”:

    how to resolve. anybody please suggest me. i need complete code. it”s required to me.

Leave a Reply