Thursday, December 29, 2011

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.
  8. 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);
            }
        }
    }
}

9. 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.

  1. 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.
  2. 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.
  3. 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

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>
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. In the Properties window for the button, set DisplayStyle to Text, and type Revert as the value for the Text setting.
  6. 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();
}
  1. 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.
  2. 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.

//Complete code:
============

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SP = Microsoft.SharePoint.Client;


namespace ProjTrack
{
    using ServiceReference1;
    using System.Net;
    using System.ServiceModel;
    using ProjTrack.ServiceReference2;

    public partial class Form1 : Form
    {
        private static string websiteUrl= "http://YourServer/sites/YourSiteCollection/YourSite";

        TestWebsDataContext context = new TestWebsDataContext(
            new Uri(websiteUrl + "/_vti_bin/listdata.svc"));

        SP.ClientContext clientContext = new SP.ClientContext("websiteUrl");

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            context.Credentials = CredentialCache.DefaultCredentials;
            projectsBindingSource.DataSource = context.Projects;

            clientContext.Load(clientContext.Web);
            clientContext.ExecuteQuery();

            this.Text = clientContext.Web.Title;

        }

        private void projectsBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            employeesBindingSource.DataSource =
                from emp in context.Employees
                where emp.Project.Id == ((ProjectsItem)projectsBindingSource.Current).Id
                select emp;
        }

        private void projectsBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            context.SaveChanges();
        }

        private void projectsBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            context.UpdateObject(projectsBindingSource.Current);
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            SP.List oList = clientContext.Web.Lists.GetByTitle("Projects");

            oList.Description = string.Format("Star Project of the Week is {0}!!!",
                ((ProjectsItem)projectsBindingSource.Current).Title);

            oList.Update();
            clientContext.ExecuteQuery();
        }

        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();
        }




    }
}

No comments:

Post a Comment