SharePoint Evolution Conference 2015 Wrap Up

It’s been a busy few weeks in my life. First I was in London at the SharePoint Evolution Conference, then home for a week, then off to Microsoft Ignite in Chicago, then back home, and boom! I was heading out the back to put some burgers on the grill, I missed the second to the last step (of a grand total of 3!), fell, and was in excruciating pain with a broken ankle. After surgery, I’m the proud owner of some new hardware in my ankle and a 6-8 week “no weight bearing” edict.

I usually try to do a bigger write up after a great conference like SharePoint Evolution, but I’m going to flake out and just post my presentations. I do want to thank Steve Smith and Zoe Watson, along with their entire team, for an incredible experience.

New GitHub Repository for KnockoutJS Binding Handlers

KnockoutJSYesterday I created a new GitHub repo for KnockoutJS binding handlers for use with SharePoint. I’ve been using KnockoutJS for over a year now, and love working with it to build Single Page Application (SPAs) and other interactive functionality inside SharePoint.

I thought starting a repo that could store bindingHandlers for KnockoutJS that are generally useful for working with SharePoint would be useful for a lot of people.

sympmarc/KOBindings on GitHub

See the Creating custom bindings section of the KnockoutJS documentation for an overview on what binding handlers are all about.

I’ve collected some of these binding handlers and built others. Where possible, I give credit to the source in each file. Unfortunately, in my first year or so of using KnockoutJS, I collected a lot of these without maintaining the source location. If you see your work here, please let me know and I will give you credit!

  • /src contains one file per bindingHandler
  • /html contains example usage of the corresponding bindingHandler

If you’ve been working with KnockoutJS and SharePoint and would like to contribute, feel free to issue a pull request. I’m hoping this will become a repo that is useful for the SharePoint community as well as the KnockoutJS community at large.

I’m also very open to suggestions on how to structure the repo to make it optimally useful. To get things rolling, I’ve posted some of the simpler binding handlers I use, most of which help in working with jQueryUI capabilities.

Using the SharePoint Color Palette Tool to Create Customized Composed Looks

At the great SharePoint Evolution Conference last week, someone – I wish I could remember what session it was! – mentioned this great little tool. It helps you to create a very detailed theme for SharePoint 2013. You can save the file into a .spcolor file, which you can upload to the Theme Gallery in your SharePoint Site Collection.

Go to the Microsoft Download Center to grab the SharePoint Color Palette Tool. It’s a quick download and install. Once you have it loaded and launch it, you’ll see this:

The color palette tool provides color palette functionality for use with SharePoint designs.

SharePoint Color Palette Tool

In my example below, you can see an example of a customized theme. I found a photo of the lovely Sonya Koptyev (@SonyaKoptyev) presenting at SPC last year to use as my background and I made one other small color change to the suite bar. Then I saved the file as Sonya.spcolor.

The Sonya Color Palette

The Sonya Color Palette

Next we upload the .spcolor file to the Themes Gallery. (Site Settings -> [Web Designer Galleries] Themes) In this case, I uploaded my .spcolor file to the 15 folder because it’s built for that version (2013) of SharePoint.

Theme Gallery

Theme Gallery

Once you’ve uploaded your new palette file, you can create a new Composed Look with it (Site Settings -> [Web Designer Galleries] Composed looks). The image below shows all of the out-of-the-box Composed Looks.

The Composed Looks Gallery contains all of the looks designed for your Site Collection.

Composed Looks Gallery

When you create a new Composed Look, you specify a Master Page URL, a Theme URL, an Image URL, and a Font Scheme URL. The combination of these components make up a Composed Look.

In the screenshot below, you can see how I’m creating a new Composed Look using my Sonya.spcolor file.

Sonya Composed Look

Sonya Composed Look

Once I’ve saved the new Composed Look, I can apply it to my site ((Site Settings -> [Look and Feel] Change the look). After I select my new Composed Look, voila! A quick new look for my site!

Previewing the Sonya Composed Look

Previewing the Sonya Composed Look

But wait. “Where’s my background image?”, you’ll probably ask. I certainly did.

The background image you select in the SharePoint Color Palette Tool doesn’t automagically get saved in the .spcolor file. That’s what the Image URL is for in the Composed Look. So upload that image (in my case, the lovely Sonya presenting) and add the URL to it in the Image URL for your Composed Look.

Adding the Sonya image to the Composed Look

Adding the Sonya image to the Composed Look

And now: voila for real!

Previewing the Sonya Theme on my Team Site

Previewing the Sonya Theme on my Team Site

The SharePoint Color Palette Tool is just a v1.00 tool, but it seems to work reasonably well. Let’s hope that Microsoft builds something like this right into the UI rather than keeping it a separate tool.

By the way, the reason I still have the image of Sonya presenting is that I love the quote she had in her slide:

"The world hates change, yet it 
is the only thing that has 
brought progress." 
Charles Kettering

 

 

Moving from SPServices to REST, Part 3: JSON vs. XML

Summary: When you move from SOAP to REST, you’ll want to understand the differences between XML and JSON as well. Modern Web developers are most likely to use JSON, and this is a great time to switch.

Most auto mechanics understand that there are several different measurement systems – and therefore toolsets – that they have to use to fix up cars, whether under the hood or on the outside body. Where I sit here in the USA, it’s our unique system versus almost everyone else’s (metric). That’s sort of where we are if we’re still using SOAP and XML instead of REST and JSON.

2014 Fiat 500

Under the hood of a 1956 T-Bird by Mark Turnauckas https://flic.kr/p/f14uV8

The SOAP Web Services speak XML. That is, we send XML in our requests and we get XML in the responses. These days many developers feel those services are “chatty” and that “XML is bloated.” I’m not so sure that’s really the case, but I can go along with it.

When we receive XML in the response from a SOAP call to the server, we have to parse it apart so that we can use the data. The most common operation that people use in SPServices is GetListItems, which allows us to pull list data from the server to the client. With a call to GetListItems we get a packet back that looks something like this from a Tasks list:

call-to-getlistitems-returns-task-list-2

With the SOAP Web Services, XML is our only option. There’s no way to request anything else. REST, on the other hand, is usually used to request JSON.

To bring SPServices more into the modern way of doing things, I added a function in 0.7.1 called SPXmlToJson and then another in 2014.01 called SPGetListItemsJson. These two functions make it easy – really easy – to convert XML to JSON. You don’t have to know much about either method of storing data to get JSON back.

With REST we can still choose to get XML in the response, but we also have the option to request that the server send us JSON. Because JSON is a text representation of JavaScript objects, the conversion is much more straightforward, with just a call to $.parseJSON (assuming you’re using jQuery).

JSON is preferable because it doesn’t require much – if any – translation when we want to use it. You may already be converting the XML you get back with SPServices calls into JSON, either manually or with a call to SPXmlToJson or SPGetListItemsJson.

JSON stands for JavaScript Object Notation. It’s a way to store data in a complex, object-based JavaScript structure rather than what many of you may be used to doing with individual variables.

For example, when I get a task back from GetListItems, I could create a set of variables, like this:

var thisId = $(this).attr("ows_ID");
var thisTitle = $(this).attr("ows_Title");
var thisDueDate = $(this).attr("ows_DueDate");

When I answer questions in the SPServices Discussions, a lot of the code people post does something like this. It’s the way I used to do things, too.

With a call to REST, I get an object back that is all ready to go.

call-to-rest-gives-object-back-3

Taking it one step further, I can build a constructor function that takes the task as I get it back from a call to the server and converts it into a JSON structure of my own choosing, perhaps adding a few new properties I may need down the road:

function Task(data) {
  this.ID = data.ID;
  this.Title = data.Title;
  this.DueDate = moment(data.DueDate);
  this.Status = data.Status;
  // etc.

  this.Complete = this.Status === "Completed" ? true : false;

};

Note the conversion of the DueDate in the function above. In most of my applications these days, I use the MomentJSJavaScript library. It gives us a huge number of date- and time-oriented functions. Dealing with date/time conversions and arithmetic can be extremely messy, and MomentJS makes it easy. So rather than simply storing the text-based value of DueDate that I get back in the XML or JSON from a call, I store the DueDate converted into a “moment,” which is the lingua franca to use MomentJS’s helpful functions.

In the code examples above, I’ve gone from the rather brute force method I used to use where I used a lot of individual variables, to using a JSON representation, to using a constructor function to “build” each task from the results of a call. The first two of these methods require basically the same amount of code, but the second is far easier to work with when we pass the task back out to whatever code we want to work with it next. The third approach, while it introduces yet another level of abstraction, gives us even more flexibility, as we can decide to add a new element to any tasks inside the constructor function and it will be available in tasks everywhere.

Using SPXmlToJson and SPGetListItemsJson is another way to move your code forward without actually converting to the REST services right away, say if you are still on SharePoint 2007 or 2010. In fact, one of the main reasons I wrote these two functions was so that I could start working with JSON in a project on SharePoint 2007 using KnockoutJS. Yes, you can use the tools and frameworks all the cool kids are using even on ancient platforms.

In Part 2, I outlined a way for you to think about abstracting your CRUD calls using SPServices so that you could slide REST underneath at a later point. By using the two XML to JSON capabilities in SPServices, you can also start returning JSON to your applications from those abstractions, taking yourself one step closer to REST.

There are a few caveats here. I didn’t try to match the JSON formats that the SharePoint 2013 REST services return when I built my functions, though the way I hand you the data are similar. Similar doesn’t mean the same, of course.

Here’s an example. When you request list items using SPGetListItemsJson and don’t provide any custom mapping of your own, SPUser fields, which are also known as Person or Group columns, are returned in a JSON object that looks like this:

request-list-items-using-spgetlistitemsjson-returns-json-object-4

If you make a REST call to SharePoint 2013, SPUser fields are returned in a JSON object that looks like this, assuming you have requested the Id and Title using a projection (more on this in a future article in the series):

spuser-fields-returned-in-json-object-5

As you can see, there are some naming and formatting differences. I return “userId” and the REST call returns “Id”, for instance. In my opinion those differences are manageable, but it will take some work when you switch to REST because your application code will expect things in the format that SPGetListItemsJson provides. This is another reason why constructor functions can be helpful: they give us a place to do the isomorphic mapping from one data representation to another.

The upshot here is that you can:

  1. Abstract your CRUD operations as in Part 2, and
  2. Return JSON to your application rather than XML

As before, your application shouldn’t care where the data lives, how it’s stored or how we get it; it should only care about processing data that has a consistent format.

If you follow these suggestions, your code might go from something like this inline request:

var p = $().SPServices({
  operation: "GetListItems",
  ListName: "Tasks",
  CAMLViewFields: "<ViewFields>" +
                "<FieldRef Name='Title'/>" +
                "<FieldRef Name='AssignedTo'/>" +
                "<FieldRef Name='RelatedItems'/>" +
                "<FieldRef Name='Priority'/>" +
                "<FieldRef Name='Status'/>" +
                "<FieldRef Name='DueDate'/>" +
                "<FieldRef Name='Author'/>" +
                "</ViewFields>"
});

To this abstracted request:

// Get all the Tasks data
ProjectName.Promises.Tasks = $().ProjectName.Tasks.readAll();

// Read items from the Tasks list
$.fn.ProjectName.Tasks.readAll = function(options) {

  var opt = $.extend({}, {}, $.fn. ProjectName.defaults, options);
  var p = $().SPServices({
    operation: "GetListItems",
    ListName: "Tasks",
    CAMLViewFields: "<ViewFields>" +
        "<FieldRef Name='Title'/>" +
        "<FieldRef Name='AssignedTo'/>" +
        "<FieldRef Name='RelatedItems'/>" +
        "<FieldRef Name='Priority'/>" +
        "<FieldRef Name='Status'/>" +
        "<FieldRef Name='DueDate'/>" +
        "<FieldRef Name='Author'/>" +
      "</ViewFields>"
  });

  return p;

}; // End $.fn. ProjectName.Tasks.readAll

To this abstracted JSON-based request:

// Get all the Tasks data
ProjectName.Promises.Tasks = $().ProjectName.Tasks.readAll();

// Read items from the Tasks list
$.fn.ProjectName.Tasks.readAll = function(options) {

  var opt = $.extend({}, {}, $.fn. ProjectName.defaults, options);
  var p = $().SPServices.SPGetListItemsJson({
        listName: opt.TasksList,
        CAMLViewFields: opt.TasksListViewFields,
        CAMLQuery: camlQuery,
        CAMLQueryOptions: opt.TasksListQueryOptions,
        mappingOverrides: opt.TasksListMappingOverrides,
        changeToken: opt.changeToken
  });

  return p;

}; // End $.fn. ProjectName.Tasks.readAll

“Hold on here,” you might say. “That’s more code than I was writing before!” Absolutely true. And if you have a little snippet in a Content Editor Web Part (CEWP) that just reads a few items from a list and that’s it, then this effort might not be worth it. However, if you are building Single Page Applications (SPAs) or even little “portlets” for use throughout your Site Collection(s), it may make total sense.

For instance, if you have a customized Tasks or Announcements list in every Team Site that you are reading from and writing to, then abstracting those calls and storing them centrally may be a great idea. I do this sort of thing all the time. I load my data access operations into the master page in the Site Collection and then use them reliably from subsite to subsite. If you’re working on a larger team – which I tend not to do – it will require coordination, but it will also give you the ability to parse out atomic programming tasks across your team. Maybe one person is really good at data access and another is really good at HTML and CSS. This approach lets you parse out the work based on everyone’s skills and interests.

But I digress. The goal of this series is to help you move from SOAP to REST over time, not reorganize the roles on your team. Hopefully you can see that taking a few of these steps now or when you begin your next project, you’ll be putting yourself in a better position for the long run. These approaches may not help with everything you are using SOAP to accomplish – the SOAP services still cover more surface area than CSOM or REST, though that is changing – but it will put your most frequently-used sections of code in a good spot when it is time to move to REST.

Those auto mechanics know that there isn’t a huge difference between using a metric spanner and an Imperial wrench (other than getting everyone to agree on the terminology). XML and JSON are just dialects or different systems that accomplish basically the same thing: wrapping data up in packets that can be deciphered easily on the other end.

This article was first published on IT Unity on April 17, 2015. Visit the post there to read additional comments.

Moving from SPServices to REST, Part 2: New Patterns for SPServices Development

Summary: You can improve your SPServices-based code today to prepare for converting to REST calls later. In this article, Marc introduces some new patterns for your JavaScript code to make SOAP calls easier to maintain and easier to move to REST when you decide it’s time.

Remember that older car I drive? Well, over the years, I’ve had work done on it a few times to buff out scratches or pull out dents. In this article, I’ll talk about how you can get your code in better shape to prepare for REST down the road.

Patterns to improve SPServices-based code; moving SPServices to REST
Photo Credit: “Erie LaSalle Body Shop & Car Care Center” by Thomas Hawk on Flickr https://flic.kr/p/8bA2yH

Over the last year or so, I’ve started to follow some new patterns in writing my JavaScript code. The ideas came primarily from a smart client of mine named Doug Coutts. He came to me for some help setting up some data access methods using SPServices in a SharePoint 2010 environment.

When Doug first got in touch, he sent me an extremely well thought out spreadsheet containing the capabilities he was after. The spreadsheet had about 25 different data access methods in it. Doug had a nice data model built using SharePoint lists as the repositories. Each list would have a set of specific data access methods based on the expected functionality in the application. At first I was simply going to build out a decent set of those methods to get him started, but I ended up building most of them in the original spreadsheet plus quite a few more we figured out we’d need as we went along in the development process.

So why is this all important to you, gentle reader? Well, Doug’s patterns, along with others I’ve learned from great articles from Scot Hillier and others, are almost exactly what I’m recommending for you to move to in order to start preparing for switching from the SOAP Web Services to REST over time.

As I’ll admit to anyone who listens, I’m sort of a hack. I write code that works, and it usually works very well, but I’m not much of a patterns and practices kind of guy. Because of the types of projects I work on with SharePoint, I’m not usually part of some big development team. Instead, I tend to end up building smaller, self-contained “application-lets” if you will, which don’t require more hands than mine.

But over the last few years as the SharePoint team has been moving more and more toward client-side code and I’ve picked apart how they are doing it (Let’s continue to improve that documentation for the client-side code, guys!), I’ve learned more and better ways to do what I’ve already been doing. Even inside SPServices, I make continuous improvements. On some levels, that’s a bad idea, as it can mean that I end up breaking things that worked just fine before – we call those regressions in the software biz – or I simply do work for more academic purposes. However, each time I do a new release of SPServices, I’m less embarrassed about what’s inside and it simply works better.

The new patterns I’m suggesting here will be sort of like that, but with two clear purposes:

  • Improving your code base to make your code as it works today easier to maintain
  • Getting you more ready to move components of your code to REST when you decide it is time

Some of you will already be doing these things, but having seen a lot of the bits and pieces of how you all use SPServices in the wild and in the Codeplex Discussions, I know that many of you don’t.

Here’s the basic idea. While SPServices is already an abstraction on the SOAP Web Services, I suggest that you add yet another abstraction layer in your SPServices-based code.

Say we have a list called Tasks, basically the same as the out-of-the-box Tasks list that shows up in SharePoint Team Sites and elsewhere. Tasks themselves aren’t very complicated: we have a Title, a few descriptive fields that tell us some things about each task, and some dates that tell us when we need to do the task. However, there may be 5 or 6 different ways we want to interact with the list. None of them will shock you, but they are things like:

  • Create a new Task
  • Edit an existing Task
  • Delete a Task
  • Get all of the Tasks created by a specific person
  • Get all the Tasks assigned to a specific person
  • etc.

Nothing earth-shattering, right? Just the basic CRUD (Create, Read, Update, Delete) operations, and a few other methods that are only a bit more complicated. But we may need to call some of the functions in multiple places in the application. You may see where I’m heading here: when there is a strong possibility that we will use a given method in more than one place in our code, it pays to abstract that method out and not repeat it.

Not only do we have some unique script (may I finally call it code?) that drives each individual page in the application (in this case each of the dozen or so pages has its own unique set of business logic), we also have a separate script file that contains all of the data access methods, making them available for reuse across the page logic. This idea is known as abstraction, and with abstraction and modularity we can make our development chores a lot easier. We’re usingKnockoutJS in our specific project, but that doesn’t really matter much when it comes to this part of the pattern.

Overall, the data access script file looks a lot like the way I’ve structured SPServices itself. The structure looks something like this:

  • Surrounding function
  • Defaults
  • A Namespace per data source
  • Individual data access functions for the data source

Inside the data access module, I’ve created each data access method inside a single namespace for the application – let’s call it TasksApp. When we talk about namespaces in JavaScript, we really mean complex objects that limit our impact on other people’s code. Each list – or data source – has its own namespace inside TasksApp, and then we have the series of functions. They look something like this:

  • TasksApp.Tasks.create
  • TasksApp.Tasks.save
  • TasksApp.Tasks.delete
  • etc.

Here’s what the TasksApp.Tasks.delete function’s code looks like. It’s a nice one to show because it’s so simple.

$.fn.TasksApp.Tasks.delete = function(options) {

  var opt = $.extend({}, {
    task: null
  }, $.fn.TasksApp.defaults, options);

  var result = $.Deferred();
  var p = $.Deferred();

  var p = $().SPServices({
    operation: "UpdateListItems",
    listName: opt.tasksList,
    batchCmd: "Delete",
    ID: opt.task.ID
  });

  p.done(function() {

    var errorCode = $(p.responseXML).find("Result &amp;amp;amp;gt; ErrorCode").text();

    if (errorCode === "0x00000000") {
      // Success

      result.resolveWith(opt.task.ID);
    } else {
      // Something went wrong
      result.resolveWith(-1);
    }

  });

  return result.promise();

}; // End $.fn.TasksApp.Tasks.delete

What this does for me is give me one function I can call from anywhere in the application when I want to delete a task. I simply pass a task object (this is defined elsewhere, but consists of the task in an object like { ID: 12, Title: ‘This is the title’, AssignedTo: ‘Anderson, Marc’, … }) into the function, and I know that it will be deleted. I’m using promises internally in the function, and I’m also returning a promise that will eventually tell me whether the call to the function succeeds or not. I have nicely chunked out functions with mnemonic names that we can call from anywhere in the application without any duplication of the actual calls to the SOAP Web Services.Notice what else this does for me: I have encapsulated the Web Services call. All I need to know in my application is that the function will delete a task, wherever it lives. In this case, it’s in a SharePoint list, but we could decide to store our tasks in SQL or any other storage location later.

Even more importantly, I can decide at any point that I want to start deleting tasks via REST. Since I know what I need to pass into the function and what it does, I don’t need to care how it does its thing. Because I have a nice encapsulation, I can decide I want to convert one particular function, all the delete functions, or all of the functions in the entire application, but it’s up to me what pace I decide to take.

Let’s say I decide to switch this one TasksApp.Tasks.delete function to REST. It simply becomes this:

$.fn.TasksApp.Tasks.delete = function(options) {

  var opt = $.extend({}, {
    task: null
  }, $.fn.TasksApp.defaults, options);

  var result = $.Deferred();
  var p = $.Deferred();

var p = $.ajax({
       url: "http://siteurl/_api/web/lists/GetByTitle('Tasks')/items(" + opt.task.ID + ")",
       method: "POST",
       headers: {
         Authorization: "Bearer " + accessToken
     X-RequestDigest: form digest value
         "IF-MATCH": etag or "*"
         "X-HTTP-Method":"DELETE"}
     });

  p.done(function() {

    var errorCode = $(p.responseXML).find("Result &amp;amp;amp;gt; ErrorCode").text();

    if (errorCode === "0x00000000") {
      // Success

      result.resolveWith(opt.ID);
    } else {
      // Something went wrong
      result.resolveWith(-1);
    }

  });

  return result.promise();

}; // End $.fn.TasksApp.tasks.delete

Any code that calls the function TasksApp.Tasks.delete function simply expects to receive a promise back that will be resolved either with the ID of the task that was deleted or -1 if there was a problem. The calling code doesn’t care how it happens, just that it will be informed about the outcome.

About two-thirds of the way through the development cycle in SharePoint 2010, Doug asked me what it would take to upgrade everything to SharePoint 2013. I thought a minute and said, “Copying the files into the SharePoint 2013 environment.” And you know what? It was just about that easy. Take that, managed code developers!

We took a backup of the development Site Collection and restored it into the 2013 environment. Then I simply copied and pasted the script, CSS and HTML files we had built into the 2013 environment. The “conversion” was a big copy of the files from a Document Library using SharePoint Designer 2010 and a paste into a Document Library using SharePoint Designer 2013.

Caveat: there was *one* thing I needed to fix. While “protocol-less” script references are considered good practice, SharePoint Designer doesn’t deal well with them and tries to fix them up; breaking them in the process. So I did have to repair those script reference hrefs, but I didn’t need to rewrite a single line of code!

At that point we were in SharePoint 2013 and I was calling the SOAP Web Services with SPServices. Shouldn’t I have switched to REST calls right away? We decided not to tackle that then because we wanted to finish the application and get it released. I’ve pushed to do some replacement in subsequent versions, and we’ve done it where it makes sense. It’s not a very big deal because we have the discrete data access methods in place. In fact, we have replaced only the methods we were using during updates with REST calls and can tackle others later. We may continue to decide which calls fall into each category simply by what the REST services support or we may decide based on level of effort, but the level of effort won’t be high, I guarantee it.

This article was first published on IT Unity on April 6, 2015. Visit the post there to read additional comments.