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 Applicationand apply the following settings to your project:Target Framework: .NET 3.5 - Build output:
AnyCpu(orx64)
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:
/PostImages/SP2010ClientOM/ScreenShot001.png
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.
- Right click the
Referencesnode and chooseAdd Reference
/PostImages/SP2010ClientOM/ScreenShot002.png.png
- Choose
Browse - Navigate to this folder:
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI - Select these two files: 1.
Microsoft.SharePoint.Client.dll,Microsoft.SharePoint.Client.Runtime.dll
/PostImages/SP2010ClientOM/ScreenShot004.png
- Make sure they are included in the references of your project:
/PostImages/SP2010ClientOM/ScreenShot005.png
- Add the following using-statement in your class (note the last line!):
/PostImages/SP2010ClientOM/ScreenShot008.png
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
Buttoncontrol - A new
TextBoxcontrol (Set multiline = true, readonly = true etc to make it look like mine if you want..)
/PostImages/SP2010ClientOM/ScreenShot006.png
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("yourUrl"))
{
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("yourUrl"))
{
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:
- You use the ClientContext object to connect and work with the SharePoint server
- You use ClientContext.Load() to load the objects you need to work with
- You use the ClientContext.ExecuteQuery() to execute the query and fetch the objects
Running the simple application
When you decide to run this awesomely simple application, it will look something like this:
/PostImages/SP2010ClientOM/ScreenShot009.png
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 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:
AnonymousDefaultFormsAuthentication
/PostImages/SP2010ClientOM/ScreenShot010.png
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!
Comments are closed
Archived comments
Hi Tobias
The graphics are missing on the page and the download file is also missing. Can you re-upload the file please.
Cheers
Thanks for the pointers, the images clearly didn't make it in the blog migration. I'll look into that.
Cheers.
Very well written article but alas your awesome sample project is no where to be found.
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
Seems like there is some information missing from what is pasted. can't replicate it, as some information was in the images only.
learn how to properly add pics to a post
Learn how to read the comments already posted. Great, thanks.
The link to the sample project is broken, please update, thanks for the great post!
Unfortunately the sample project didn't make it through the blog migration. All the necessary code is published in the blog article though :-)
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
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.
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
Great article....but images have gone for a walk....
Yes, they were tired of hanging around here all day long :-)
Maybe you can edit the original article then. Especially where you indicate to "add the following using statement" and don't actually type the statement.
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...
thanks in advance,
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
Nice Article. Well i need to get the document id once the document is uploaded on sharepoint server programmatically. Any help would be appreciated.