Sandeep's Blog: This blog is no longer updated, please visit http://sandeepnakarmi.com.np for latest posts

September 30, 2009

Host WCF Service in SharePoint

Filed under: Sharepoint 2007 — Tags: , , — sandeep nakarmi @ 6:57 AM

Recently, I had been working on how to get a WCF service hosted in SharePoint. The requirement was to host a WCF service in SharePoint and a custom webpart would access the service. So in this post, I will illustrate how to host WCF in SharePoint.

Download SourceCode

Environment:

  • Microsoft SharePoint Server 2007
  • Visual Studio 2008
  • Visual Studio Extensions for WSS 3.0 v1.3 March CTP

1)      First let’s create a WCF service and its implementation. For this, create a project of type WCF Service Library. Name it SPService. This will create a default interface “IService.cs” and its implementation “Service.cs”. 

2)      Delete the defaut IService.cs and Service.cs files. 

3)      Add a new item of type WCF Service named SPService

4)      Modify the ISPService interface as shown below.

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

namespace SPService
{
    // NOTE: If you change the interface name "ISPService" here, you must also update the reference to "ISPService" in App.config.
    [ServiceContract]
    public interface ISPService
    {
        [OperationContract]
        string SayHello(string name);
    }
}

5) Modify SPService class as shown below.

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Activation;

namespace SPService
{
    // NOTE: If you change the class name "SPService" here, you must also update the reference to "SPService" in App.config.
    [AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
    public class SPService : ISPService
    {
        #region ISPService Members

        public string SayHello(string name)
        {
            return string.Concat("Hello ",name);
        }

        #endregion
    }
}

6) Modify the web.config file as shown below.  

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicBinding">
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Ntlm" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    <services>
      <service behaviorConfiguration="NewBehavior" name="SPService.SPService">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicBinding"
          name="basicBindingEndPoint" contract="SPService.ISPService" />
<!--<host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/SPService" />
          </baseAddresses>
        </host>-->      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="NewBehavior">
          <serviceDebug />
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

7)      Sign the project .

sign the project  

8)      Now run the project. This will bring up the WCF Test Client wizard. Test remote method by invoking the method. It should respond you as shown below.

WCF Test Client

WCF Test Client

9)      Now create a SharePoint project of template type Empty. Name it “SharePoint.WSP”. Select the option to Deploy it to GAC.

 GAC 

10)   Create the folders “RootFiles”, “ISAPI”, “SPService” in the structure as shown below. We will host the service in the folder “SPService”.

Soln

11)    Rename the “App.config” file in project SPService to “web.config”. Now in project, SharePoint.WSP, select the folder SPService and select to add an existing item. Navigate to web.config file and add it as a link.

 web config link 

12)   Similarly, add a link to assembly SPService.dll also.

 assembly link 

13)   Then in folder SPService, add an item of type “SPService.svc”. Modify the file to following. 

<%@ Assembly Name="SPService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ee2ed923e46a9fcd" %>
<%@ ServiceHost Service="SPService.SPService,SPService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ee2ed923e46a9fcd" %>

You can retrieve the full assembly signature using a reflector.

 reflector 

14)   Go to the WSP view (View – > Other Windows -> WSP View). The manifest.xml file should look like below.

 manifest 

15)   Now set site url in the properties of project SharePoint.WSP where the solution will be deployed. Then deploy the solution.

prop 

16)    Now try to access the service with the url http://sandeep-pc/_vti_bin/spservice/spservice.svc . At this point you may receive an VirtualPath error like below.

 err 

Exception: System.ArgumentException: virtualPath
at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result) 

at Microsoft.SharePoint.ApplicationRuntime.SPRequestModule.IsExcludedPath(Stri­ng virtualPath) 
at Microsoft.SharePoint.ApplicationRuntime.SPVirtualPathProvider.FileExists(St­ring virtualPath) 
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceA­vailable(String normalizedVirtualPath) 
at System.ServiceModel.ServiceHostingEnvironment.EnsureServiceAvailableFast(St­ring relativeVirtualPath)
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.HandleRequest()
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.BeginRequest() 
at System.ServiceModel.Activation.HttpHandler.ProcessRequest(HttpContext context)
 

The problem here is that SPVirtualPathProvider isn’t coded to handle URLs that start with ‘~’;

        See workaround references for this:

17)    As a workaround, follow the procedure below.  

18)   Add a folder named WCFSupport, in the project SharePoint.WSP. In this folder, add a new class file named “WCFVirtualPathProvider” and add the following lines of code.

class WCFVirtualPathProvider : VirtualPathProvider
    {
        public override string CombineVirtualPaths(string basePath, string relativePath)
        {
            return Previous.CombineVirtualPaths(basePath, relativePath);
        }

        public override System.Runtime.Remoting.ObjRef CreateObjRef(Type requestedType)
        {
            return Previous.CreateObjRef(requestedType);
        }

        public override bool DirectoryExists(string virtualDir)
        {
            return Previous.DirectoryExists(virtualDir);
        }

        public override bool FileExists(string virtualPath)
        {
            // Patches requests to WCF services: That is a virtual path ending with ".svc"     
            string patchedVirtualPath = virtualPath;
            if (virtualPath.StartsWith("~", StringComparison.Ordinal) &amp;&amp;
              virtualPath.EndsWith(".svc", StringComparison.InvariantCultureIgnoreCase))
            {
                patchedVirtualPath = virtualPath.Remove(0, 1);
            }
            return Previous.FileExists(patchedVirtualPath);
        }

        public override System.Web.Caching.CacheDependency GetCacheDependency(string virtualPath,
                   System.Collections.IEnumerable virtualPathDependencies, DateTime utcStart)
        {
            return Previous.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
        }

        public override string GetCacheKey(string virtualPath)
        {
            return Previous.GetCacheKey(virtualPath);
        }

        public override VirtualDirectory GetDirectory(string virtualDir)
        {
            return Previous.GetDirectory(virtualDir);
        }

        public override VirtualFile GetFile(string virtualPath)
        {
            return Previous.GetFile(virtualPath);
        }

        public override string GetFileHash(string virtualPath, System.Collections.IEnumerable virtualPathDependencies)
        {
            return Previous.GetFileHash(virtualPath, virtualPathDependencies);
        }

        protected override void Initialize()
        {
            base.Initialize();
        }
    }

19)   Create another class file named “WCFVPPRegModule” and add the following lines of code.

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Hosting;

namespace SharePoint.WSP.WCFSupport
{
    class WCFVPPRegModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {
            // do nothing
        }

        public void Init(HttpApplication context)
        {
            if (!wcfProviderInitialized)
            {
                lock (locker)
                {
                    WCFVirtualPathProvider wcfVPP = new WCFVirtualPathProvider();
                    HostingEnvironment.RegisterVirtualPathProvider(wcfVPP);
                    wcfProviderInitialized = true;
                }
            }
        }

        #endregion

        static bool wcfProviderInitialized = false;
        static object locker = new object();
    }
}

 
20)    Now after we have created the HttpModule, we need to register this in the web.config file of the root web application. This can be done manually or by creating a feature receiver which will apply the modification to the web.config file. I am going to use the later one. These feature receiver will be scoped at WebApplication and enabling this feature will apply the necessary modification to get the service running.  

21)   Add a new class file named “WCFSupportReceive.csr” in the folder “WCFSupport” and change it to below.

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Security;

namespace SharePoint.WSP.WCFSupport
{
    [Guid("1860F007-6E2B-4a95-A8B6-371AB8F6B012")]
    class WCFSupportReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
            if (webApp != null)
            {
                foreach (ModificationEntry entry in Entries)
                {
                    webApp.WebConfigModifications.Add(CreateModification(entry.Name, entry.XPath, entry.Value));
                }
                SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
            }      
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
            if (webApp != null)
            {

                foreach (ModificationEntry entry in Entries)
                {
                    webApp.WebConfigModifications.Remove(CreateModification(entry.Name, entry.XPath, entry.Value));
                }

                SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
            }    
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties){}

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties){}
      
        private struct ModificationEntry
        {
            public string Name;
            public string XPath;
            public string Value;
            public ModificationEntry(string Name, string XPath, string Value)
            {
                this.Name = Name;
                this.XPath = XPath;
                this.Value = Value;
            }
        }

private ModificationEntry[] Entries = {
              new ModificationEntry(
                  "add[@name='WCFVPPRegModule']",
                   "configuration/system.web/httpModules",
                   @"<add name=""WCFVPPRegModule"" type=""SharePoint.WSP.WCFSupport.WCFVPPRegModule,SharePoint.WSP, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1948038ea0d4e8e4"" />"
                   )
            };

        public SPWebConfigModification CreateModification(string Name, string XPath, string Value)
        {
            SPWebConfigModification modification = new SPWebConfigModification(Name, XPath);
            modification.Owner = WebConfigModificationOwner;
            modification.Sequence = 0;
            modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
            modification.Value = Value;
            return modification;

        }
        private const string WebConfigModificationOwner = "SharePoint.WSP";
    }
}

Note: The ModificationEntry[] is used to define the set of configurational changes needed to be made to web.config file. For now, we just need to register a http module, so there is just one entry defined. Use reflector to find the full signed signature of the assembly. Make sure that the PublicKeyToken matches to that of the assembly.

22)   Then go to WSP View (View – > Other Windows-> WSP View). This is how it looks in WSP View.

 wsp 

23)   Change the feature.xml of the WCFSupportReceiver as shown below.

<?xml version="1.0" encoding="utf-8"?>
<Feature Id="1860f007-6e2b-4a95-a8b6-371ab8f6b012"
         Title="WCFSupportReceiver"
         Description="Enable WCFSupport for SPService"
         Scope="WebApplication"
         Version="1.0.0.0"
         Hidden="FALSE"
         ReceiverAssembly="SharePoint.WSP, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1948038ea0d4e8e4"
         ReceiverClass="SharePoint.WSP.WCFSupport.WCFSupportReceiver"
         DefaultResourceFile="core"
         xmlns="http://schemas.microsoft.com/sharepoint/">
  <ElementManifests />
</Feature>

The key things to note here are:

  • The feature is scoped at WebApplication since we are making change in the web.config file of the web application. Also this means that in each web application, this feature has to be activated in order to acecess WCF Service.
  • Use the reflector to get the full assembly signature for the ReceiverAssembly. 

24)   Now everything set, deploy the project. Go to “Manage Web Application Features” of the web application into which the solution was deployed. Activate the WCFSupportFeaure feature if it  is not yet activated. You can also verify this by opening web.config file of web application and see for the entry for “WCFSupportReceiver”.

 config

 25)   Navigate to the url again: http://sandeep-pc/_vti_bin/spservice/spservice.svc .You should see a response like below.

 25 

26)   So the service has been hosted. To test the service, following the procedures below.

  1. Create a console application.
  2. Add the service reference to the above hosted service.
  3. Modify the client code to the following.

using System;
using System.Collections.Generic;
using System.Text;

namespace TestClient
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Service.SPServiceClient client = new TestClient.Service.SPServiceClient();
                string response = client.SayHello("sandeep");

                Console.WriteLine(string.Format("Response from server: {0}", response));
            }
            catch (Exception exc)
            {
                Console.WriteLine(string.Format("Error:{0}", exc.Message));
            }
            Console.ReadLine();
        }
    }
}

This is the output of the client application.

 output

 I would suggest you to have a look at the following references that I went through to get this done.

References:

Advertisement

3 Comments »

  1. I don’t know If I said it already but …Great site…keep up the good work. :) I read a lot of blogs on a daily basis and for the most part, people lack substance but, I just wanted to make a quick comment to say I’m glad I found your blog. Thanks, :)

    A definite great read..Jim Bean

    Comment by JimmyBean — October 1, 2009 @ 3:48 PM

  2. If anyone has a link to a similar procedure for Sharepoint 2010, please post it here. Would the WCF service be hosted as a Sandbox Solution, a Farm Solution, or a Feature? Thank you!

    Comment by Eric Rangell — May 2, 2011 @ 1:33 PM

  3. I found the answer in the book: Microsoft SharePoint 2010: Building Solutions for SharePoint 2010 (Books for Professionals by Professionals) by Sahil Malik. In Chapter 5 he walks through deployment of a WCF service in SP2010. The service is deployed to the GAC using the Advanced tab of the Package.

    Comment by Eric Rangell — May 3, 2011 @ 5:24 PM


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

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 )

Connecting to %s

Theme: Shocking Blue Green. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.