WSS 3.0 Code Snippets – Accessing SharePoint List using Object Model and Web Services

Microsoft provides different methods to access the WSS 3.0 lists through the SharePoint Object Model APIs and SharePoint Web Services. It is recommended practice that if you are accessing the list in the same web application or site collection, preferred method should be object model for faster performance. If you are accessing the SharePoint list from another farm or different applications, you should use the web service for the better integration and interoperability.

Visual Studio 2005 had “Add Web Reference” option to reference the classic .NET web services. Visual Studio 2008 introduced the “Add Service Reference” option to add the WCF service reference. Visual Studio 2008 also supports adding the Web Service Reference through the advanced options for backward compatibility. The difference between Web Reference and a Service Reference are – a Web Reference is a wrapper over wsdl.exe for the classic .NET web services access in Microsoft.NET Framwork 2.0 and earliar and a Service Reference is a wrapper over svcutil.exe for the WCF services access in Microsoft.NET Framework 3.5 and later. Since MOSS 2007 is based on the Microsoft.NET 2.0 framework, it is recommended to use the classic web services (Microsoft.NET 1.x and 2.0 frameworks) wrapper over the WCF wrapper introduced in the Visual Studio 2008.

Following are the code snippets and intended to be used for the reference only. In most cases, it will provide the reference pattern to access the SharePoint List through different methods – the Object Model, Web Service, and WCF Service.

Method 1 – Access SharePoint List using SharePoint Object Model in Visual Studio 2005 and Visual Studio 2008

Code to access and read List Data ===

   1:  //Import Assemblies
   2:  using Microsoft.SharePoint;
   3:   
   4:  //Retrieve the links from the site collection list.
   5:  using (SPSite site = new SPSite(ConfigurationManager.AppSettings["IntranetUrl"]))
   6:  {
   7:      using (SPWeb web = site.RootWeb)
   8:      {
   9:          //Access the custom my links from the list and add to the group
  10:          SPList myLinkLists = web.Lists["My Links"];
  11:          SPQuery query = new SPQuery();
  12:          query.Query = "<Where><Contains><FieldRef Name='Sites'/><Value Type='MultiChoice'>" + location + "</Value></Contains></Where>";
  13:          
  14:          //Access the list through the CAML query
  15:          SPListItemCollection items = myLinkLists.GetItems(query);
  16:  
  17:          // Loop through the listitem collection and retrieve the data
  18:          foreach (SPListItem item in items)
  19:          {       
  20:              string title = item["Title"] != null ? item["Title"].ToString() : string.Empty; ;
  21:              string summary = item["Summary"] != null ? item["Summary"].ToString() : string.Empty;    
  22:          }
  23:      }
  24:  }

Method 2 – Access SharePoint List using SharePoint List Services and the WSDL Wrapper in Visual Studio 2005 and Visual Studio 2008

In VS 2005, Add the web service references through Project -> Web References -> Add Reference
In VS 2008, Add the web service references through Project -> Service References -> Add Reference -> Advanced Options -> Add Web Reference for backward compatability
Specify Web Service URL – SPListWebService – http://ServerName/_vti_bin/Lists.asmx

Web.Config ====

   1:  <configuration>
   2:    <configSections>
   3:      <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
   4:        <section name="SharePoint.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
   5:      </sectionGroup>
   6:    </configSections>
   7:    <applicationSettings>
   8:      <SharePoint.Properties.Settings>
   9:        <setting name="SharePoint_SPListWebService_Lists" serializeAs="String">
  10:          <value>http://ServerName/_vti_bin/lists.asmx</value>
  11:        </setting>
  12:      </SharePoint.Properties.Settings>
  13:    </applicationSettings>
  14:  </configuration>

Code to access and read List Service Data ===

   1:  //Import Assemblies
   2:  using SharePoint.SPListWebService;
   3:  using System.Xml;
   4:  
   5:  // Open the list service through the WSDL client
   6:  SPListWebService.Lists list = new SPListWebService.Lists();
   7:   
   8:  // Pass the Credentials
   9:  list.UseDefaultCredentials = false;
  10:  list.Credentials = new System.Net.NetworkCredential
  11:            (ConfigurationManager.AppSettings["IntranetListWebServiceServiceAccountId"],
  12:             ConfigurationManager.AppSettings["IntranetListWebServiceServiceAccountPassword"],
  13:             ConfigurationManager.AppSettings["IntranetListWebServiceServiceAccountDomain"]);
  14:  
  15:  // Query the list
  16:  XmlDocument camlDocument = new XmlDocument();
  17:  XmlNode queryNode = camlDocument.CreateElement("Query");
  18:  queryNode.InnerXml = "<Where><Eq><FieldRef Name='Sites'/><Value Type='MultiChoice'>" + location + "</Value></Eq></Where>";
  19:  XmlNode viewFieldsNode = camlDocument.CreateElement("ViewFields");
  20:  viewFieldsNode.InnerXml = "<FieldRef Name='Title' />" + "<FieldRef Name='Summary' />" + "<FieldRef Name='URL' />";
  21:  XmlNode queryOptionsNode = camlDocument.CreateElement("QueryOptions");
  22:  XmlNode resultNodes = list.GetListItems("My Links", "", queryNode, viewFieldsNode, "", queryOptionsNode, "");
  23:   
  24:  // Build the MyLinks menu
  25:  foreach (XmlNode node in resultNodes)
  26:  {
  27:     if (node.Name == "rs:data")
  28:     {
  29:         for (int i = 0; i < node.ChildNodes.Count; i++)
  30:         {
  31:             if (node.ChildNodes[i].Name == "z:row")
  32:             {
  33:                  string title = node.ChildNodes[i].Attributes["ows_Title"] != null ? node.ChildNodes[i].Attributes["ows_Title"].Value : string.Empty; ;
  34:                  string summary = node.ChildNodes[i].Attributes["ows_Summary"] != null ? node.ChildNodes[i].Attributes["ows_Summary"].Value : string.Empty;
  35:             }
  36:         }
  37:     }
  38:  }

Method 3 – Access SharePoint List using SharePoint List Services and the WCF Wrapper in Visual Studio 2008
In VS 2008, Add the WCF web service references through Project -> Service References -> Add Reference
Specify Web Service URL – SPListService – http://ServerName/_vti_bin/Lists.asmx

Web.Config ====

   1:  <configuration>
   2:    <system.serviceModel>
   3:      <bindings>
   4:        <basicHttpBinding>
   5:          <binding name="ListsSoap" closeTimeout="00:01:00" openTimeout="00:01:00"
   6:              receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"
   7:              bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
   8:              maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
   9:              messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
  10:              useDefaultWebProxy="true">
  11:            <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
  12:                maxBytesPerRead="4096" maxNameTableCharCount="16384" />
  13:            <security mode="TransportCredentialOnly">
  14:              <transport clientCredentialType="Ntlm" proxyCredentialType="Ntlm"/>
  15:            </security>
  16:          </binding>
  17:        </basicHttpBinding>
  18:      </bindings>
  19:      <client>
  20:        <endpoint address="http://ServerName/_vti_bin/Lists.asmx"
  21:            binding="basicHttpBinding" bindingConfiguration="ListsSoap"
  22:            contract="SPListService.ListsSoap" name="ListsSoap"
  23:            behaviorConfiguration="ListServiceBehavior"/>
  24:      </client>
  25:      <behaviors>
  26:        <endpointBehaviors>
  27:          <behavior name="ListServiceBehavior">
  28:            <clientCredentials>
  29:              <windows allowedImpersonationLevel="Impersonation"/>
  30:            </clientCredentials>
  31:          </behavior>
  32:        </endpointBehaviors>
  33:      </behaviors>
  34:    </system.serviceModel>
  35:  </configuration>

Code to access and read List Service Data ===

   1:  //Import Assemblies
   2:  using System.ServiceModel;
   3:  using SharePoint.SPListService;
   4:  using System.Xml;
   5:   
   6:  // Open the list service through the SvcUtil client
   7:  ListsSoapClient wsClient = new ListsSoapClient();
   8:  
   9:  // Pass the Credentials
  10:  wsClient.ClientCredentials.Windows.ClientCredential =
  11:           new System.Net.NetworkCredential
  12:              (ConfigurationManager.AppSettings["IntranetListWebServiceServiceAccountId"],
  13:               ConfigurationManager.AppSettings["IntranetListWebServiceServiceAccountPassword"],
  14:               ConfigurationManager.AppSettings["IntranetListWebServiceServiceAccountDomain"]);
  15:  wsClient.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
  16:  
  17:  // Open the connection to the web service
  18:  wsClient.Open();
  19:   
  20:  // Query the list
  21:  XmlDocument camlDocument = new XmlDocument();
  22:  XmlElement queryNode = camlDocument.CreateElement("Query");
  23:  queryNode.InnerXml = "<Where><Eq><FieldRef Name='Sites'/><Value Type='MultiChoice'>" + location + "</Value></Eq></Where>";
  24:  XmlElement viewFieldsNode = camlDocument.CreateElement("ViewFields");
  25:  viewFieldsNode.InnerXml = "<FieldRef Name='Title' />" + "<FieldRef Name='Summary' />" + "<FieldRef Name='URL' />";
  26:  XmlElement queryOptionsNode = camlDocument.CreateElement("QueryOptions");
  27:  XmlElement resultNodes = wsClient.GetListItems("My Links", "", queryNode, viewFieldsNode, "", queryOptionsNode, "");
  28:  
  29:  // Build the MyLinks menu
  30:  foreach (XmlNode node in resultNodes)
  31:  {
  32:     if (node.Name == "rs:data")
  33:     {
  34:         for (int i = 0; i < node.ChildNodes.Count; i++)
  35:         {
  36:             if (node.ChildNodes[i].Name == "z:row")
  37:             {
  38:                 string title = node.ChildNodes[i].Attributes["ows_Title"] != null ? node.ChildNodes[i].Attributes["ows_Title"].Value : string.Empty; ;
  39:                 string summary = node.ChildNodes[i].Attributes["ows_Summary"] != null ? node.ChildNodes[i].Attributes["ows_Summary"].Value : string.Empty;
  40:             }
  41:         }
  42:     }
  43:  }

Addtionally, following are online references on accessing list through the different mechanism in WsS 3.0 and MOSS 2007.

Writing CAML Queries For Retrieving List Items from a SharePoint List
http://sharepointmagazine.net/technical/development/writing-caml-queries-for-retrieving-list-items-from-a-sharepoint-list

Talk to SharePoint Through its Web Services
http://www.csharphelp.com/2007/6/talk-to-sharepoint-through-its-web-services/

Connecting to SharePoint 2007 Web Services using a Service Reference in Visual Studio 2008
http://petesullivan.spaces.live.com/blog/cns!96D0E96711D2A69E!187.entry

Calling SharePoint Lists Web Service Using WCF
http://blogs.msdn.com/kaevans/archive/2009/03/10/calling-sharepoint-lists-web-service-using-wcf.aspx

MOSS Web Services – Accessing Sharepoint List data
http://dotnetdreamer.com/2009/06/04/moss-web-services-accessing-sharepoint-list-data/

Retrieving SharePoint List Data using CAML
http://dotnetdreamer.com/2009/02/09/retrieving-sharepoint-list-data-using-caml/

Hope this will be useful. Have a wonderful holidays.

Advertisements
This entry was posted in SP2007 DEV. Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s