LINQ to SharePoint with WCF 4.0

Objective

How could we perform CRUD operations on SharePoint 2010 List from a WCF Service? Assume we need to create a WCF Service and that service will perform CRUD operation on SharePoint 2010 list. We are going to see that in this article.

Flow Diagram

clip_image001

Now we will follow the below steps to perform all above operations.

Step 1: Setting up the SharePoint list

We have a custom list

1. Name of the list is Test_Product.

2. Columns of the list is as below ,

clip_image003

3. There are two items in the list

clip_image005

4. URL of the SharePoint site is

http://dhananjay-pc/my/personal/Test1

Now we will access the SharePoint site on above URL.

Step 2 Creating WCF Service

Now we will create a WCF Service. WCF Service will have four operation contracts for CRUD operation on list.

To create WCF service, open visual studio and from WCF tab select WCF Service application.

clip_image007

Now to make sure that we would able to use SPLinq or LINQ to SharePoint we need to change the target framework and Platform target

So to do those follow as below,

1. Right click and click on Properties of WCF Service

clip_image008

2. Click on the Build tab and change Platform Target to Any CPU.

clip_image010

3. Click on the Application tab and change the Target framework type to .Net Framework 3.5

clip_image012

Now we need to create DataContext class of SharePoint list such that we can perform LINQ against that class to perform CRUD operation. To create context class we need to perform below steps.

1. Open the command prompt and change directory to

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN

Type command CD C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN

clip_image014

2. Now we need to create the class for corresponding list definitions.

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN> spme

tal.exe /web:http://dhananjay-pc/my/personal/Test1 /namespace:nwind /code:Product.cs

In above command we are passing few parameters to spmetal.exe, they are as below

a. /web:Url

Here we need to provide URL of SharePoint site

/web:http://dhananjay-pc/my/personal/Test1 /

://dhananjay-pc/my/personal/Test1 / is URL of SharePoint site, I created for myself. You need to provide your SharePoint site URL here.

b. /namespace:nwind

This would be the namespace under which class of the list will get created. In my case name of the namespace would be nwind.

c. /code:Product.cs

This is the file name of the generated class. Since we are giving name Product for the file then class generated will be ProductDataContext

The classes default gets saved in the same folder with SPMetal.exe. So to see where the class got created we need to navigate to folder

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN

Add created class to the WCF Service project

Now add this class to the project. To do this, right click on the WCF Service project and select Add existing item. Then browse to above path and select Product.cs

Host the WCF Service in IIS

To work with SPLInq in WCF service, we need to host the service in IIS with the same application pool SharePoint is running.

See the below link for step by step explanation on how to host WCF 4.0 Service in IIS 7.5

http://dhananjaykumar.net/2010/09/07/walkthrough-on-creating-wcf-4-0-service-and-hosting-in-iis-7-5/

Only we need to make sure that,

Hosted WCF service is sharing the same application pool with SharePoint.

clip_image015

Select the Application pool to SharePoint-80

Create Contracts

We need to create DataContract or Data Transfer object. This class will represent the Product Data context class (We generated this class in previous step) 0

Create Data Contract,

[DataContract]
 public class ProductDTO
 {
 [DataMember]
 public string ProductName;
 [DataMember]
 public string ProductId;
 [DataMember]
 public string ProductPrice;
 }

Add References to work with LINQ to SharePoint

Microsoft.SharePoint

Microsoft.SharePoint.Linq

Right click on Reference and select Add Reference. To locate Microsoft.SharePoint and Microsoft.SharePoint.Linq dll browse to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI. All the SharePoint dll are here in this location.

Add the namespace

clip_image016

Nwind is the name of the namespace of the data context class we created in previous steps. We need to make sure that we have added Product class to the WCF Service application project as Add an Existing item.

Create Service Contract

We need to create Service contract. There would be four operation contracts each for one operation on Sharepoint list.

IService1.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.ServiceModel.Description;

namespace WcfService1
{
 [ServiceContract ]
 public  interface IService1
 {

[OperationContract]
 List<ProductDTO> GetProduct();

[OperationContract]
 bool InsertProduct(ProductDTO product);

[OperationContract]
 bool UpdateProduct(ProductDTO product);

[OperationContract]
 bool DeleteProduct(ProductDTO product);

 }

In above code

1. Creating instance of ProductDataContext.

2. Using LINQ to SharePoint retrieving all the list items.

3. Creating instance of ProductDTO class with values fetched from SharePoint list

4. Adding the instance of ProductDTO class in List of ProductDTO.

5. Returning list of ProductDTO

Inserting an element in List

 public bool InsertProduct(ProductDTO product)
 {
 try
 {
 using(ProductDataContext context = new ProductDataContext("<a href="http://dhananjay-pc/my/personal/Test1">http://dhananjay-pc/my/personal/Test1</a>"))
 {
 EntityList<Test1_ProductItem> products = context.GetList<Test1_ProductItem>("Test1_Product");
 Test1_ProductItem itemToInsert = new Test1_ProductItem()
 {
 ProductId = product.ProductId ,
 ProductName = product.ProductName ,
 ProductPrice = Convert.ToDouble(product.ProductPrice)
 };
 products.InsertOnSubmit(itemToInsert);
 context.SubmitChanges();
 return true;
 }
 }
 catch (Exception ex)
 {
 return false;
 }

}

In above code

1. Boolean is being returned. If item will get saved successful then true will return by the service else false.

2. Instance of ProductDataContext being created and submitchanges() will be called on instance of ProductDataContext.

3. Instance of Test_ProductItem is being created and we are passing values from ProductDTO to create instance of Test_ProductItem. Point we need to note here is that Test_Product is name of the SharePoint list.

4. Calling InsertOnSubmit() to submit a list to item to get inserted.

Updating an Element in the List

 public bool UpdateProduct(ProductDTO product)
 {
 try
 {
 using (ProductDataContext context = new ProductDataContext("<a href="http://dhananjay-pc/my/personal/Test1">http://dhananjay-pc/my/personal/Test1</a>"))
 {
 var itemToUpdate = (from r in context.Test1_Product where r.ProductId == product.ProductId select r).First();
 itemToUpdate.ProductName = product.ProductName;
 itemToUpdate.ProductPrice = Convert.ToDouble(product.ProductPrice);
 context.SubmitChanges();
 return true;
 }
 }
 catch(Exception ex)
 {
 return false;
 }

 }

In above code

1. We are fetching list item to be updated on basis of ProductId of ProductDTO.

2. Assigning the new values

3. Performing the submitchnages on instance of ProductContext class.

Deleting an Element from the List

 public bool DeleteProduct(ProductDTO product)
 {
 try
 {
 using (ProductDataContext context = new ProductDataContext("<a href="http://dhananjay-pc/my/personal/Test1">http://dhananjay-pc/my/personal/Test1</a>"))
 {
 EntityList<Test1_ProductItem> products = context.GetList<Test1_ProductItem>("Test1_Product");
 var itemToDelete = (from r in context.Test1_Product where r.ProductId == product.ProductId  select r).First();
 products.DeleteOnSubmit(itemToDelete);
 context.SubmitChanges();
 return true;
 }
 }
 catch (Exception ex)
 {
 return false;
 }
 }

In above code

1. We are fetching the list item to be deleted.

2. Calling DeleteOnSubmit() and passing the item to be deleted.

3. Calling SubmitChanges() on instance of ProductContext.

Modify the Web.Config

1. We will put Binding as basicHttpBinding.

2. In ServiceBehavior attribute , we will enable the servicemetadata

3. In ServiceBehavior , we will make IncludeserviceException as false.

4. We will configure MetadataExchnagePoint in the service

So, Now in Web.Config Service configuration will look like

 <system.serviceModel>
 <behaviors>
 <serviceBehaviors>

 <behavior name="MyBeh">
 <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->

 <serviceMetadata httpGetEnabled="true"/>
 <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
 <serviceDebug includeExceptionDetailInFaults="false"/>
 </behavior>
 </serviceBehaviors>
 </behaviors>
 <services>
 <service name="WcfService1.Service1"  behaviorConfiguration="MyBeh">
 <endpoint address="" binding="basicHttpBinding" contract="WcfService1.IService1"/>
 <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
 <host>
 <baseAddresses>
 <add baseAddress="<a href="http://localhost:8181/Service1.svc/&quot;/">http://localhost:8181/Service1.svc/"/</a>>
 </baseAddresses>
 </host>
 </service>
 </services>
 <!--<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>-->
 </system.serviceModel>

Now our service is created. We will be hosting this service in IIS as we discussed in previous step. From IIS we will browse to test whether service is up and running or not.

For reference, full source code for service implementation is as below ,

Service1.svc.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Microsoft.SharePoint.Linq;
using Microsoft.SharePoint;
using nwind;
namespace WcfService1
{

 public class Service1 : IService1
 {
 public  List<ProductDTO> GetProduct()
 {
 using (ProductDataContext context = new ProductDataContext("<a href="http://dhananjay-pc/my/personal/Test1">http://dhananjay-pc/my/personal/Test1</a>"))
 {

ProductDTO product;
 List<ProductDTO> lstProducts = new List<ProductDTO>();
 var result = from r in context.Test1_Product select r;
 foreach (var r in result)
 {

product = new ProductDTO { ProductId = r.ProductId, ProductName = r.ProductName, ProductPrice = r.ProductPrice.ToString () };

lstProducts.Add(product);
 }

&nbsp;

return lstProducts;
 }

 }
 public bool InsertProduct(ProductDTO product)
 {
 try
 {
 using(ProductDataContext context = new ProductDataContext("<a href="http://dhananjay-pc/my/personal/Test1">http://dhananjay-pc/my/personal/Test1</a>"))
 {
 EntityList<Test1_ProductItem> products = context.GetList<Test1_ProductItem>("Test1_Product");
 Test1_ProductItem itemToInsert = new Test1_ProductItem()
 {
 ProductId = product.ProductId ,
 ProductName = product.ProductName ,
 ProductPrice = Convert.ToDouble(product.ProductPrice)
 };
 products.InsertOnSubmit(itemToInsert);
 context.SubmitChanges();
 return true;
 }
 }
 catch (Exception ex)
 {
 return false;
 }

}
 public bool UpdateProduct(ProductDTO product)
 {
 try
 {
 using (ProductDataContext context = new ProductDataContext("<a href="http://dhananjay-pc/my/personal/Test1">http://dhananjay-pc/my/personal/Test1</a>"))
 {
 var itemToUpdate = (from r in context.Test1_Product where r.ProductId == product.ProductId select r).First();
 itemToUpdate.ProductName = product.ProductName;
 itemToUpdate.ProductPrice = Convert.ToDouble(product.ProductPrice);
 context.SubmitChanges();
 return true;
 }
 }
 catch(Exception ex)
 {
 return false;
 }

 }

public bool DeleteProduct(ProductDTO product)
 {
 try
 {
 using (ProductDataContext context = new ProductDataContext("<a href="http://dhananjay-pc/my/personal/Test1">http://dhananjay-pc/my/personal/Test1</a>"))
 {
 EntityList<Test1_ProductItem> products = context.GetList<Test1_ProductItem>("Test1_Product");
 var itemToDelete = (from r in context.Test1_Product where r.ProductId == product.ProductId  select r).First();
 products.DeleteOnSubmit(itemToDelete);
 context.SubmitChanges();
 return true;
 }
 }
 catch (Exception ex)
 {
 return false;
 }
 }

 }
}

Creating a Managed Application (Console client to consume Service)

Now we will create a new project by selecting console application as project type. Right click on the project and add a service reference. Give the URL of the WCF Service hosted in IIS.

We need to call the service to perform the CRUD operation on SharePoint list from the console client.

Program.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using ConsoleApplication1.ServiceReference1;
using System.Collections.Generic;
namespace ConsoleApplication1
{
 class Program
 {
 static void Main(string[] args)
 {
 try
 {
 Service1Client proxy = new Service1Client();

// Insertion
 ProductDTO productToInsert = new ProductDTO { ProductId = "99", ProductName = "Ball", ProductPrice = "700" };
 if (proxy.InsertProduct(productToInsert))
 Console.WriteLine("Inserted successfully ");
 else
 Console.WriteLine("Opps some problem in Insertion ");

// Update

ProductDTO productToUpdate = new ProductDTO { ProductId = "99", ProductName = "Ball for New game ", ProductPrice = "7000" };
 if (proxy.InsertProduct(productToInsert))
 Console.WriteLine("Updated  successfully ");
 else
 Console.WriteLine("Opps some problem in Updation ");

//Delete
 ProductDTO productToDelete = new ProductDTO { ProductId = "99" };
 if (proxy.InsertProduct(productToInsert))
 Console.WriteLine("Deleted  successfully ");
 else
 Console.WriteLine("Opps some problem in Deletion ");

&nbsp;

//Reterive

Console.WriteLine("Records are as below ");
 List<ProductDTO>  p = proxy.GetProduct().ToList();
 foreach (var r in p)
 {
 Console.WriteLine(r.ProductName + r.ProductId + r.ProductPrice);
 }
 Console.ReadKey(true);
 }
 catch (Exception ex)
 {
 Console.WriteLine(ex.Message);
 }

&nbsp;

Console.ReadKey(true);
 }

 }
}

Calling service is very simple. Just we need to create proxy of the service and call the methods on the service as normal function with required parameter.

Output

clip_image018

One response to “LINQ to SharePoint with WCF 4.0”

  1. Great article but I have a question on InsertOnSubmit.

    What if you have a Lookup field on Product which is for example ProductType that looks up on ProductType List how would I do this now?

    EntityList products = context.GetList(“Test1_Product”);
    Test1_ProductItem itemToInsert = new Test1_ProductItem()
    {
    ProductId = product.ProductId ,
    ProductName = product.ProductName ,
    ProductPrice = Convert.ToDouble(product.ProductPrice)
    ProductType = ??????????
    };
    products.InsertOnSubmit(itemToInsert);
    context.SubmitChanges();

    as ProductType will be or ProductTypeItem type.

Leave a comment

Create a website or blog at WordPress.com