Thursday, December 29, 2011

To create a service reference to access SharePoint lists

  1. Open or create a Visual Studio project.
  2. In Solution Explorer, right-click the References node, and then click Add Service Reference.
  3. In the Address box, type the URL to the target site and append /_vti_bin/ListData.svc. For example, the address for the site intranet.wingtip.com would be http://intranet.wingtip.com/_vti_bin/ListData.svc.
  4. Change the default name in the Namespace box from ServiceReference1 to something more appropriate, such as WingtipSite.
  5. Click OK to create proxy classes, including a data context and entity classes for the lists that you want to access.
  6. Begin writing code against these proxy classes, which provide strongly typed access to the columns of SharePoint list items.
Programming with the DataContext Class
When you add a service reference to your project, the WCF Data Services support can inspect the target site and build a DataContext class that exposes a property for each list in the site. For example, if the target site has a list named "Developers", the DataContext object exposes a property named Developers that holds a collection of items that you can enumerate with a simple foreach loop. Be aware that you must set the proper credentials for the DataContext object before you make the first call to a SharePoint site.

WingtipDevSiteDataContext dc = 
  new WingtipDevSiteDataContext(new 
  Uri("http://intranet.wingtip.com/_vti_bin/ListData.svc/"));

dc.Credentials = System.Net.CredentialCache.DefaultCredentials;

var source = dc.Developers;

lstDevelopers.Items.Clear();
foreach (var dev in source) {
    string devName = dev.FirstName + " " + dev.LastName;
    lstDevelopers.Items.Add(devName);
}
Adding New List Items 
When you add a service reference to ListData.svc, in addition to generating a proxy class for the DataContext object, the WCF support also creates an 
entity class for each list. For example, if the target site has a list named "Developers", the creation of a service reference creates an entity class named DevelopersItem.
This entity class provides an easy way to add items to a SharePoint list. You use the entity class to create and initialize an object that holds the data for a new SharePoint 
list item. Next, you pass the object to one of the Add methods in the DataContext object. For example, if you have a list named "Developers", 
the DataContext object contains a method named AddToDevelopers. After you call the Add method with a new instance of the entity class, you can call the SaveChanges method on the 
DataContext object to call across the network and create a new item inside a SharePoint list.

No comments:

Post a Comment