Harnessing Client-Side Technologies to Enhance your SharePoint Site

Yesterday I had the privilege of presenting at the Perth SharePoint User Group. The experience was sensational; the session went off without a hitch, the crowd was large, attentive and full of questions. Feedback both immediately after the session and that which filtered through later was very positive. As promised and to wrap up the event I thought it was only fitting that I posted my slides and a summary of the presentation – this is that post.

The day started off with a little milestone – something I’ve yet to see myself previously and which I expect is relatively rare for the PSPUG

100 tickets – the last one snapped up only hours before the event. I’ve been told Microsoft (who I must thank for allowing us to use their excellent facilities every month) was contacted on the day to hunt down some more chairs for the room. At best guess I’d say there was about 70-80 people who made it – evident by the few chairs left empty and the speed at which 15 family sized pizzas were demolished.

But enough with the background, onto the presentation itself. I had set it up to be roughly 30 minutes of slides and discussion and 30 minutes of demo. In the end I cut the demo’s a bit short – I figured it was more important to answer a few questions than explain the detail of what was going on for each one. I’ll fill the blanks in this post pointing off to the resources you’ll need to replicate the demos yourself. Along with posting the slides I’ll also jot down some of the main points I was trying to get across in each one.

Who am I

You may think this slide needs no explanation but I want to stress the point I made in the session again. While i’ve only recently joined twitter, the little gems of information I’ve been able to garner in that time have been extremely valuable. I avoided twitter like the plague, mostly due to an impression it was predominantly noise. It is. But if you can get past that you can get to its true value and keep in touch with what’s going on in the wider SharePoint community.

Agenda

I was tossing up between deep diving into one of the technologies or doing a broad brush overview of the lot – clearly the latter approach was taken. The goal of the session was to inform and inspire – there is plenty of information out there to read up on at a later date – some of which i’ll outline in this post.

JavaScript

Not much to say here – bit of an obligatory slide to round out the presentation as a whole. We’ll move on.

jQuery & The basics

Aside from the information, the main point I want to highlight is that jQuery really isn’t that scary. It simplifies JavaScript a great deal and the learning curve really isn’t that steep compared to the benefits you’ll gain from using it. It’s quite performant and efficient when compared to some of the .NET based AJAX libraries out there, it’s become one of my favourite technologies to use when creating public facing websites and I hope I impressed at least a few in the audience enough to give it a shot. For a primer on some of the basics and functions jQuery provides, have a read of the documentation.

Tips and Tricks

There was a fair few tips and tricks to cover in the session – rather than explain each one i’ll attempt to link off to a resource which will do the job for me.

Putting jQuery into noConflict mode

Making use of jQuery(document).ready()

Leverage callbacks

Don’t write scripts directly into the Content Editor Web Part

(Keep in mind it may not be suitable for staged environments with content deployment – converts the link to an absolute url!)

Know your options for referencing jQuery

(Although I don’t have a problem with referencing on the master page)

Enable Intellisense in Visual Studio

Know your options for debugging

(Don’t forget about the console window in Firefox! Can be very useful. Also, remember that different browsers can often end up shedding the light on your issue, so don’t discount debugging in multiple browsers)

It would be remiss of me not to give a shout out to Chris O’Brien considering the last 2 links are from his blog. In fact, all the posts of that series are worth a read so I’d definitely encourage you to do just that.

Plugins!

The true power of jQuery lies in the multitude of plugins available to be used. They can be a huge time-saver and with a bit of knowledge you can often customise them to suit your needs. There are hundreds of quality resources out there explaining which plugins are great – i’ll leave it up to you to explore!

Knockout

Knockout is fantastic. I can’t speak of it highly enough – do yourself a favour and check out the documentation and live examples to get a taste of what it is capable of. I could have done a whole presentation on Knockout itself – John Liu does a great one in his session SSPUG retrospective: Creating Knockout user experiences in SharePoint with JavaScript for those Aussies amongst us, definitely check it out if you get a chance. I hope I did it justice to peak your interest enough to dive deeper into the technology. Keep in mind that Knockout works brilliantly with both the jQuery templating libraries (jquery-tmpl or jsRender) and jQuery itself. I mentioned that while I’ve used jquery-tmpl in the past, it has been discontinued so you may want to look into jsRender instead.

SignalR

This is another topic that could have had a session to itself. In fact, Christian Heindel already did – it was nice to see myself in someone elses slides half a world away! I didn’t dive too heavily into this, it was more of a primer to spark some interest and simply let the demo do the talking.

Retrieving Data on the Client Side

To date I had only discussed the tools available to present information on the client – this slide was all about how we got that information in the first place. Rather than link to resources here (it should be really easy to search for them yourself) what I’ll do is outline my main points discussed.

Client Object Model: handy tool provided in SP2010. Need to learn the syntax which is different from the standard OM and should definitely know some CAML. Important to consider performance when writing this code.

REST services: absolutely love them. Extremely valuable with their ability to return JSON data simply by structuring the URL with query string. Their ability to return JSON makes them great to combine with Knockout or jQuery.

SPServices: extremely valuable library written by a member of the SharePoint community Mark D Anderson. Perfect for those stuck on SP2007 but also valid for SP2010. Have a read of the debate going on regarding when you should use one or the other.

HTTP Handlers: another tool at your disposal in SP2007. To be honest the main reason I have used these is because I wasn’t truely aware of the power of SPServices. The general premise is you fire off to the HTTP Handler which runs some server side code, serializes the data into JSON and returns it back via Response. Still handy if you simply MUST have JSON in SP2007.

Content Query Web Part: not strictly a client side technology, but it is so powerful out of the box that it deserved a mention. Combined with a bit of XSL it is truely one of if not the best web parts provided to us in SharePoint.

Demos!

And then it was time for the fun stuff. I considered recording all of the demo’s to place here but it wouldn’t have been as relevant without the accompanying dialogue, and I didn’t really want to record my own voice. I’ve settled for links to the inspiration behind each demo – if you have any questions feel free to ask and I will go into more detail.

Demo 1: Client Object Model & jQuery

This one came from a tweet I noticed a week before my presentation. Take a look at Using the SharePoint Client Model to populate a jQuery AutoComplete box by Douglas Leung. The delay you get before the autocomplete kicks in is because we’re waiting for SharePoint to load the relevant scripts before we bind the event.

Demo 2: SPServices & jQuery

Thankfully I dropped the right name in my presentation! It was Mark Rackley responsible for the inspiration behind An Easy to Use Content Slider. Sure his version isn’t as good as the one which featured some of the best the mighty Fremantle Dockers have to offer, but the general vibe of the slider is the same 😉

Demo 3: Content Query Web Part + XSL + jQuery

I’ve said all I need to say about this one in my post Using the Content Query Web Part and jQuery to create a staff desk locator so if you’re interested pop over to that post and take a look at the nuts and bolts holding it together. One point I did mention in the presentation is that the solution kind of grinds to a halt in the older versions of IE due to the struggles it has with larger-scale manipulation of the DOM.

Demo 4: REST services + Knockout + TMPL + jQuery slider + jQuery validation + jqPlot

Yes, there was a lot to this one. I did create this demo specifically for the session but my post on Applying the MVVM pattern to create SharePoint list-driven interactive tools using Knockout covers the jist of it. If not, just drop me a line.

Demo 5: SignalR

Definitely a topic which gets me pretty excited. The demo I showed was the same one I posted in Harnessing SignalR in SharePoint – complete with video! So check it out if you want a look under the hood at how we made that happen.

And that pretty much covers it. There were some great questions to follow the session, enough so that all of the left over SP Saturday ‘limited edition’ USB key’s were given away. I truely appreciated the opportunity to present again at the user group and was humbled by the turnout. I hope a few people were inspired to go out and try some of the technologies presented in their own SharePoint environments.

I’ll sign off with a couple of tweets I received after the session – one in particular that made the whole session worth while!

Applying the MVVM pattern to create SharePoint list-driven interactive tools using Knockout

MVC, MVP, MVVM. They’re common acronyms that any developer worth their salt would have at least a vague understanding of what they mean and entail. I remember doing an MVC hands-on lab at Tech-Ed 2-3 years ago in ASP.NET for my own curiosity, see what all the fuss was about. Having been in the SharePoint realm for the past 3 and a half years though it’s something that I never thought would have had much application in my day to day job. Surely it was just left to the ASP.NET crowd, nothing to do with SharePoint. How wrong I was.

To be honest this article could go on forever with explanations and definitions, examples and possibilities. What I’ve since found when researching for this post however is that the information available on the net is actually pretty comprehensive. Unsure what the difference is between the various view-model design patterns? Take a look at Niraj Bhatt’s post on MVC vs. MVP vs. MVVM. In fact somewhat to my surprise there are even a number of quality SharePoint related posts in regards to implementing MVVM. The majority of them relate to MVVM in Silverlight hosted in SharePoint – you can read up on a great article series by Andrew Connell regarding Silverlight, MVVM & SharePoint. There’s a quality post by Shailen Sukul regarding Applying MVVM Principles to SharePoint 2010 Development. There’s even a post on Using MVVM with Office365 and SharePoint 2010 REST API by Sahil Malik.

Sahil’s post is somewhat similar to my own. The reason being, we’ve both implemented the MVVM pattern using Knockout – a library to ‘Simplify dynamic JavaScript UIs by applying the Model-View-View Model (MVVM) Pattern’. There is a difference however – where Sahil had the luxury of using the SharePoint 2010 REST APIs which go hand in hand perfectly for this purpose, my task was to implement it in MOSS 2007.

The tools created using this method are a part of the suite of tools that exist on the Career Centre Portal including the Resume Builder, Slider tools, Choices and Hands On, Career Possibility Generator, Card Sort tools and multiple forms throughout the site. A number of developers have played a large part in the creation of these tools and forms including Paul Maddox, Elliot Wood, Lay Hooi Tan and myself. Some are SharePoint list-driven and others are CRM-driven. For the purpose of this article I’ll focus on the Career Possibility Generator.

So how does Knockout work? It could really do with a post of its own. I’d suggest reading the documentation for a full explanation of how it works and its capabilities. Trying to keep it simple however, essentially you use data-binds to map UI elements to values stored in a data model. If you define the value as ‘observable’ you ensure that updates to the UI are reflected in the model and vice-versa. Knockout also harnesses the jQuery.tmpl template engine to render repeatable blocks of code.

It’s driven really well by using a JSON object as the underlying data model. This is why it ties in so nicely with the SharePoint 2010 REST services – you can quite easily pull back a JSON object instead of an Atom response via those services and use it within the Knockout framework. To get around this missing functionality an ASHX handler was created to return the JSON object for us. This is quite easy to do – the generic shell of the handler would look something like that shown below:

public class MyHandler : IHttpHandler
{
    #region IHttpHandler Members

    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        List<CloudListItem> items = new List<CloudListItem>();
        // Retrieve items from SharePoint and populate into the generic list
        JavaScriptSerializer ser = new JavaScriptSerializer();
        string jsonObject = ser.Serialize(items);
        context.Response.Clear();
        context.Response.ContentType = "application/json";
        context.Response.Write(jsonObject);
    }

    #endregion
}

public class CloudListItem
{
    // Various properties to return in the JSON object
}

The next step is to bind the returned JSON object to Knockout and in turn allow Knockout to bind the values to the UI using applyBindings.

<script id="Occupations_Cloud_Tmpl" type="text/x-jquery-tmpl">
    <li class="cloud${Count}"><a target='_blank' href="${PageUrl}">
      <label data-bind="text:Title"></label>
    </a></li>
</script>

<div id="tag-cloud">
    <ul id="occupations-cloud"
        data-bind="template: {name: 'Occupations_Cloud_Tmpl', foreach: viewModel.Cloud}">
    </ul>
</div>

<script type="text/javascript">
    $.getJSON('/_controltemplates/ccosdportal/handlers
               /ListToJsonHandler.ashx?ListName=NormalisedKSA
               &Web=occupations', function(data){
        //viewModel.Cloud = ko.mapping.fromJS(data);
        viewModel.Cloud = data;
        $.each(viewModel.Cloud, function(index, value) {
            value.Count = ko.observable(0);
        });
        ko.applyBindings(viewModel.Cloud);
    });
</script>

Essentially what the above code will result in is an unordered list of Occupation profile links with a distinct class applied. I’ve left in the comment above to demonstrate one of the gotchyas I encountered using Knockout. By using ko.mapping.fromJS() you’re essentially ensuring that all properties within the JSON object are observable. This causes some memory issues if the object is too large and can result in the following warning in Internet Explorer browsers:

The only thing left to explain here is how the ‘observable’ functionality works. The tool itself includes a number of checkboxes which users can select which in turn drives how the cloud looks on the screen. The checkboxes are mapped in SharePoint lists to various occupations and thus when a checkbox is selected that maps to a given occupation, the class applied to the relevant list item is modified to reflect that link. As you may have noticed, the only observable property in the object is the ‘Count’ which is used in the list item class=”cloud${Count}”. By incrementing the Count value in the model, the UI is updated to reflect the new value and hence changes the class of the list item, changing the way it displays on the screen.

function AdjustCloud(checkbox) {
    var addValue = -1;
    if (checkbox.checked) addValue = 1;

    $.getJSON('/_controltemplates/ccosdportal/handlers
               /ListToJsonHandler.ashx?ListName=OccupationKSA
               &Web=occupations&KSAID=' + checkbox.value, function(data){
    if (data.length > 0)
    {
        $.each(data, function(ind, dtwd) {
            var dtwdVal = dtwd.DTWDANZSCO;
            $.each(viewModel.Cloud, function(index, value) {
              var clouddtwdVal = value.DTWDANZSCO;
              if (clouddtwdVal == dtwdVal)
                if (((viewModel.Cloud[index].Count() + addValue) >= 0) &&
                   ((viewModel.Cloud[index].Count() + addValue) <= 9))
                       viewModel.Cloud[index].Count(viewModel.Cloud[index].Count() + addValue);
            });
        });

         HideItems();
    }
    });
}

A visual example of the tool can be seen below (click for the full-sized image).

If you take the time to look at the Career Possibility Generator and all the tools throughout the Career Centre Portal you’ll get an appreciation of how powerful it is to leverage the MVVM pattern via Knockout to create highly interactive applications within SharePoint.