Share via


Creating a Custom WCF Service in SharePoint Foundation

Applies to: SharePoint Foundation 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.

Creating a WCF Service to Revert List Items to Previous Versions

  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.

    Imports System.Runtime.Serialization
    Imports System.ServiceModel
    
    Namespace WcfService
        <ServiceContract()> _ 
        Public Interface IRevert
            <OperationContract()> _ 
            Sub Revert(ByVal listName As String, ByVal listItemId As Integer)
        End Interface
    End Namespace
    
    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:

    Imports Microsoft.SharePoint.Client.Services
    Imports System.ServiceModel.Activation
    
    Namespace WcfService
    
        <BasicHttpBindingServiceMetadataExchangeEndpointAttribute()> _ 
        <AspNetCompatibilityRequirements(RequirementsMode := AspNetCompatibilityRequirementsMode.Required)> _ 
        Public Class RevertService
            Implements IRevert
    
            Public Sub Revert(ByVal listName As String, ByVal listItemId As Integer) Implements IRevert.Revert
                Dim oList As SPList = SPContext.Current.Web.Lists(listName)
    
                Dim oItem As SPListItem = oList.GetItemById(listItemId)
    
                If oItem.Versions.Count > 1 Then
                    oItem.Versions.Restore(1)
                End If
            End Sub
        End Class
    End Namespace
    
    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="https://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: https://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 Sub toolStripButton2_Click(ByVal sender As Object, ByVal e As EventArgs)
    
        ' Set up proxy.
        Dim binding As New BasicHttpBinding()
        binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly
        binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm
        Dim endpoint As New EndpointAddress(websiteUrl + "/_vti_bin/Revert.svc")
        Dim proxy As New RevertClient(binding, endpoint)
        proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation
    
        ' Call web service.
        proxy.Revert("Projects", DirectCast(projectsBindingSource.Current, ProjectsItem).Id)
    
        ' Refresh the UI.
        context.MergeOption = System.Data.Services.Client.MergeOption.OverwriteChanges
    
        context.Projects.ToList()
        projectsBindingSource.ResetCurrentItem()
    End Sub
    
    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.

See Also

Concepts

Walkthrough: Creating and Implementing a Custom WCF Service in SharePoint Foundation

WCF Services in SharePoint Foundation 2010

Other Resources

Windows Communication Foundation

Configuring Windows Communication Foundation Services