客户端对象模式是Sharepoint2010的一个新功能,它允许开发者在远程的客户端通过编程的方式来操作Sharepoint的列表。如你可以在远程的客户端创建WinForm、WPF、Silverlight或者Javascript操作Sharepoint数据。
下面我们创建一个WinForm应用来读取列表数据:
1、 打开VS2010,File->New Project->Windows Form Application,确保选择 的是.NET Framework3.5,为项目起个名字,如:SPReadListData.
2、 添加一个Lable,一个Textbox,一个Datagrid和两个按钮,如下图:

3、 为项目添加一个类:BlogInfo,并为它添加以下代码:
class
BlogInfo
{
public
string
BlogTitle {
get
;
set
; }
public
string
BlogContent {
get
;
set
; }
public
string
BlogAuthor {
get
;
set
; }
}
4、 分别双击两个按钮,为按钮分别添加事件代码:
为推出按钮的点击事件添加如下代码:
为获取数据按钮添加代码前,我们需要先为项目添加两个引用,Microsoft.SharePoint.Client.dll和Microsoft.SharePoint.Client.RunTime.dll,他们一般位于:
c:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI,在代码中添加如下的using:
using
ClientOM
=
Microsoft.SharePoint.Client;
至于为什么不直接用using Microsoft.SharePoint.Client;而是用using ClientOM = Microsoft.SharePoint.Client;,这是为了避免和命名空间using System.Windows.Forms;的冲突。
在获取数据按钮的事件中添加如下代码:
代码
private
void
btnLoadData_Click(
object
sender, EventArgs e)
{
string
SPUrl
=
txtbxSPURL.Text;
IEnumerable
<
ClientOM.ListItem
>
myListItems;
List
<
BlogInfo
>
myBlogs
=
new
List
<
BlogInfo
>
();
ClientOM.ClientContext SPContext
=
new
ClientOM.ClientContext(SPUrl);
ClientOM.Web mySPSite
=
SPContext.Web;
ClientOM.ListCollection myListCollection
=
mySPSite.Lists;
var productsList
=
SPContext.Web.Lists.GetByTitle(
"
Blog
"
);
ClientOM.CamlQuery myCamlQuery
=
new
ClientOM.CamlQuery();
IQueryable
<
ClientOM.ListItem
>
myList
=
productsList.
GetItems(myCamlQuery);
myListItems
=
SPContext.LoadQuery(myList);
SPContext.ExecuteQuery();
var returnedListData
=
from prod
in
myListItems
select prod;
foreach
(ClientOM.ListItem tempListItem
in
returnedListData)
{
BlogInfo tempBlog
=
new
BlogInfo();
tempBlog.BlogTitle
=
tempListItem.FieldValues.Values.ElementAt(
1
).ToString();
tempBlog.BlogContent
=
tempListItem.FieldValues.Values.ElementAt(
4
).ToString();
tempBlog.BlogAuthor
=
tempListItem.FieldValues.Values.ElementAt(
5
).ToString();
myBlogs.Add(tempBlog);
}
dtgrdSPListData.DataSource
=
myBlogs;
}
在上面的代码中,我们使用了ClientContext对象,这是Sharepoint客户对象模型(Client Object Model)的一个关键的功能。当然,我们也使用了Linq来组织数据。
5、 当你运行此程序时,你会看到如下的画面:

项目文件下载:http://files.cnblogs.com/Jayan/SPReadListData.zip