Working with Content Types in the JavaScript Client Object Model

Some things that should be simple are made more difficult in the Client Object Model because of the asynchronous manner in which it works. The Client Object Model does not interact directly with SharePoint’s data – it is really a wrapper for web service calls that send and receive messages from SharePoint. So in order to do anything with the CSOM, you need to send a request to the web service, wait for the response, and then act on it.

A prime case is Content Types. Suppose you had a list with multiple Content Types, and you need to fetch an item and determine its Content Type. You might think you could do something like this:

Var ct = listItem.get_item("Content Type");

Well, there is no such property available in the CSOM object. You could Fiddle the web service response JSON of a simple query like this and you would not see the Content Type’s name anywhere, so there’s no chance the CSOM will be able to get that data. There is, however, and object called ContentTypeId which has a property containing the Content Type’s ID.

In order to get the name of the list item’s Content Type, here’s what we need to do: We need to explicitly query the list’s Content Types collection, load it into the context object, and loop through the collection until we find the one whose ID matches the ContentTypeID we’ve found earlier.

Note: Sometimes it’s not so obvious when we need to call load() on an object when querying the Client Object Model. Here is a rule of thumb I have developed: For “loose” properties, you generally do not need to explicitly load them, but for collections of objects, you need to call load on them. For example, a collection of Content Types on a list, or a collection of Lists in a Web object, must be loaded into the context object explicitly.

The code to do this would look something like this:

//couple of global variables
var listItem = null;
var listContentTypes = null;

function getContentTypeOfCurrentItem(id) {
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle("Projects");

    //get the list item and load() it
    listItem = oList.getItemById(id);
    clientContext.load(listItem);

    //get the content types and load the collection
    listContentTypes = oList.get_contentTypes();
    clientContext.load(listContentTypes);

    clientContext.executeQueryAsync(Function.createDelegate(this, getContentTypeOfCurrentItemSucceeded), Function.createDelegate(this, onQueryFailed));
}

//the callback
function getContentTypeOfCurrentItemSucceeded(sender, args) {    
    var ctid = listItem.get_item("ContentTypeId").toString();

    var ct_enumerator = listContentTypes.getEnumerator();
    while (ct_enumerator.moveNext()) {
        var ct = ct_enumerator.get_current();

        if (ct.get_id().toString() == ctid) {
            //we've got our content type, now let's get its name
            var contentTypeName = ct.get_name();
        }
    }
}

Setting the Content Type on a new list item

Setting the Content Type on a newly created list item works in about the same manner. You query the collection of Content Types, loop through them to find the one you want, get its ID and pass that ID into the new item using set_item():

var projectList;
function getContentTypeOfCurrentItem(id) {
    var clientContext = new SP.ClientContext.get_current();
    projectList = clientContext.get_web().get_lists().getByTitle("Projects");
    clientContext.load(projectList);

    //get the content types and load the collection
    listContentTypes = oList.get_contentTypes();
    clientContext.load(listContentTypes);

    clientContext.executeQueryAsync(Function.createDelegate(this, getContentTypeOfCurrentItemSucceeded), Function.createDelegate(this, onQueryFailed));
}

function getContentTypeOfCurrentItemSucceeded() {
    var CTID;

    var ct_enumerator = listContentTypes.getEnumerator();
    while (ct_enumerator.moveNext()) {
        var ct = ct_enumerator.get_current();
        if (ct.get_name() == ctName) {
            CTID = ct.get_id();           
        }
    }
   
    var newProjectInfo = new SP.ListItemCreationInformation();
    var newProject = reviewTasksList.addItem(newProjectInfo);
    newProject.set_item('Title', "Foo list item");
    newProject.set_item('ContentTypeId', CTID);
    //set other fields
    newProject.update();
    clientContext.load(newProject);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.SomeCallbackIhaveNotDefined), Function.createDelegate(this, this.queryFailed));
}

Become a great SharePoint developer in 10 easy steps

The job market for SharePoint developers is really hot lately, and right now it’s a really nice place to be from a career perspective. There just doesn’t seem to be enough of us around, and those who are can expect to be courted quite aggressively by recruiters (at least that has been my experience). With that in mind I thought I’d put together a list of steps to becoming a great SharePoint developer and getting in on the action:

1. Be (or become) really good at solving problems. When developing SharePoint solutions, you will quite often find yourself doing things that no one has ever done before. While this is true for any type of software development(I mean, if someone else has already done it they’d just use that), it seems especially true for SharePoint development, for a number of reasons:

a. There are just not that many SharePoint developers, and the more advanced your problem the fewer people there are doing something similar;
b. The sheer size and scope of the SharePoint platform means there is lots of unexplored and undocumented territory, and every now and then you’ll search on some aspect of SharePoint and find zero hits online.
c. SharePoint rarely exists in a vacuum. There are always integration points and little quirks that are unique to the organization deploying the product. These often center around network irregularities, legacy systems, business processes, or cultural issues within the organization. Any of these points, and more, can throw wrenches into your solution.

So all these things add up to one thing: you’d better be really good at solving these issues, because there is often nowhere to turn if you can’t figure them out.

2. Have access to a SharePoint environment. And when I say “access”, I really mean a complete development farm over which you have full control. Having your own environment opens up the following opportunities:
a. The freedom to make mistakes. Software development is about “poking the box”, as Seth Godin would say. That is, you learn by trying new things, making mistakes, and drawing lessons and understanding from them. Having your own environment means you can make all the mistakes you need to, roll back and keep going.
b. Your own security sandbox. Security is an important aspect of SharePoint solutions, and you’ll need the ability to create accounts and alter the privileges of those accounts. Suppose you are building a workflow that routes to different users. Without the ability to create and use different accounts, how on earth are you going to test that workflow?

If your employer is trying to get you to learn SharePoint and they have not provided you a full SharePoint server to use, they are setting you up for an uphill and frustrating experience.

3. Get some real-world problems to solve. Real-life solutions in SharePoint are rarely as straightforward as training or demo scenarios would make it seem. It is managing those quirky idiosyncrasies peculiar to the customers’ way of doing business that separates the competent devs from the pretenders. Workflows, especially, tend to get very tricky when you try to automate real-world business processes. Hands-on labs are a great way to get introduced to a topic, but once you’ve done them, try to apply them to the way things would actually work in your environment.

4. Get to know SharePoint’s user interface really well. Smart SharePoint developers know to leverage the out-of-the-box capabilities of the platform as much as possible. This means having a firm grasp on how to use SharePoint’s various UI components properly. The Ribbon, the ECB, Site Actions, List Views, Forms, layouts pages, web parts – each of these components, and more, lend a unique aspect to the SharePoint ecosystem, and knowing when and where to deploy these items will pay off in a number of ways. For example, leveraging OOB components will simplify your development efforts and result in a more consistent experience for your users. Knowing this will also come in handy when practicing skill number 5….

5. Learn to do things the SharePoint way. SharePoint is a funny platform. In many ways it gives you a lot of freedom, but it will punish those who take too much of that freedom. I see this a lot with user interfaces. Sure, in theory you can build lots of custom web parts and user controls and layouts pages to build out your screens exactly how you want them. Just know that if you do this as a default approach you are exposing yourself to some risks:
a. You are building an unnecessarily complex solution, which will lead to bugs, maintenance overhead and place more burden on your administrators.
b. You are likely missing out on a great deal of out-of-the-box SharePoint functionality. For example, if you are building a custom solution to show a grid of data, you are losing the ECB, the Ribbon, and some nifty sorting and filtering functionality, not to mention the security trimming, which you’ll now have to manage yourself. A common List View provides all this and more, and can be quite flexible through customization.

Also included with this skill is knowing how to push back when requirements are out of line with SharePoint’s expectations. You’ll need to seize these opportunities to educate your customers on “the SharePoint Way”.

6. Find a mentor. Trying to learn SharePoint on your own is an uphill struggle, and when you hit a wall you need somewhere to turn for help. Blogs and MSDN will only get you so far, and much of the content you’ll find on the web is either not useful or downright wrong – until you figure out where to look and whom to trust. Having a mentor or a network of colleagues will be a major asset, and if you are lacking this you’ll want to look for a user group or at the very least an online community like stack exchange to bounce ideas and ask for help.

7. Learn the internals of SharePoint. While the first six traits I outlined were mostly non-technical in nature, the remaining skills will cover the technical aspects of the things a SharePoint developer needs to know. Foremost on that list is an understanding of the underpinnings of SharePoint. There is a lot to learn here, but most of it is found in the “hive”, or the file system location where SharePoint’s files live(this is known as the ’14 hive’ in SharePoint 2010). The 14 hive is a treasure trove of useful information, and by looking through it(on a development machine of course), one can learn a whole lot about how Microsoft builds things. Among the useful things you can browse in the hive include:
○ Features
○ Layout pages
○ JavaScript files
○ Site Definitions and Web Templates
○ XSLT files
○ Images
○ Configuration files
○ User controls
○ Resource files
○ Much, much more

An understanding of how SharePoint is put together will help you understand how to extend it, and will offer clues as to the right way to do things when you are stuck(which will be often).

8. Learn .NET. SharePoint heavily leverages .NET, and any non-trivial solution you build will likely involve some amount of .NET integration. Knowing how to code in .NET is crucial, of course, but of equal concern is knowing the internals of .NET. Deploying an assembly to a SharePoint farm is a complex process, and you must master the various ways to deploy and register assemblies, modify and troubleshoot configuration entries, and advanced debugging techniques.

9. Get to know the Windows Infrastructure ecosystem. I’ve said it before, SharePoint doesn’t exist all alone by itself. It is tightly integrated with several Windows products, and getting comfortable with SharePoint means getting cozy with these systems as well, including Windows Server, SQL Server, and IIS. You may optionally find yourself dealing with other players as well, including Exchange, SQL BI, and the Office client. A knowledge of WCF and Workflow Foundation will likely come into play at some point as well.

10. Build solutions, not customizations. Many people who call themselves SharePoint developers never launch Visual Studio. While it’s true you can build great solutions in a very short time without ever using Visual Studio, the benefits of that approach will diminish in the long run. These “customizations” are one-off solutions and cannot be repeated unless the work is re-done. Since there is no source code associated with these efforts, maintenance becomes a dicey affair, and when a solution is broken, there’s often no way to resurrect it.

A professional SharePoint developer will use Visual Studio to build a repeatable, deployable solution package which can be deployed and activated on a site. He will follow the same processes as a custom-code solution, with source control, testing, deployment, and support.

Reflections on my first public speaking engagement

It’s been a day since my talk on Javascript solutions at SharePoint Saturday Detroit, so I’ve had some time to think and reflect on what went well and what didn’t. The feedback I received afterward was positive, and a few people even tweeted about it. 199 people have viewed my slides on SlideShare, which gives me great hope that people actually have an interest in what I had to say.

This was my first technical talk of any consequence, aside from client training sessions or internal Sogeti talks, so I was a little apprehensive about how it would play out. I obsessed over the content for a month, but walked into the room without a clear idea on whether I was really ready for this.

My main takeaways:

I can totally do this. Once I started speaking, the anxiety melted away, I fell into the role I do every day – a knowledgeable SharePoint developer who can speak authoritatively and passionately about JavaScript. The audience was engaged and asked great questions, and I felt like they were finding value in my content.
I had waaay too much content. My greatest fear was running out of things to say long before the time slot was up. Once I got into the flow of the talk, though, there was plenty to say, and soon enough I was startled when a guy in front said to me, “your time’s up”. The 75-minute time had come and gone, and my best demos went unseen. I learned that my scope has to be much smaller. Instead of trying to cram everything I know about JavaScript and SharePoint , I should have focused exclusively on either jQuery or the Client Object Model. In retrospect, I could have treated either of those topics alone for the entire time.
Don’t sweat it. There really was no reason for me to be anxious about this – the SharePoint community is full of helpful, passionate, and appreciative people.
I can’t wait to do it again. Rather than wait for the next conference to come around, I am going to seek out opportunities to talk to whoever will listen – clients, peers, user groups.

Thanks again to everyone who came out to see my talk!