Using CSOM in a Windows 8 app for SharePoint Online

Working with the Client-Side Object Model is rather easy and that’s why I looked for a solution to use it in a Windows 8 app.

There are two assemblies to be referred for working with the CSOM.

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

Creating the app

Let’s start by creating a new Class Library for Windows Store apps.
In here we add the references to the SharePoint assemblies.
In our Windows 8 app, we add a reference to our newly created class library.

Untitled

To be able to invoke methods on SharePoint Online using the Client-Side Object Model (CSOM), we need to authenticate first.
The authentication is based on this solution found on MSDN Blogs:
http://blogs.msdn.com/b/omarv/archive/2012/10/25/windows-8-store-apps-office-365-enterprise-preview-sharepoint-online.aspx

When the app starts, the app will try to retrieve the credentials from the password vault to connect to SharePoint. If the credentials from the password vault are empty, you’ll get the input fields to pass your credentials and login.

After the login is done, the cookies are stored in a CookieContainer. We need to pass this cookies to the CSOM ClientContext.

context.ExecutingWebRequest += delegate(object sender, WebRequestEventArgs e)
{
    e.WebRequestExecutor.WebRequest.CookieContainer = Cookies;
};

Now that we are loged in and that the cookies are passed to the ClientContext, we can do what ever we want using CSOM code.

In this example we will retrieve the site title.

BasicPage

SPClient client = new SPClient();
client.SiteUrl = AuthUtility.Current.SiteUrl.ToString();
client.Cookies = AuthUtility.Current.CookieContainer;
TextBlockTitel.Text = client.GetSiteTitle();

Class using the CSOM

public class SPClient
{
	public string SiteUrl { get; set; }
	public CookieContainer Cookies { get; set; }

	public string GetSiteTitle()
	{
		string Title = string.Empty;
		ClientContext context = null;

		try
		{
			using (context = new ClientContext(SiteUrl))
			{
				try
				{
					context.ExecutingWebRequest += delegate(object sender, WebRequestEventArgs e)
					{
						e.WebRequestExecutor.WebRequest.CookieContainer = Cookies;
					};
				}
				catch
				{
					if (context != null) context.Dispose();
					throw;
				}

				context.Load(context.Web);
				context.ExecuteQuery();
				Title = context.Web.Title;
			}
		}
		catch
		{
			throw;
		}

		return Title;
	}
}

You can download the sample code here. Enjoy!