SP 2010: Getting started with the Client Object Model in SharePoint 2010

Author: Tobias Zimmergren
http://www.zimmergren.net | http://www.tozit.com | @zimmergren

Introduction

In this article I will talk about how you can get started with using the Client Object Model in SharePoint 2010. This new object model is introduced in SharePoint Foundation 2010, and does not require SharePoint Server 2010 to be installed.

The Client Object Model is a new object model introduced in SharePoint 2010 which is aimed at making things easier for the developer when developing client-side applications for SharePoint 2010.

Three new client APIs

With the Client Object Model, Microsoft has introduced a set of new APIs to work with to ease the daily tasks of developers.

  • .NET Managed Applications (using the .NET CLR)
  • Silverlight Applications
  • ECMAScript (JavaScript, JScript)

The client APIs provide you as a developer with a subset of the Microsoft.SharePoint namespace which is based on the server-side object model.

Naming conventions

As a small side-note I would like to mention that the objects you are comfortable with calling “SPWeb”, “SPSite”, “SPList” and so on are now named “Web”, “Site”, “List”.

So to conclude the naming convention, the “SP” in the objects has been dropped. Easy enough to remember, right?

Good, let’s move on to some actual code samples to get things fired up!

SharePoint 2010 Client Object Model – Creating your first client-side application

With some fundamental knowledge about the Client OM mentioned above, I would like to take this one step further and actually demonstrate how you can utilize the Client OM in order to create your first client-side application and work with data from SharePoint, instead of using the built-in Web Services.

Step 1 – Creating the Visual Studio project

To be able to follow along with this article, the prerequisites are that you have SharePoint 2010 and Visual Studio 2010 installed in a development environment.

  • Launch Visual Studio 2010
  • Create a new project
  • Choose “Windows Application” and apply the following settings to your project:
    • Target Framework: .NET 3.5
    • Build output: AnyCpu (or x64)

As you can see we are specifically targeting .NET 3.5 since this is the version of the framework that SharePoint 2010 is based on.

Also notice that we are changing the build output from x86 (unsupported!) to AnyCpu or x64 in order to be able to compile and run this project properly.

You should now have an empty Windows Application project like so:   
ScreenShot001

 

Step 2 – Adding the Client Object Model references

Next, we need to add references to the Client Object Model in order to be able to work with the client-side APIs from our awesome Windows Application.

  1. Right click the “References” node and choose “Add Reference”  
    ScreenShot002
  2. Choose “Browse
    1. Navigate to this folder:
      C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14ISAPI
    2. Select these two files:
      1. Microsoft.SharePoint.Client.dll
      2. Microsoft.SharePoint.Client.Runtime.dll 

         ScreenShot004
  3. Make sure they are included in the references of your project: 
    ScreenShot005
  • Add the following using-statement in your class (note the last line!): 
    ScreenShot008

Alright – that was easy enough. Adding the references shouldn’t be any problems. Moving on the the more interesting part – getting our first client object model application up and running!

Step 3 – Make our Windows Application pull out some data from SharePoint

Now that you’ve created your Windows Application, targeted the correct framework and platform, added the Client object model references – we’re ready to take on some Client Object Model action!

Adding the necessary controls to the form
  • Add the following controls to your Windows Application:
    • A new ListBox control
    • A new Button control
    • A new TextBox control (Set multiline = true, readonly = true etc to make it look like mine if you want..)

ScreenShot006

Adding some code-logic to fetch the lists on a particular site and populate the ListBox
  • Double-click the Button that you’ve created and add the following code logic:

private void btnGetLists_Click(object sender, EventArgs e)
{
    lbLists.Items.Clear(); 

    using (SP.ClientContext ctx = new SP.ClientContext("http://zimmer"))
    {
        var web = ctx.Web; 

        ctx.Load(web);
        ctx.Load(web.Lists); 

        ctx.ExecuteQuery(); 

        foreach (SP.List list in web.Lists)
        {
            lbLists.Items.Add(list.Title);
        }
    }
}

  • Double-click the ListBox that you’ve created and add the following code logic:

private void lbLists_SelectedIndexChanged(object sender, EventArgs e)
        {
            using (SP.ClientContext ctx = new SP.ClientContext("http://zimmer"))
            {
                var list = ctx.Web.Lists.GetByTitle(lbLists.SelectedItem.ToString());

                ctx.Load(list);
                ctx.ExecuteQuery(); 

                string infoAboutList =
                    string.Format("Title: {0}ItemCount: {1}IsHidden: {2}",
                    list.Title + Environment.NewLine,
                    list.ItemCount + Environment.NewLine,
                    list.Hidden.ToString()); 

                textBox1.Text = infoAboutList;
            }
        }

Things to note:

Running the simple application

When you decide to run this awesomely simple application, it will look something like this: 
ScreenShot009

With a few simple lines of code you have created your first Client-side application for SharePoint 2010.
Of course we could elaborate this sample to make it way more complex, but this is a teaser for you to get started with the client object model.

Step 4 – Authentication Options for our application

Quite naturally, the question of how you can authenticate to SharePoint often pops up when I do my SP 2010 training and seminars. With that said, I’ll walk you through the different authentication options you’ve got for your client application.

Basically there are three (3) authentication options you can use when you’re working with the Client Object Model in SharePoint 2010:

  • Anonymous
  • Default
  • FormsAuthentication

ScreenShot010

If you do not choose an authentication method in your code, the application will default to using the client’s Windows Credentials (DefaultCredentials)

Example 1: Using anonymous authentication

ctx.AuthenticationMode = SP.ClientAuthenticationMode.Anonymous;

Example 2: Using Forms Authentication with the Client Object Model

SP.FormsAuthenticationLoginInfo formsLoginInfo = 
new SP.FormsAuthenticationLoginInfo("TobiasZimmergren", "SecretPassword");

ctx.AuthenticationMode = SP.ClientAuthenticationMode.FormsAuthentication;

ctx.FormsAuthenticationLoginInfo = formsLoginInfo;

When you call the Forms Authentication, it will automatically call the Authentication Web Service for you and return the authenticated cookie.

Summary & Downloads

With very little effort, we have created a new Windows Form application that can be run as a client-side application – without the need of SharePoint to be installed on that machine.

Easy enough we have done so without calling any Web Services.

With that said, you should now at least be updated on how you create your first few Client Object Model applications, and be able to start your own project(s) using this new awesome OM.

ENJOY!

Download my sample project

Download my awesome sample project here

Follow me

Tobias Zimmergren

Founder / Consultant / Advisor at TOZIT AB
Tobias Zimmergren delivers high-quality articles about business and technology around the Microsoft scene.

Tobias focuses on advisory and consultancy for the Office 365 and SharePoint offerings from Microsoft.
Follow me
  • Pingback: Object get | Ltdcare

  • Pingback: Javascript jscript | Haymanproducts

  • TS

    Hi Tobias

    The graphics are missing on the page and the download file is also missing. Can you re-upload the file please.

    Cheers

    • http://www.zimmergren.net/ Tobias Zimmergren

      Thanks for the pointers, the images clearly didn’t make it in the blog migration. I’ll look into that.
      Cheers.

  • Vaqar Hyder3567

    Very well written article but alas your awesome sample project is no where to be found.

    • http://www.zimmergren.net/ Tobias Zimmergren

      Hey Vaqar. Thanks.
      About the project; You can just rip the code right out of the blog – all the necessary code is published there.

      Cheers,
      Tobias

      • victor

        Seems like there is some information missing from what is pasted. can’t replicate it, as some information was in the images only.

  • Johan Kruger

    learn how to properly add pics to a post

    • http://www.zimmergren.net/ Tobias Zimmergren

      Learn how to read the comments already posted. Great, thanks.

  • Gvijaikumar9

    The link to the sample project is broken, please update, thanks for the great post!

    • http://www.zimmergren.net/ Tobias Zimmergren

      Unfortunately the sample project didn’t make it through the blog migration. All the necessary code is published in the blog article though :-)

  • http://www.thesarkarinaukri.net/ Govt. Jobs

    I was interesting, but it has become clear is beneficial. To update a lot of excitement.

  • http://highpageranklink.in/ High Pagerank Link

    Interesting post and thanks for sharing. Some things in here I have not thought about

    before.Thanks for making such a cool post which is really very well written.will be referring a

    lot of friends about this.Keep blogging

  • Richard

    Great Article
    Do you have any advice on using clientcontext and the current user’s AD credentials with Kerberos?

    I have console app that I have been using to try out the clientcontext.. It works when I tell it to go to a NTLM based site, but gives a 401 error when I point it to a Kerberos based site. It also works when I tried httprequest objects pointing to the KRB site

    Is there anything else I need to add?

    Here’s the code

    string siteURL = “http://dev-ntlm/site”;
    //string siteURL = “http://dev-krb/site”;

    ClientContext ctx = new ClientContext(siteURL);
    CredentialCache cc = new CredentialCache();
    cc.Add(new Uri(siteURL), “Kerberos”, CredentialCache.DefaultNetworkCredentials);
    ctx.Credentials = cc;
    // ctx.AuthenticationMode = ClientAuthenticationMode.Default;
    ///1
    Web remoteWeb = ctx.Web;
    ctx.Load(remoteWeb);
    ctx.ExecuteQuery();

    This fails on the executeQuery(); with and without the ClientAuthenticationMode.Default line..

    Other posts discuss the kerberos configuration and ensuring the domains match, but kerberos works with a web service pointed at list.asmx. It also works with httprequest / httpresponses with the following inserted at point ///1

    HttpWebRequest WebRequest =(HttpWebRequest)WebRequest.Create(siteURL);
    WebRequest.Credentials = cc;
    WebRequest.UseDefaultCredentials = true;
    HttpWebResponse WebResponse = (HttpWebResponse)WebRequest.GetResponse();

    This suggests to me that the client config, the domains & the Sharepoint box configuration are OK …. and that there is something up with the ClientContext config

    Thanks in advance

    • Richard

      Have been working on this

      I have added the code to insert X-FORMS_BASED_AUTH_ACCEPTED: f in to the header to allow Kerberos Authentication to a site. it partially solved my problem. I can log in to the root with ClientContext with Kerberos. A Fiddler debug shows I am redirected to “/_vti_bin/sites.asmx” with a 200 status code, but then I’m sent on to “/sites/hrer/_vti_bin/client.svc/ProcessQuery” which gives a 500 – System.ServiceModel.ServiceActivationException.

      Putting this URL in the browser tells me I need Windows authentication for the service, but isnt that what the X-FORMS_BASED_AUTH_ACCEPTED: f header does ?

      Any ideas on how to fix this.

  • http://casinospiele2000.com/ casino spiele

    Nice to very useful info for me.Because i’m new in blogging and i’m need good tutorial like your post.

  • http://www.casino-tests-lesen.com/ online casino test

    Very interesting and useful discussion for me. I think this is a common problem for all parents so don’t worry about it. Thanks guys for such a great comments, have a good luck.

  • http://www.online-casino-berater.com/ online casino free

    I have been reading and reviewing your article for a few minutes to ponder some of your sound points. I like the way you think and I agree on a large portion of this content.

  • Chris

    Is there any documentation on how to authenticate the CSOM in Silverlight against SharePoint Online?
    Since some of the applications we are writing are quite large we wanted to have the option to have some of them as desktop applications. We have no problem doing this with a .Net application. But we can’t get it to work from the CSOM within Silverlight. Is it possible? If so can someone point us in the right direction. *sigh* its always the simple stuff that killsa project LOL

  • Mudit

    Great article….but images have gone for a walk….

    • http://www.zimmergren.net/ Tobias Zimmergren

      Yes, they were tired of hanging around here all day long :-)

  • Pingback: Client Object Model in Sharepoint | Software related stuff thro my experiences!

  • Dmitry

    Dear Tobias,

    I have CSOM application for SharePoint ( remote website ) running, in my VisualStudio 2010,

    but since I’m trying to deploy application to clean machine, my log says :

    Could not load file or assembly ‘Microsoft.SharePoint.Client, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c’ or one of its dependencies. The system cannot find the file specified….

    Can you please suggest what set of installation .NET packages must be installed?

    I have installed only this:

    SharePoint Foundation 2010 Client Object Model Redistributable

    http://www.microsoft.com/en-us/download/details.aspx?id=21786

    thanks in advance,
    Dmitry

    • Dmitry

      Tobias, we have found the reason why our application did not run.It started after manually placing in local folder Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll of v16 and registering them with RegAsm.

      But we can not find a distributive where v16 comes from. It seems v16 appears on developer machine with MSVS2013.

      Can you please suggest if there in space official standard distributives including v16 of CSOM.

      thanks,
      Dmitry