Creating Your First Windows 8 Application using the Client Object Model (CSOM) and JavaScript

Body:

Definitely one of my highlights from 2012 was presenting a session at the Microsoft SharePoint Conference in Vegas with my cohort Eric Harlan. In our session we built a Windows 8 application using HTML and CSOM to retrieve and post information for SharePoint 2013’s Social features.

We got a lot of great feedback on the session and actually scored fairly well tell too. I think what resonated with the audience is that we built the application step-by-step and even allowed the application to throw many of the errors I ran into when writing the application. I wanted to bring some “real world” to the demos and help people overcome these common errors when they were writing their own applications. I’ve been meaning to blog about this as well but have been so busy / burned out that I just have not gotten around to it.  Well… thanks to insomnia, I’m finally getting around to it.  

Okay.. okay.. enough rambling back story… Let’s step through the process of building your first JavaScript Windows 8 application that uses SharePoint 2013’s CSOM (Client Side Object Model). 

Getting Started

So, I’m going to write this blog so that anyone wanting to getting started with Windows 8 apps and SharePoint CSOM can have a reference point. I’m not going to assume you know anything. I’ll pretend you are me.  🙂

Get Visual Studio 2012 for Windows 8

First things first, make sure you have Visual Studio 2012 for Windows 8. You don’t have it?? Well… lucky for you, you can get Visual Studio Express 2012 for Windows 8 for free!! From what I can tell, there are no limitations in your Windows 8 application development either. So, you have no excuse for not developing your own application. Go on… go download and install it…  we’ll wait. 

Creating A Windows Store Project

Now we need to create our Windows Store Project using one of the templates in Visual Studio. Click on “File->New Project”.  From here you can add a XAML Project under “Visual C#->Windows Store” or, if you aren’t a JavaScript hater you can add a JavaScript project under “JavaScript->Windows Store”.  Obviously, given the name of this blog post I’m going to be adding a JavaScript project using the “Blank App” template.

image 

Name your project and click “OK”.

Congrats! You’ve created your first Windows Store project. The project comes with several files to get you started, pay special attention to the “default.js” and the “default.html” files. This is where you will build out your interface, include other scripts, and call functions from those other scripts.

Go ahead and run the project, you’ll just have a blank screen with the message “Content Goes Here”. Nothing too fancy.  One thing you will notice about Win 8 application development is that you don’t write any code to “end” or “exit” the program. In general you only write code that ends your Windows 8 application in some sort of error handling logic.

Also, go ahead and click the “Windows” button and go back to your desktop. Notice anything? Yep, you now have an icon for your application on your desktop.

image

You can change the image used for the tile for the application as well as other options by double clicking on the “package.appxmanifest” file in the Solution Explorer and editing those values.

image

Nothing too hard, or too fancy. So, now let’s get things set up so our application can communicate with SharePoint!

Add a Windows Runtime Component Project

Since we will be using the Client Side Object Model, we’ll need to create a “Windows Runtime Component” project and add it to our solution. This is where Windows 8 development gets pretty cool. You can write C# code in your Windows Runtime Component and call it from your JavaScript code. This allows us to write a JavaScript application and use the .NET CSOM easily.

Anecdotally, I was having conversations with some smart SharePoint developers who were trying to use the Client Side Object Model in a Class library for their XAML applications and could not get it to work. I don’t know if this means it just not possible to use the CSOM libraries in a Windows Store Application without using a Windows Runtime Component, or if there was some quirk or setting that wasn’t getting set properly, regardless, if you are having this problem, try creating a Windows Runtime Component instead. Maybe if I ever get more motivated I’ll do some research and figure out if this is true and if so, the reasons… but hey, I’m lazy and I got it working… so.. I’m good for now.  🙂

Anyway, let’s add our Windows Runtime Component project. Select “File->Add->New Project”.  Then under “Templates” select “Visual C#” and then “Windows Store” and finally “Windows Runtime Component”

image

Name your project and click “OK”. Last thing we need to do here is add a reference from our Windows Runtime Component project to our JavaScript project so the JavaScript project can use the Windows Runtime Component functionality. So, right click on the “References” for your JavaScript project in the Solution Explorer and select “Add Reference”.  Then select “Solution”, click the checkbox next to your Windows Runtime Component project, and click “OK”.

image

You’ll now see your Windows Runtime Component Library listed as a reference.

image

Now (after you build your project) you can open up your “default.js” file and even get Intellisense into your C# Windows Runtime Component library:

image

Pretty cool? eh?

A Word about Debugging

So, you can set break points in your code now and step through either your JavaScript code or your C# code. You cannot, however, debug both at the same time. 

To debug your JavaScript, right click on the name of your project, select “Properties”. Then under the “Debugging” section select “Script Only” for “Debugger Type”.

image

To debug the C# code in your Windows Runtime Component, select “Managed Only”.  You can now step through your C# code while debugging your application.

Now back to our regularly scheduled blog.

Add CSOM libraries to your Windows Runtime Component Library

Before we can use the CSOM libraries we have to actually add references to our desired libraries to your Windows Runtime Component Library. The CSOM libraries are located on your SharePoint Server under “c:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI”

Like in our SPC Session, I’m going to execute a method to access some of SharePoint Social features, so for the purposes of this blog I’m adding references to:

  • Microsoft.SharePoint.Client.dll
  • Microsoft.SharePoint.Client.Runtime.dll
  • Microsoft.SharePoint.Client.UserProfiles

So, under your Windows Runtime Component Project, right click on “References” and select “Add Reference…” and add references to the above mentioned dll’s.

image

Also, be sure to add the correct using statements to your .cs file as well:

image

Okay! We are now ready to write some CSOM code! 

Using the Client Object Model to retrieve followed content

A fairly simple CSOM Social operation is retrieving all the followed content for a user. So, using common sense that code would look like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Social;
using System.Net;

namespace WindowsRuntimeComponent2
{
    public sealed class Class1
    {
        public static ClientResult GetFollowedContent()
        {
            //create client context. 
            ClientContext cc = new ClientContext("http://fe01");
            cc.Credentials = CredentialCache.DefaultCredentials;

            //if you don't want to use default credentials you can also specify credentials using
            //cc.Credentials = new NetworkCredential("url", "username", "password", "domain");

            //create a SocialFollowing Manager to retrieve all the followed content
            SocialFollowingManager sfmgr = new SocialFollowingManager(cc);

            //Each item followed (documents, sites, tags, and users) is an "Actor" object.
            //We want to get all followed content.
            ClientResult actors = sfmgr.GetFollowed(SocialActorTypes.All);

            //execute our query
            sfmgr.Context.ExecuteQuery();

            //return all the followed content
            return actors;
        }
    }

}

Seems simple? right? All your CSOM functionality should be structured fairly similarly and have the 3 main steps involved:

  1. Create Context (if you don’t already have it)
  2. Create Query
  3. Execute Query (using your context)

For more information on common CSOM operations, check out How to: Complete basic operations using SharePoint 2013 client library code. That should get you started on many things you’d like to do with CSOM.

Okay.. now that you code is created, let’s build our project.

image

Hmmm… maybe this isn’t going to be as easy as we thought… what in the world?? 

Welcome to the wonderful world of Windows Runtime Component Libraries, in this wonderful world you are only allowed to return valid Windows Runtime Types externally. We are trying to return “ClientResult” which is NOT a valid Windows Runtime Type. What are valid Windows Runtime Types??? So glad you asked, check out: Windows Runtime base data types

So, what do we do? It looks like an Object is a valid type?  Why don’t we create a class to store all of the information we care about for a followed item and then return an array of that class? That should satisfy these needs??  Let’s change our code as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Social;
using System.Net;

namespace WindowsRuntimeComponent2
{
    public sealed class Class1
    {
        public static FollowedContent[] GetFollowedContent()
        {
            //create client context. 
            ClientContext cc = new ClientContext("http://fe01");
            cc.Credentials = CredentialCache.DefaultCredentials;

            //if you don't want to use default credentials you can also specify credentials using
            //cc.Credentials = new NetworkCredential("url", "username", "password", "domain");

            //create a SocialFollowing Manager to retrieve all the followed content
            SocialFollowingManager sfmgr = new SocialFollowingManager(cc);

            //Each item followed (documents, sites, tags, and users) is an "Actor" object.
            //We want to get all followed content.
            ClientResult actors = sfmgr.GetFollowed(SocialActorTypes.All);

            //execute our query
            sfmgr.Context.ExecuteQuery();

            //create an array of FollowedContent the size of the number of actors returned
            FollowedContent[] followedContent = new FollowedContent[actors.Value.Length];

            int index = 0;

            foreach (SocialActor actor in actors.Value)
            {
                FollowedContent content = new FollowedContent();
                content.Type = actor.ActorType.ToString();
                content.Name = actor.Name;
                content.Title = actor.Title;
                content.Uri = actor.Uri;

                followedContent[index++] = content;

            }

            //return all the followed content
            return followedContent;
        }
    }

    public sealed class FollowedContent
    {
        public String Type { get; set; }
        public String Name { get; set; }
        public String Uri { get; set; }
        public String Title { get; set; }
    }

}

So, we had to do a little extra work to iterate through all the actors and store them in our array, but we should now be able to return the list of followed content to our JavaScript Project. You can rebuild your project now and sure enough, it rebuilds fine.

Call the Windows Runtime Component Library from your JavaScript file

Now it’s time to edit our JavaScript project so that it calls our function in the Windows Runtime Component Library. First thing we need to do is edit our “default.js” file from our JavaScript project and create a function that will call into our Windows Runtime Component library. Go ahead and and the following code to the bottom of file.

function GetMyFollowedContent()
{
    //get the followed contenet from the Windows Runtime Compnent that is using CSOM
    var myFollwedContent = WindowsRuntimeComponent2.Class1.getFollowedContent();

    //loop through the followed content and display it on the main screen
    for (content in myFollwedContent) {
        document.getElementById('output').innerHTML += "
"
+ "Name: " + myFollwedContent[content].name + " Type:" + myFollwedContent[content].type + " Uri:" + myFollwedContent[content].uri; } }

This simple function executes our “GetFollowedContent” function in our Windows Component Runtime Library and iterates over the results displaying them in a div with the id “output”. If you typed in the above code, did you notice all the Intellisense you got for both JavaScript AND your Windows Runtime Component? I know? cool? right?

Now, we need to edit our “default.html” file to create a button that executes our JavaScript function and to create the “output” div to display our results.  Open up the file and replace the “

Content goes here

” portion of the html so that the file looks like the code below:

DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>App1title>

    
    <link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.1.0/js/base.js">script>
    

    
    "/css/default.css" rel="stylesheet" />