Creating Your First Windows 8 Application using the Client Object Model (CSOM) and JavaScript
CREATING YOUR FIRST WINDOWS 8 APPLICATION USING THE CLIENT OBJECT MODEL (CSOM) AND JAVASCRIPT

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

Posted by on Friday, February 15th, 2013  

 

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 FilesCommon Filesmicrosoft sharedWeb Server Extensions15ISAPI”

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<SocialActor[]> 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<SocialActor[]> 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<SocialActor[]>” 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<SocialActor[]> 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 += "<br/>" +
            "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 “<p>Content goes here</p>” portion of the html so that the file looks like the code below:

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

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

    <!-- App1 references -->
    <link href="/css/default.css" rel="stylesheet" />
    <script src="/js/default.js"></script>
</head>
<body>
    <input type="button" value="Get Followed Content" onclick="GetMyFollowedContent();" />
    <div id="output"></div>
</body>
</html>

So, now when our application starts up the user will see a button at the top of the page that reads “Get Followed Content”.  When the user clicks the button our JavaScript function will call the Windows Runtime Component function which will retrieve the followed content for the current user using the Client Side Object Model. It will then iterate over all the followed content and write it out to the “output” div… simple eh?

Go ahead, rebuild your solution, and let’s run that puppy…

ooh.. there’s your button… go click it…

Well crap… now what…..

Unhandled exception at line 36, column 5 in ms-appx://49fb4604-c887-44e9-936d-0e7046dc453d/js/default.js

0x80131509 – JavaScript runtime error: System.Net.WebException —> System.Net.Sockets.SocketException

at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)

at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)

— End of inner exception stack trace —

at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)

at System.Net.HttpWebRequest.GetRequestStream()

at Microsoft.SharePoint.Client.ClientContext.GetFormDigestInfoPrivate()

at Microsoft.SharePoint.Client.ClientContext.EnsureFormDigest()

at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()

at WindowsRuntimeComponent2.Class1.GetFollowedContent()

WinRT information: Unable to connect to the remote server

What’s going on here? We’ve set everything up and it compiled for crying out loud!??! I’m sure you’ve tried browsing to your SharePoint site in your browser to make sure you can get to it, so obviously you can connect to your remote server. I take it back, I hate Windows 8 application development…

Slow your roll, before you rage quit and join a gang, let’s figure out what’s going on. Obviously your Windows 8 application is not able to communicate with SharePoint. Let’s do a quick search online to see if someone has had a similar problem.. and wouldn’t you know it! I came across a blog post from my MVP buddy Corey Roth at: How to: Use the SharePoint 2013 REST API from a Windows Store App (Windows 8 Metro).

According To Corey: “Just like Windows Phone and SharePoint apps need to declare the capabilities of the application, Windows Store Apps are no different.  To do this, open Package.appmanifest.  In our case, we need to declare that we intend to communicate over the internal network (Private Networks) and that we need Enterprise Authentication.  The latter allows the app to authenticate with the current user’s domain credentials automatically.  If you don’t have this capability set, you are guaranteed a 401 Access Denied or Unable to connect to remote server error.

In other words, we need to allow our Windows 8 Application to communicate with our SharePoint Server. So, let’s open up the “package.appxmanifst”, click on the “Capabilities” tag and do as Corey suggests:

image

Now, let’s run the application again…

with fingers crossed…

maybe your toes too?

Say a prayer…

Click our button..

and…

VIOLA!!! Success!

image

Okay.. so I’m not following a lot of stuff, but still.. it works.. okay?

Where you go from here is up to you… Beware though, there are still a lot of quirks you will run into when dealing with HTML and JavaScript in Windows 8 application development. Let me know if you find this post useful at all and I’ll do a follow-up regarding those quirks.

Regardless, I hope this made your life somewhat easier. Thanks once again for stopping by.

References

Not so fast, before you go, check out these reference links. It’s how I learned to do all this stuff….

Good luck!

 

Disclaimer
The sample scripts are not supported under any Summit 7 Systems standard support program or service. The sample scripts are provided AS IS without warranty of any kind. Summit 7 Systems further disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you. In no event shall Summit 7 Systems, its authors, or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts or documentation, even if Summit 7 Systems has been advised of the possibility of such damages.

Subscribe to RSS Feed

Sign Up for Newsletter

3

3

comments

    Mar 18
    2013

    Minh-Hoang PHAM

    Nice post. I tried also to make it work in Win8 app last year but it did not work because I tried to add some SharePoint 2010 client DLLs. This time in believing your idea, I gave it another shot and trying with SharePoint 2013 client DLLs then it worked perfectly for me. Thanks a lot and keep it going on!

    Jun 07
    2013

    Danny Jessee (@dannyjessee)

    Great post (and great session at SPC last year…I was there!) It’s worth mentioning that you also need to set the “Copy Local” attribute to “True” for the CSOM DLL references in your Windows Runtime Component or you will get a JavaScript FileNotFoundException at runtime.

    Jun 12
    2013

    Josh Fuller

    Has anyone gotten as far as submitting a completed app to the Windows 8 store? It appears that the CSOM dll reference causes the app to fail the certification process.