This topic has not yet been rated Rate this topic

Creating a Custom WCF Service in SharePoint Foundation

SharePoint 2010

Published: May 2010

This part of the walkthrough shows how to create a custom Windows Communication Foundation (WCF) service that allows users to revert list items to their previous versions. The version history of list items is not exposed through the other client APIs, and so this example creates a service that uses the server-side object model to provide this functionality to client applications.

The example shows how to create a custom WCF service in Microsoft Visual Studio 2010 as a Microsoft SharePoint Foundation project that you can deploy to any farm. In addition, because the SharePoint Foundation project type does not support WCF libraries by default, this example involves creating a WCF service library as an external project to generate the IService1 and Service1 .cs or .vb files for your project.

This example assumes that you completed the previous two parts of this walkthrough—Implementing the SharePoint Foundation REST Interface and Implementing the Client-Side Object Model—and created a Windows Forms Application that is used to implement the custom WCF service.

  1. To create a SharePoint Foundation project for the WCF service, open the ProjectTracker solution in Visual Studio. In Solution Explorer, click the solution. On the File menu, point to Add, and then click New Project. In the Installed Templates tab of the Add New Project dialog box, expand either the Visual Basic or Visual C# node, select SharePoint, select Empty SharePoint Project, and then type RevertService as the name of the project. Click OK.

  2. In the SharePoint Customization Wizard, verify that the correct local site is specified for debugging. Because sandboxed solutions do not support WCF services, select Deploy as a farm solution, and then click Finish.

  3. To create the external WCF project to obtain its IService1 and Service1 .cs or .vb files, click the ProjectTracker solution again, and follow the same procedure as in Step 1 to open the Add New Project dialog box. Expand either the Visual Basic or Visual C# node, select WCF, select WCF Service Library, type WcfService as the name, and then click OK.

  4. Copy the generated IService1 and Service1 files into the RevertService project. Because you no longer need the WCF Service Library project, you can remove it from the solution by right-clicking the WCF Service Library and clicking Remove.

  5. Add references in the RevertService project to the System.Runtime.Serialization and System.ServiceModel WCF assemblies, and to Microsoft.SharePoint, the main assembly of the server object model. Right-click the RevertService project, click Add Reference, and select each of these assemblies on the .NET tab.

  6. To add a reference to Microsoft.SharePoint.Client.ServerRuntime, which contains the service factories that are provided by SharePoint Foundation, use the Browse tab of the Add Reference box to navigate to the Microsoft.SharePoint.Client.ServerRuntime.dll file in %Windows%\assembly\GAC_MSIL\Microsoft.SharePoint.Client.ServerRuntime, select the DLL, and then click OK.

  7. To specify the contract of your custom WCF service in IService1.cs (or IService1.vb), replace the auto-generated service contract with the following interface definition, where the Revert method accepts the name of the list in which to revert changes and the ID of the item to revert.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
    
    namespace WcfService
    {
        [ServiceContract]
        public interface IRevert
        {
            [OperationContract]
            void Revert(string listName, int listItemId);
        }
    }
    
  8. Specify the implementation of the service by replacing the auto-generated code of Service1.cs (Service1.vb) with the following code. The example uses the SharePoint Foundation object model to retrieve the list by its name, to retrieve the item to revert by ID, and to check for the presence of item versions and revert them back by one version:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    using System.Text;
    
    namespace WcfService
    {
        using Microsoft.SharePoint.Client.Services;
        using System.ServiceModel.Activation;
        using Microsoft.SharePoint;
    
        [BasicHttpBindingServiceMetadataExchangeEndpointAttribute]
        [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
        public class RevertService : IRevert
        {
            public void Revert(string listName, int listItemId)
            {
                SPList oList = SPContext.Current.Web.Lists[listName];
    
                SPListItem oItem = oList.GetItemById(listItemId);
    
                if (oItem.Versions.Count > 1)
                {
                    oItem.Versions.Restore(1);
                }
            }
        }
    }
    

    In the previous example, the RevertService class has an attribute for binding, BasicHttpBindingServiceMetadataExchangeEndpointAttribute, which instructs the SharePoint Foundation service factory to automatically create a metadata exchange endpoint for the service.

  9. Now that the implementation of the service is ready, you can deploy the service to SharePoint Foundation. Right-click the RevertService project, point to Add, and click SharePoint Mapped Folder. In the Add SharePoint Mapped Folder dialog box, select ISAPI, and then click OK to map the ISAPI folder of the SharePoint Foundation hive to the RevertService project. If Visual Studio creates a RevertService subfolder in the ISAPI folder of the RevertService project, right-click the subfolder and click Remove to delete it.

  10. To create a registration file for your service in the ISAPI folder, click the ISAPI folder in your project, and on the Project menu, click Add New Item. Under Installed Templates, select General. Select Text File, name the file Revert.svc, and then click Add.

  11. Add the following service declaration to Revert.svc, which specifies the SharePoint Foundation factories and the namespace that contains them. In the example, MultipleBaseAddressBasicHttpBindingServiceHostFactory specifies the service factory for the SOAP type of web service. The service class declaration also specifies the name of the service class and uses a token to specify the strong name of the assembly.

    <%@ServiceHost Language="C#" Debug="true"
        Service="WcfService.RevertService, $SharePoint.Project.AssemblyFullName$"
        Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressBasicHttpBindingServiceHostFactory, Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    

    If you are creating the service in Visual Basic, specify VB instead of C# as the language, and in the Service attribute, include the name of your SharePoint Foundation project, as specified in step one, as follows:

    <%@ServiceHost Language="VB" Debug="true"
        Service="RevertService.WcfService.RevertService, $SharePoint.Project.AssemblyFullName$"
        Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressBasicHttpBindingServiceHostFactory, Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
    
  12. Because Visual Studio 2010 by default does not process the type of tokens used in the previous .svc file, you must add an additional instruction in the project file. Save all changes in your project, right-click the RevertService project, and then click Unload Project. Right-click the RevertService node again, click Edit RevertService.csproj or Edit RevertService.vbproj, and add a <TokenReplacementFileExtensions> tag as follows to the first property group in the .csproj or .vbproj file to enable processing of tokens in .svc file types.

    <?xml version="1.0" encoding="utf-8"?>
    <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
      <PropertyGroup>
        <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
        <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
        <SchemaVersion>2.0</SchemaVersion>
        <ProjectGuid>{F455078E-8836-403A-9E63-5E5F21B5F694}</ProjectGuid>
        <OutputType>Library</OutputType>
        <AppDesignerFolder>Properties</AppDesignerFolder>
        <RootNamespace>RevertService</RootNamespace>
        <AssemblyName>RevertService</AssemblyName>
        <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
        <FileAlignment>512</FileAlignment>
        <ProjectTypeGuids>{BB1F664B-9266-4fd6-B973-E1E44974B511};{14822709-B5A1-4724-98CA-57A101D1B079};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
        <SandboxedSolution>False</SandboxedSolution>
        <TokenReplacementFileExtensions>svc</TokenReplacementFileExtensions>
      </PropertyGroup>
    . . . .
    
  13. After you add the previous tag, save the project and close the .csproj file. In Solution Explorer, right-click the RevertService project, and then click Reload Project.

  14. To deploy the custom web service to SharePoint Foundation, in Solution Explorer, right-click the RevertService project, and then click Deploy. Visual Studio compiles the project’s code, builds a WSP file, and deploys the file to the front-end web server.

  15. To use the custom web service from your ProjectTracker client application, right-click the Service References node of the application in Solution Explorer, and then click Add Service Reference. In the Add Service Reference dialog box, type the URL of your custom WCF service in the Address box, and specify MEX as the standard name for the metadata exchange endpoint, as follows: http://Server/sites/SiteCollection/MyWebSite/_vti_bin/Revert.svc. Click Go to download the service information, and then click OK to add the reference.

  16. To add a Revert button in Form1 that implements the custom service, right-click the form title bar next to the Save button, and then select Button in the drop-down list that appears.

  17. In the Properties window for the button, set DisplayStyle to Text, and type Revert as the value for the Text setting.

  18. Double-click the Revert button and add to its Click event the following standard WCF proxy setup code with a call to your custom WCF service. Resolve references to assemblies by right-clicking red underlined elements in the code, pointing to Resolve, and accepting recommended assembly references for the System.ServiceModel namespace and for the namespace of your custom WCF service (ProjectTracker.ServiceReference2).

    private void toolStripButton2_Click(object sender, EventArgs e)
    {
        // Set up proxy.
        BasicHttpBinding binding = new BasicHttpBinding();
        binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
        binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
        EndpointAddress endpoint =
            new EndpointAddress(websiteUrl + "/_vti_bin/Revert.svc");
        RevertClient proxy = new RevertClient(binding, endpoint);
        proxy.ClientCredentials.Windows.AllowedImpersonationLevel =
            System.Security.Principal.TokenImpersonationLevel.Impersonation;
    
        // Call web service.
        proxy.Revert("Projects", ((ProjectsItem)projectsBindingSource.Current).Id);
    
        // Refresh the UI.
        context.MergeOption = System.Data.Services.Client.MergeOption.OverwriteChanges;
    
        context.Projects.ToList();
        projectsBindingSource.ResetCurrentItem();
    }
    

    Notice in the Revert method call of the previous example that the name of the SharePoint Foundation list is specified, and that the Current property is used to return the ID of the currently selected item in the Projects DataGridView control. After the web service call, the code refreshes the user interface (UI) and re-retrieves data from SharePoint Foundation.

  19. Press F5 to run the client application, and test the web service by changing an item in the Projects DataGridView and clicking the Revert button.

For the complete Form1 code sample, see Complete SharePoint Foundation WCF Form1 Sample.

Date

Description

Reason

May 2010

Initial publication

Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Http 400
Hi Guys,

I used this example for developing  simple poco echo service for Sharepoint 2010 and got a http 400 because of a mismatch in the factory class used in this article.

Using the Microsoft.SharePoint.Client.Services.MultipleBaseAddressWebServiceHostFactory instead of the given
Microsoft.SharePoint.Client.Services.MultipleBaseAddressBasicHttpBindingServiceHostFactory
solved my problem and the service worked fine.

Hope that helps.

Regards

Simon

Sample Code:

TestWCF.svc:
<% @ServiceHost Language="C#" Debug="true"
    Service="TestWCF.Service.TestWCFService, $SharePoint.Project.AssemblyFullName$"
    Factory="Microsoft.SharePoint.Client.Services.MultipleBaseAddressWebServiceHostFactory, Microsoft.SharePoint.Client.ServerRuntime, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

Service:
using System.ServiceModel.Activation;
using Microsoft.SharePoint.Client.Services;

namespace TestWCF.Service
{
    [BasicHttpBindingServiceMetadataExchangeEndpoint]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class TestWCFService : ITestWCFService
    {
        public string Echo()
        {
            return "WCF Service Echo Version 1.0...";
        }
    }
}

Interface:
using System.ServiceModel;
using System.ServiceModel.Web;

namespace TestWCF.Service
{
    [ServiceContract]
    public interface ITestWCFService
    {
        [OperationContract]
        [WebGet(UriTemplate = "/Echo", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml)]
        string Echo();
    }
}

400 Bad Request
Navneet -

Try 'http://localhost/_layouts/Revert.svc/MEX' as the URL for the metadata exchange endpoint for the service.

Regards,
NickP,
Ascentium

Seconded - just append /MEX to the end of the URL after the .svc portion.
Error at Step 15
When I try to add the service to the application at step 15 I get the following: $01- If I add servicename.svc, I get the error$0 $0There was an error downloading ... request failed with HTTP status 400: Bad Request.$0 $0...$0 $0Content Type application/soap+xml; charset=utf-8 was not supported by service http://vphq-sp2010dev/_vti_bin/VPList.svc.  The client and service bindings may be mismatched...$0 $0$0 $0 $02- If I add servicename.svc/MEX, I get the error:$0 $0 $0There was an error downloading ... request failed with HTTP status 400: Bad Request.$0 $0...$0 $0The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'NTLM'.$0 $0 $0$0 $0 $0What is going on? How to solve that?$0
The service '/_vti_bin/SubFolder/MYService.svc' does not exist.
I deplyed correctly but when I try to check by browser by url http://localhost/_vti_bin/SubFolder/MYService.svc/MEX
It appear message error of SharePoint (error template of sharepoint) with this message
The service '/_vti_bin/SubFolder/MYService.svc' does not exist. 

On eventViewer:

WebHost failed to process a request.
Sender Information: System.ServiceModel.Activation.HostedHttpRequestAsyncResult/31213533
Exception: System.Web.HttpException: The service '/_vti_bin/SubFolder/MYService.svc' does not exist. ---> System.ServiceModel.EndpointNotFoundException: The service '/_vti_bin/SubFolder/MYService.svc' does not exist.
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath)
at System.ServiceModel.ServiceHostingEnvironment.EnsureServiceAvailableFast(String relativeVirtualPath) [....]
MultipleBaseAddressBasicHttpBindingServicehostFactory does NOt support SSL
Great post.

Service works fine over HTTP, but receive a "no endpoint found" error when accessing over HTTPS.

After some research, I've narrowed it down to the MultipleBaseAddressBasicHttpBindingServiceHostFactory and the fact that it does not support HTTPS endpoints. 

How can we deploy a custom WCF Service over HTTPS without manually configuring the endpoints?

415 http error bindings mismatch utf 8 not supported
Hi guys. Tearing my hair out here. Double checked all the code, deploys fine, I see it via the browser with the /MEX URL, can add the service reference to my windows app but it bombs out on the proxy.revert call with
"utf-8 not supported .....client and service bindings may be mismatched.
I've looked in the svc file etc and all look good. Any help would be appreciated.
thanks
Unable to browse the Revert.svc
After Step 14) above if I go open the broswer and browse to the svc file, I am getting HTTP 400 error.
What am I missing?

There was an error downloading 'http://localhost/_layouts/Revert.svc'.
The request failed with HTTP status 400: Bad Request.
Metadata contains a reference that cannot be resolved: 'http://localhost/_layouts/Revert.svc'.
The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Negotiate,NTLM'.
The remote server returned an error: (401) Unauthorized.
If the service is defined in the current solution, try building the solution and adding the service reference again.