ClientObjectModel(COM)可以理解为SharePoint对外提供的APIs,通过操纵它我们可以轻松的完成对SharePoint数据的CRUD操作。当然我们可以在SharePoint的自定义页面中调用它,也可以在第三方软件中调用它,并且它的使用方法也非常的简单。要调用它我们必须引用如下程序集:Microsoft.SharePoint.dll, Microsoft.SharePoint.Client.dll,Microsoft.SharePoint.Client.Runtime。
对应这套API将SharePoint 分为了三大块:Folder,File,Item。通过COM返回的folder和File对象都不能进行修改,如果要修改记录必须对返回的Item对象进行修改。估计Folder和File在这套API中充当Metadata来使用,而与这些Metadata对应的List,ListItem着代表着每条真实存在的记录。为了验证这个想法,我制作了一个迷你的CRUD程序,如下为其展示效果:
图1
图2
图3
图4
图5
Common Methods
private ClientContext CreateClientContext()
{
NetworkCredential credential = new NetworkCredential(USERNAME, PASSWORD, DOMAIN);
ClientContext context = new ClientContext(ROOTPATH);
context.Credentials = credential;
return context;
}
Create
ClientContext spContext = CreateClientContext();
Web website = spContext.Web;
Folder folder = website.GetFolderByServerRelativeUrl(LIBRARYPATH);
spContext.Load(website);
spContext.Load(folder);
spContext.Load(folder.Files);
spContext.ExecuteQuery();
FileCreationInformation file = new FileCreationInformation();
file.Content = FileUpload1.FileBytes;
file.Url = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
folder.Files.Add(file);
spContext.ExecuteQuery();
Read
ClientContext spContext = CreateClientContext();
Web website = spContext.Web;
Folder DocLib = website.GetFolderByServerRelativeUrl(LIBRARYPATH);
spContext.Load(website);
spContext.Load(DocLib);
spContext.Load(DocLib.Files);
spContext.ExecuteQuery();
GridView1.DataSource = DocLib.Files;
GridView1.DataBind();
Update
ClientContext spContext = CreateClientContext();
Web website = spContext.Web;
Microsoft.SharePoint.Client.File file = website.GetFileByServerRelativeUrl(HiddenField1.Value);
List docLib = spContext.Web.Lists.GetByTitle("测试库");
spContext.Load(website);
spContext.Load(docLib);
spContext.Load(file);
spContext.Load(file.ListItemAllFields);
spContext.ExecuteQuery();
Microsoft.SharePoint.Client.ListItem item = docLib.GetItemById(file.ListItemAllFields.Id);
spContext.Load(item);
spContext.Load(item.File);
item.File.CheckOut();
item["Title"] = new Random().Next(10000,99999).ToString();
item.Update();
item.File.CheckIn(DateTime.Now.ToString(), CheckinType.OverwriteCheckIn);
spContext.ExecuteQuery();
Delete
ClientContext spContext = CreateClientContext();
Web website = spContext.Web;
Microsoft.SharePoint.Client.File file = website.GetFileByServerRelativeUrl(HiddenField1.Value);
spContext.Load(website);
spContext.Load(file);
spContext.Load(file.ListItemAllFields);
spContext.ExecuteQuery();
file.DeleteObject();
spContext.ExecuteQuery();