代码段:从客户端上的外部列表中获取项数据

上次修改时间: 2010年4月19日

适用范围: SharePoint Server 2010

本文内容
说明
必备组件
使用该示例

说明

以下代码段演示如何从使用 SharePoint 客户端对象模型的客户端计算机检索外部列表中的列表项数据。

重要注释重要说明

如果您尝试从外部列表中使用 ListItem 数据的"默认"ClientContext.Load,则会收到以下错误:"给定关键字不在字典中"。您需要在 CamlQuery 中以及 ClientContext.Load 方法中明确指定所需的字段。

必备组件

  • 服务器上安装了 Microsoft SharePoint Server 2010 或 Microsoft SharePoint Foundation 2010。

  • 服务器上至少有一个外部列表。

  • 客户端计算机上安装了 Microsoft Office Professional Plus 2010 和 Microsoft .NET Framework 3.5。

  • Microsoft Visual Studio。

使用该示例

  1. 在客户端计算机上启动 Visual Studio,并创建 C# 控制台应用程序项目。在创建项目时,选择".NET Framework 3.5"。

  2. 从"视图"菜单中,单击"属性页"以显示项目属性。

  3. 在"生成"选项卡中,为"目标平台"选择"任何 CPU"。

  4. 关闭项目属性窗口。

  5. 在"解决方案资源管理器"的"引用"下,移除除 System 和 System.Core 之外的所有项目引用。

  6. 将以下引用添加到项目中:

    1. Microsoft.SharePoint.Client

    2. Microsoft.SharePoint.Client.Runtime

    3. System.Data.Linq

    4. System.XML

  7. 用此过程末尾列出的代码替换 Program.cs 中自动生成的代码。

  8. 将 <TargetSiteUrl> 和 <TargetListName> 的值替换为有效值。

  9. 保存该项目。

  10. 编译并运行该项目。

using System;
using Microsoft.SharePoint.Client;
using System.Linq.Expressions;
using System.Collections.Generic;
using System.Xml;
using System.IO;
using System.Text;
using System.Globalization;

namespace Microsoft.SDK.Sharepoint.Samples
{
    /// <summary>
    /// This example shows how to retrieve list item data 
    /// from an external list.
    /// 
    /// You'll need to explicitly specify the field data in both
    /// the CAML query and also ClientContext.Load.
    /// </summary>
    class Program
    {
        // Note: Replace these with your actual Site URL and List name.
        private static string TargetSiteUrl = "<TargetSiteUrl>";
        private static string TargetListName = "<TargetListName>";

        /// <summary> 
        /// Example to show using CSOM to retrieve external List data.        
        /// </summary>        
        static void Main(string[] args)
        {
            ClientContext clientContext = new ClientContext(TargetSiteUrl);

            List externalList = clientContext.Web.Lists.GetByTitle(
                TargetListName);

            // To properly construct the CamlQuery and 
            // ClientContext.LoadQuery,
            // we need some View data of the Virtual List.
            // In particular, the View will give us the CamlQuery 
            // Method and Fields.
            clientContext.Load(
                externalList.Views,
                viewCollection => viewCollection.Include(
                    view => view.ViewFields,
                    view => view.HtmlSchemaXml));

            // This tells us how many list items we can retrieve.
            clientContext.Load(clientContext.Site,
                s => s.MaxItemsPerThrottledOperation);

            clientContext.ExecuteQuery();

            // Let's just pick the first View.
            View targetView = externalList.Views[0];
            string method = ReadMethodFromViewXml(
                targetView.HtmlSchemaXml);
            ViewFieldCollection viewFields = targetView.ViewFields;

            CamlQuery vlQuery = CreateCamlQuery(
                clientContext.Site.MaxItemsPerThrottledOperation,
                method,
                viewFields);

            Expression<Func<ListItem, object>>[] listItemExpressions =
                CreateListItemLoadExpressions(viewFields);

            ListItemCollection listItemCollection =
                externalList.GetItems(vlQuery);

            // Note: Due to limitation, you currently cannot use 
            // ClientContext.Load.
            //       (you'll get InvalidQueryExpressionException)
            IEnumerable<ListItem> resultData = clientContext.LoadQuery(
                listItemCollection.Include(listItemExpressions));

            clientContext.ExecuteQuery();

            foreach (ListItem li in resultData)
            {
                // Now you can use the ListItem data!

                // Note: In the CamlQuery, we specified RowLimit of 
                // MaxItemsPerThrottledOperation.
                // You may want to check whether there are other rows 
                // not yet retrieved.                
            }
        }

        /// <summary>
        /// Parses the viewXml and returns the Method value.
        /// </summary>        
        private static string ReadMethodFromViewXml(string viewXml)
        {
            XmlReaderSettings readerSettings = new XmlReaderSettings();
            readerSettings.ConformanceLevel = ConformanceLevel.Fragment;

            XmlReader xmlReader = XmlReader.Create(
                new StringReader(viewXml), readerSettings);
            while (xmlReader.Read())
            {
                switch (xmlReader.NodeType)
                {
                    case XmlNodeType.Element:
                        if (xmlReader.Name == "Method")
                        {
                            while (xmlReader.MoveToNextAttribute())
                            {
                                if (xmlReader.Name == "Name")
                                {
                                    return xmlReader.Value;
                                }
                            }
                        }
                        break;
                }
            }

            throw new Exception("Unable to find Method in View XML");
        }

        /// <summary>
        /// Creates a CamlQuery based on the inputs.
        /// </summary>        
        private static CamlQuery CreateCamlQuery(
            uint rowLimit, string method, ViewFieldCollection viewFields)
        {
            CamlQuery query = new CamlQuery();

            XmlWriterSettings xmlSettings = new XmlWriterSettings();
            xmlSettings.OmitXmlDeclaration = true;

            StringBuilder stringBuilder = new StringBuilder();
            XmlWriter writer = XmlWriter.Create(
                stringBuilder, xmlSettings);

            writer.WriteStartElement("View");

            // Specifies we want all items, regardless of folder level.
            writer.WriteAttributeString("Scope", "RecursiveAll");

            writer.WriteStartElement("Method");
            writer.WriteAttributeString("Name", method);
            writer.WriteEndElement();  // Method

            if (viewFields.Count > 0)
            {
                writer.WriteStartElement("ViewFields");
                foreach (string viewField in viewFields)
                {
                    if (!string.IsNullOrEmpty(viewField))
                    {
                        writer.WriteStartElement("FieldRef");
                        writer.WriteAttributeString("Name", viewField);
                        writer.WriteEndElement();  // FieldRef
                    }
                }
                writer.WriteEndElement();  // ViewFields
            }

            writer.WriteElementString(
                "RowLimit", rowLimit.ToString(CultureInfo.InvariantCulture));

            writer.WriteEndElement();  // View

            writer.Close();

            query.ViewXml = stringBuilder.ToString();

            return query;
        }

        /// <summary>
        /// Returns an array of Expression used in 
        /// ClientContext.LoadQuery to retrieve 
        /// the specified field data from a ListItem.        
        /// </summary>        
        private static Expression<Func<ListItem, object>>[]
            CreateListItemLoadExpressions(
            ViewFieldCollection viewFields)
        {
            List<Expression<Func<ListItem, object>>> expressions =
                new List<Expression<Func<ListItem, object>>>();

            foreach (string viewFieldEntry in viewFields)
            {
                // Note: While this may look unimportant, 
                // and something we can skip, in actuality,
                //       we need this step.  The expression should 
                // be built with local variable.                
                string fieldInternalName = viewFieldEntry;

                Expression<Func<ListItem, object>>
                    retrieveFieldDataExpression =
                    listItem => listItem[fieldInternalName];

                expressions.Add(retrieveFieldDataExpression);
            }

            return expressions.ToArray();
        }
    }
}