WCF: Building WCF Web Services for SharePoint 2010 Business Connectivity Services (Part 1 of 4)

Summary:  Learn to authenticate users in Microsoft SharePoint Foundation 2010 in this four-part series. Create Windows Communication Foundation (WCF) web services that you can consume as external content types from Microsoft Business Connectivity Services (BCS).

Available in SharePoint Online

Applies to: Business Connectivity Services | Office 2010 | Open XML | SharePoint Designer 2010 | SharePoint Foundation 2010 | SharePoint Online | SharePoint Server 2010 | Visual Studio

Provided by:   Eric White, Microsoft Corporation | Saji Varkey, Microsoft Corporation | Bin Zhang, Microsoft Corporation

Contents

  • Introduction

  • Prerequisites

  • Installing Windows Communication Foundation (WCF) and Internet Information Services

  • Registering the Service Model

  • Updating Script Maps

  • Creating Web Services

  • Validating the Web Service

  • Conclusion

  • Additional Resources

This article is the first in a four-part series of articles that show how to create and consume a claims-aware web service by using Business Connectivity Services. Check out the other articles in the series:

Introduction

This article shows how to create a very simple web service by using WCF. There is one special characteristic of the web service that I present in this article: Although it is very simple, it can be consumed as an external content type from Business Connectivity Services. In addition, the procedure presented in this article describes how to host this web service by using Internet Information Services (IIS).

This web service contains only two methods: a finder method to retrieve a collection of items, and a specific finder method to retrieve a single item. The data behind the collection is an initialized list. The schema of this little database is very simple. It is a single flat table consisting of two fields—an integer field, CustomerID, and a string field, CustomerName. CustomerID is a unique ID. The following snippet shows the initialization of list that contains the data that are served by the web service.

return new List<Customer>()
{
    new Customer
    {
        CustomerID = 1,
        CustomerName = "Bob",
    },
    new Customer
    {
        CustomerID = 2,
        CustomerName = "Bill",
    },
    new Customer
    {
        CustomerID = 3,
        CustomerName = "Cheryl",
    },
};

After building and configuring this web service, you can use SharePoint Designer 2010 to create an external content type from it, and then view the data in a SharePoint list. The following figure shows a SharePoint external list.

Figure 1. SharePoint 2010 external list

SharePoint 2010 External List

As you probably know, Business Connectivity Services in SharePoint Foundation 2010 and SharePoint Server 2010 is read/write. If you supply additional methods to create, update, and delete items, you can fully maintain the data in a list. I want this web service as simple as possible. Therefore this is a read-only implementation. My focus is on security and identity issues. How the database is stored, where it is stored, or the details of the schema are irrelevant to this topic.

The procedure presented here is for Windows Server 2008 R2 and Windows Server 2008. You can build this web service by using either Microsoft Visual Studio 2010 or Visual Studio 2008.

You can build, run, and test the web service presented in this article on any development computer that is running Internet Information Services. However, if you want to connect to this web service as an external content type by using Business Connectivity Services, build this example in a SharePoint 2010 development environment so that SharePoint Foundation 2010 or SharePoint Server 2010 and the example web service are running on the same computer. You can put this web service on a different server, and consume it as an external content type. However, in that situation, you must either remove security, or you must create a claims-aware web service.

As I mentioned, the procedure that I present here shows how to host the web service under IIS. This is the way that most implementers of such a web service want to host it. Hosting it as a service of IIS gives lots of benefits such as process recycling, process health monitoring, and message based activation.

Prerequisites

This procedure is for Windows Server 2008 or Windows Server 2008 R2. In both cases, I started on a server that had a fresh, patched install of the operating system. Next, I installed the necessary roles and features so that IIS was installed and running. In addition, the procedures that are presented in this article require the .NET Framework 3.5.1, and either Visual Studio 2008 or Visual Studio 2010.

Installing Windows Communication Foundation (WCF) and Internet Information Services

Use Server Manager to install the Web Server (IIS) role and the .NET Framework 3.5.1 feature.

To run this example, the only role that is Required is Web Server (IIS). The following figure shows the dialog in the Add Roles Wizard.

Figure 2. Select Web Server Role in Add Roles Wizard

Select Web Server in Add Roles Wizard

After adding the Web Server (IIS) role, the wizard asks you to select Role Services. Select Application Development. The following figure shows the dialog in the Add Roles Wizard.

Figure 3. Select Application Development in Add Roles Wizard

Select Application Development in Add Roles Wizard

To install the .NET Framework, add the .NET Framework 3.5.1 Features. The following figure shows the dialog in the Add Roles Wizard.

Figure 4. Select .NET Framework 3.5.1 Features in Add Roles Wizard

Select .NET Framework 3.5.1

When you install this feature on Windows Server 2008 (not R2), after you select the .NET Framework 3.0 Features, select WCF Activation. This is the default selection on Windows Server 2008 R2. The following figure shows the dialog in the Add Roles Wizard.

Figure 5. Select WCF Activation

Select WCF Activation on Windows Server 2008

Both WCF and IIS must be installed for IIS-hosted WCF services to function correctly. The procedures for installing WCF (as part of .NET Framework 3.0) and IIS vary depending on the operating system that you are using. If you are installing on an operating system other than Windows Server 2008 or Windows Server 2008 R2, see Microsoft .NET Framework 3.0 Redistributable Package to download and install .NET Framework 3.0. See Installing IIS.

Registering the Service Model

To run this example, you must register this version of WCF and update script maps at the IIS metabase root.

To register the service model

  1. Start a Visual Studio command prompt. Run as administrator. The following figure shows running the command prompt as administrator.

    Figure 6. Run the Visual Studio Command Prompt as administrator

    Run command prompt as administrator

    Click Start, click All Programs, click Visual Studio 2010, click Visual Studio Tools, right-click Visual Studio Command Prompt, and then click Run as Administrator.

    The Visual Studio command prompt is located in a similar location for Visual Studio 2008.

  2. Change the directory to the following:

    c:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation

  3. In the command prompt, enter:

    ServiceModelReg -i

    The following figure shows ServiceModelReg running.

    Figure 7. Running ServiceModelReg

    Running ServiceModelReg

    Note

    This did not have to be a Visual Studio command prompt. However, the following step needs a Visual Studio command prompt. Therefore for efficiency, I created one in this step.

Updating Script Maps

To update script maps

  • In the command prompt, enter:

    aspnet_regiis.exe -i

    The following figure shows updating script maps.

    Figure 8. Updating script maps

    Running aspnet_regiis

Creating Web Services

To create a web service

  1. Create a directory, C:\MyWebService, to contain the web service. If you use a different directory, you must change these procedures as appropriate.

  2. Start Visual Studio 2010 (or Visual Studio 2008).

  3. Click File, click New, and then click Project. For the installed template category, select WCF. For the template, select WCF Service Application. Target the .NET Framework 3.5. For the location of the project, browse to the directory that you created in step 1. Name the project CustomersService. Do not create a directory for the solution. The following figure shows what the New Project dialog box should look like.

    Figure 9. The New Project dialog box

    New Project dialog box

    Note

    Remember to change target to .NET Framework 3.5. By default, Visual Studio targets .NET Framework 4, and you must change it to .NET Framework 3.5 for the procedure presented here to work.

  4. In the project, rename IService1.cs to ICustomers.cs. Visual Studio 2010 offers to rename all references to the code element IService1 in this project. Click Yes. Actually, we will replace all code in all modules, so whether you click Yes or No has no affect.

  5. In the project, rename Service1.svc to Customers.svc. The following figure shows Solution Explorer after renaming these items.

    Figure 10. Solution Explorer after renaming the items

    Solution Explorer after renaming items

  6. Replace Customers.svc with the following single line of markup. Right-clickCustomers.svc, and then select View Markup. Copy the markup from this article, paste it into Visual Studio, and save.

    <%@ ServiceHost Language="C#" Debug="true" Service="CustomersService.Customers" CodeBehind="Customers.svc.cs" %>
    
  7. Replace Customers.svc.cs with the following code.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    namespace CustomersService
    {
        public class Customers : ICustomers
        {
            // Finder
            public List<Customer> GetAllCustomers()
            {
                return new List<Customer>()
                {
                    new Customer
                    {
                        CustomerID = 1,
                        CustomerName = "Bob",
                    },
                    new Customer
                    {
                        CustomerID = 2,
                        CustomerName = "Bill",
                    },
                    new Customer
                    {
                        CustomerID = 3,
                        CustomerName = "Cheryl",
                    },
                };
            }
    
            // Specific finder
            public Customer GetCustomerByID(int CustomerID)
            {
                return GetAllCustomers().FirstOrDefault(c => c.CustomerID == CustomerID);
            }
        }
    }
    
  8. Replace ICustomers.cs with the following code.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.ServiceModel;
    
    namespace CustomersService
    {
        [ServiceContract]
        public interface ICustomers
        {
            [OperationContract] //finder
            List<Customer> GetAllCustomers();
    
            [OperationContract] //specificFinder
            Customer GetCustomerByID(int CustomerID);
        }
    
        [DataContract]
        public class Customer
        {
            [DataMember]
            public int CustomerID { get; set; }
    
            [DataMember]
            public string CustomerName { get; set; }
        }
    }
    
  9. Replace Web.config with the following markup. In Solution Explorer, right-click Web.config and select Edit. Copy, paste, and save.

    Important

    This is the Web.config file that configures this specific web service. It resides at C:\MyWebService\CustomersService.

    <?xml version="1.0"?>
    <configuration>
      <system.serviceModel>
        <services>
          <service behaviorConfiguration="CustomersService.Service1Behavior"
            name="CustomersService.Customers">
            <endpoint address="" binding="wsHttpBinding" contract="CustomersService.ICustomers">
              <identity>
                <dns value="localhost" />
              </identity>
            </endpoint>
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior name="CustomersService.Service1Behavior">
              <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deploying the solution. -->
              <serviceMetadata httpGetEnabled="true"/>
              <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deploying the solution to avoid disclosing exception information. -->
              <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
          </serviceBehaviors>
        </behaviors>
      </system.serviceModel>
    </configuration>
    
  10. Build the application.

  11. Add an application to the default web site. Start Internet Information Services (IIS) Manager. Click Start, click All Programs, click Administrative Tools, and then click Internet Information Services (IIS) Manager. In Internet Information Services (IIS) Manager, expand Sites, and right-click Default Web Site, and then select Add Application. The following figure shows how to add an application in Internet Information Services (IIS) Manager.

    Figure 11. Internet Information Services Manager

    Internet Information Services Manager

    In the Add Application dialog box, in the Alias field, type Customers. In the Physical Path field, browse to C:\MyWebService\CustomersService. Click OK twice. The following figure shows the directory that contains the web service.

    Figure 12. Directory with the web service

    Browse to directory that contains Web service

  12. Validate that the web service is running. Start Internet Explorer, and browse to https://localhost/Customers/Customers.svc. If the web service is running, you see the following:

    Figure 13. CustomersService web service in Internet Explorer

    Web service running in Internet Explorer

Validating the Web Service

Another approach to testing the web service is to use the WCF test client.

To validate the Web Service by using the WCF Test Client

  1. Start a Visual Studio command prompt (or use the one that is open from the end of the preceding procedure).

  2. Type wcftestclient to run the WCF test client. Click File and then click Add Service.

  3. Type https://localhost/Customers/Customers.svc as the endpoint address, and then click OK.

    The following figure shows entering the endpoint into the WCF test client.

    Figure 14. WCF Test Client

    WCF test client

    If the service was added successfully, you see the methods that the service exposes. The following figure shows the web service methods in the WCF test client.

    Figure 15. WCF Test Client showing methods

    WCF test client showing methods

  4. Double-click GetAllCustomers. This opens a window that lets you configure the request and start the request.

  5. Click Invoke to see the response from the web service. The following figure shows the results of calling GetAllCustomers.

    Figure 16. WCF Test Client showing results from calling GetAllCustomers

    WCF test client showing data

Conclusion

In this article, you completed the first of four major steps towards creating a claims-aware web service, and using it with Business Connectivity Services. You created the web service, compiled it, and hosted it by using IIS. In the next article, WCF: Determining Caller Identity within WCF Web Services (Part 2 of 4), you enhance this example to use features from Windows Identity Foundation (WIF) to determine the identity of the web service caller.

Additional Resources