Saturday, April 14, 2012

WCF Hosting in SharePoint environment

Creating the WCF service and consuming in SharePoint application is now improved.Later version we need to create the WCF service and hosting it in IIS server as stand alone application. From this we need to create the "Proxy Class" using the tool wsdl or svcutility to be used on client application. But this approach will not be so user friendly when it comes to SharePoint. Again the hosting endpoint is the static one. Maintainability and back up of the webapplication or service application in SharePoint is must not be complex. Recent improvement has been done in WCF using Factory method.This will get rid of the static end point problem.It automatically set the dynamic end point in run time. Create the SharePoint empty project. Select the "SharePoint Mapped" folder. Under ISAPI folder you'll the folder.Inside this folder create the "text file or xml file". Copy the below line in to this txt or xml file.
<%@ServiceHost Language="C#" Debug="true"
    Service="WCFHosting.Layouts.WCFHosting.ListService, $SharePoint.Project.AssemblyFullName$"
    Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressBasicHttpBindingServiceHostFactory, Microsoft.SharePoint.Client.ServerRuntime, Version=, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
Rename this file's extension as .svc Under the same folder create the code file type "Interface" and implement all the methods on the same file. For simplicity I created the below class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Runtime.Serialization;
using Microsoft.SharePoint.Client.Services;
using System.ServiceModel.Activation;

namespace WCFHosting.Layouts.WCFHosting
    interface ServiceInterface
        List GetAllRecords();
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class ListService:ServiceInterface
        public List GetAllRecords()
            List obj = new List();
            SPListRecord record = new SPListRecord();
            record.title = "SP"; = "Pandian"; "Mumbai";
            return obj;
public class SPListRecord
    public string title{get;set;}
    public string city {get;set;}
    public string name{get;set;}

Now we need to do important step to enable dynamic endpoint by sharepoint. Now right click on your "Project" and choose the "Unload project".Edit the Project file(.csproj). Inside the PropertyGroup place this tag
Now reload your WCF project,rebuild and deploy it. Now we have the full pledged and SharePoint compatible WCF service and it can be host anywhere in the Farm and it can be consumed in Application Page,Visual WebPart and InfoPath forms.