Section 2: Consuming an On-Premise WCF Service from SharePoint

Overview

Silverlight Web Parts and the Azure AppFabric Service Bus make it easy to interact with on-premise WCF services hosted inside your protected intranet from SharePoint. “On-Premise” means any internal WCF service which runs within the confines of a corporate intranet, or otherwise within the bounds of a server which is protected by firewalls /network address translation (NAT) and which has no public IP or direct exposure to the internet.

Objectives

In this lab, you will:

  • Create a simple WCF service hosted in a console application.
  • Create a WCF “forwarder” service hosted in Windows Azure which will forward calls to the console WCF service via the Azure AppFabric Service Bus.
  • Create a Silverlight application which consumes the on-premise console WCF service via routing a call through the forwarder service.

System Requirements

You must have the following items to complete this lab:

Setup

The Windows Azure SDK (included in Windows Azure Tools for Visual Studio) installs a simulation environment on your development machine for testing Azure applications locally before deploying them to the cloud. The simulation environment consists of the development fabric to host web and worker roles, and the development storage which simulates cloud blob, table and queue storage locally.

Development storage uses SQL Server as its underlying storage mechanism, and by default the SDK will attempt to configure it to use SQL Server Express. If you do not have SQL Server Express installed before installing the SDK, or you wish to simply use an existing SQL Server instance to host the development storage database, you must run the dsinit command to select the SQL Server instance where the database will be created.

Please see instructions below for how to run dsinit.

Using dsinit to Configure Development Storage

  1. Open a command prompt.
  2. Edit the following command line as appropriate for your environment, where [AzureSDKInstallDrive] is the drive where you installed the Azure SDK (or Windows Azure Tools for Visual Studio), and [YourSqlInstance] is the SqlServer where you want to create the development storage database.[AzureSDKInstallDrive]\ Program Files\Windows Azure SDK\v1.4\bin\devstore\dsinit.exe /sqlinstance:[YourSqlInstance].

    Example Command Line:“C:\Program Files\Windows Azure SDK\v1.4\bin\devstore\dsinit.exe” /sqlinstance:.

  3. Note that the sample command line above uses the value “.” for the sqlinstance argument, which specifies that the local default SQL instance will be used for development storage.

Estimated time to complete this lab: 20 minutes

Exercise 1: Create an On-Premise WCF Service

In this exercise, you will create an On-Premise WCF service hosted in a console application.

Task 1 – Beginning the Exercise

In this task, you will open the lab solution in Visual Studio 2010.

  1. Make sure that you’ve downloaded and installed the items listed in System Requirements above prior to beginning this exercise.
  2. Launch Visual Studio 2010 and open the lab project by selecting File » Open » Project.
    1. Browse to the SPtoOnPremise.sln file located at the Before folder of the lab.
    2. Click Open to open the solution.

Task 2 – Creating an XML File Containing Sample Data

In this task, you will create an XML file which contains data that will be returned by the on-premise WCF service to client applications.

  1. Right-click the EmployeeInfoService project, and choose Add » New Item.
  2. In the Installed Templates pane of the Add New Item dialog, select Data.
  3. Choose the XML File template.
  4. Name the file EmployeeList.xml and click Add. The new XML file will open in Visual Studio.
  5. Replace the default contents of the file with the following XML:

    XML

    <?xml version="1.0"?> <ArrayOfEmployee xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="https://www.w3.org/2001/XMLSchema"> <Employee> <FirstName>Ted</FirstName> <LastName>Burgundy</LastName> <Salary>89000</Salary> </Employee> <Employee> <FirstName>Jane</FirstName> <LastName>Smith</LastName> <Salary>72000</Salary> </Employee> <Employee> <FirstName>Rita</FirstName> <LastName>Flores</LastName> <Salary>115000</Salary> </Employee> <Employee> <FirstName>Bob</FirstName> <LastName>Hess</LastName> <Salary>82000</Salary> </Employee> <Employee> <FirstName>Allen</FirstName> <LastName>Jackson</LastName> <Salary>91000</Salary> </Employee> </ArrayOfEmployee>

  6. Right-click the EmployeeList.xml file and choose Properties. In the Copy to Output Directory property, choose Copy Always.

Task 3 – Creating and Configuring the EmployeeInfoSvc WCF Console Application

In this task, you will implement a service operation on the EmployeeInfoSvc WCF service, and modify the web.config file to configure expose a service endpoint via the Azure AppFabric Service bus.

  1. In the EmployeeInfoService project, open the file EmployeeInfoSvc.cs. Insert the following code in the EmployeeInfoSvc class, under the //TODO:5.2.2 comment:

    C#

    List<Employee> IEmployeeInfoSvc.GetEmployees() { Console.WriteLine("GetEmployees was called."); XmlSerializer xs = new XmlSerializer(typeof(List<Employee>)); object employeeList = null; using (FileStream fs = new FileStream("EmployeeList.xml", FileMode.Open)) { employeeList = xs.Deserialize(fs); } return (List<Employee>)employeeList; }

  2. The above code deserializes the EmployeeList.xml file into a generic List of Employee objects, and returns that list to the caller.
  3. Open the Program.cs file.
  4. Add the following code to the Main() method, under the //TODO: 5.2.3 comment.

    C#

    _wcfHost = new ServiceHost(typeof(EmployeeInfoSvc)); _wcfHost.Open(); Console.WriteLine("Employee info service is running."); Console.WriteLine("Press [Enter] to exit..."); Console.ReadLine(); _wcfHost.Close();

    The above code creates a WCF service hosting environment and instructs it to expose the EmployeeInfoSvc type as a service. This means that instsances of EmployeeInfoSvc will be created to serve incoming requests. Requests are served on background threads.

    Specifics of how the WCF service is hosted are contained in the app.config file. This service opens a relayed TCP (binary) endpoint in the Azure AppFabric service bus, allowing it to receive requests from the internet without being directly exposed to the internet. This is possible because the service’s binding, netTcpRelayBinding, initiates an outbound, bi-directional TCP channel, allowing it to traverse network address translation (NAT) and firewalls. For more information on the AppFabric service bus, see Getting Started with AppFabric Service Bus.

  5. To create a new service namespace, log on to Windows Azure Appfabric portal at https://appfabric.azure.com using your azure credentials.
  6. Create a new service namespace.
  7. Back in your EmployeeInfoService project, Open the app.config file .
  8. Replace the text [YourServiceBusNamespace] with a service bus namespace from your Azure AppFabric account.
  9. Replace the text [YourIssuerName] and [YourIssuerSecret] with valid values for your Azure AppFabric account.
  10. Build the EmployeeInfoService Project.

Exercise 2: Create a Windows Azure WCF Service to Forward Calls to the On-Premise Service

In this exercise, you will create a WCF service which will be hosted in Windows Azure. This service will receive calls from a Silverlight Web Part running in SharePoint and forward them to the EmployeeInfoSvc on-premise WCF service, via the Azure AppFabric service bus.

**Note that this exercise is only necessary because version 1.0 of the Azure AppFabric Service Bus does not support Silverlight clients directly. This capability will be introduced in the upcoming AppFabric version and will eliminate the need to forward calls through Windows Azure in this scenario.

Task 1 – Creating the ForwarderServiceWebRole.

  1. Open the CloudToOnPremForwarder.svc.cs file in the ForwarderServiceWebRole project.
  2. Replace the text [YourServiceBusNamespace] with the service bus namespace from your Azure AppFabric account which you used for the console application above.
  3. Replace the text [YourIssuerName] and [YourIssuerSecret] with the service bus issuer name and secret from your Azure AppFabric account which you used for the console application above.
  4. Add the following code to the GetEmployees(), after the //TODO:5.2.4 comment.

    C#

    Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, serviceName); // create the credentials object for the endpoint TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior(); sharedSecretServiceBusCredential.CredentialType = TransportClientCredentialType.SharedSecret; sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerName = issuerName; sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerSecret = issuerSecret; NetTcpRelayBinding binding = new NetTcpRelayBinding(); // create the channel factory loading the configuration ChannelFactory<IEmployeeInfoChannel> channelFactory = new ChannelFactory<IEmployeeInfoChannel>(binding, new EndpointAddress(serviceUri)); // apply the Service Bus credentials channelFactory.Endpoint.Behaviors.Add(sharedSecretServiceBusCredential); // create and open the client channel IEmployeeInfoChannel channel = channelFactory.CreateChannel(); channel.Open(); List<Employee> listFromOnPrem = channel.GetEmployees(); channel.Close(); return listFromOnPrem;

    The above code creates a client endpoint in the AppFabric Service Bus which maps to the endpoint created by the console application in the previous exercise. Any .NET application with access to the internet and the proper service bus credentials is able to consume the console application’s WCF service.Note that the WCF client code above does not need to use design time generated proxies, meaning there is no service reference present. Instead, the client and service applications share a reference to a common assembly (Shared.dll, defined in the Shared project of this solution) which contains the service and operation contracts. The ChannelFactory is used to create a runtime proxy based on the shared assembly. In general, this technique is the most efficient choice when both the client and service application are controlled by the same development team and there is no nead to expose the service to external parties.

    Note:
    Microsoft.ServiceBus.dll is not installed on Azure boxes. In the WebRole project, the reference Microsoft.ServiceBus.dll is configured for "Copy Local = True". This causes the assembly Microsoft.ServiceBus.dll to be packaged up with your WebRole project, before it is deployed to Azure. This is a mandatory step, otherwise the WebRole will fail to run on the cloud.

  5. Set the CloudToOnPremForwarder.svc as start up page and Demo52CloudApp as start up project. Run Demo52CloudApp project in the local simulation environment by hitting the F5 key. This causes the web roles to run on your local machine.
  6. Build the Solution and publish the Demo52CloudApp project to your Windows Azure account by right-clicking on the Demo52CloudApp project and selecting Publish. Follow the instructions in Lab 1 to publish the service to Azure.
  7. Browse to the service information page to verify that CloudToOnPremForwarder service is active. For example, https://myaccount.cloudapp.net/CloudToOnPremForwarder.svc.

Exercise 3: Create a Silverlight Application to Consume the On-Premise WCF Service

Task 1 - Connecting the Silverlight Application to the CloudToOnPremForwarder Service

In this task, you will update the ServiceReferences.ClientConfig file of the EmployeeInfoSLDisplay project.

  1. Open the ServiceReferences.ClientConfig file in the EmployeeInfoSLDisplay project.
  2. Replace the text [YourCloudServiceAddress] with the address of the service you deployed to Windows Azure in previous steps. For example, https://myaccount.cloudapp.net/CloudToOnPremForwarder.svc
  3. Right-click on the EmployeeSLDisplay project and select Build to build the Silverlight application.

Task 2 - Adding the Silverlight Application to your SharePoint Site

In this task, you will upload the SalarySLDisplay Silverlight application to SharePoint, and display it in a web part.

  1. Log into a your SharePoint site.
  2. If you do not already have a document library created for storage of Silverlight XAP files, create one now:
    1. In the Site Actions menu, click New Document Library.
    2. In the Name field, type Silverlight Apps.
    3. In the Document Template field, select None.
    4. Click Create.
  3. Navigate to your Silverlight Applications document library if necessary.
  4. Click Add Document.
  5. Click Browse.
  6. Navigate to the bin\debug directory within the EmployeeInfoSLDisplay project.
  7. Select the file EmployeeInfoSLDisplay.xap.
  8. Click Open.
  9. Click OK.
  10. An entry in the document library appears for EmployeeInfoSLDisplay.
  11. Right click the entry’s Name column and select Copy Shortcut.
  12. Navigate to the Home page in your Sharepoint site in which you want to display the Silverlight application.
  13. In the Site Actions menu, click Edit Page.
  14. Under the Editing Tools menu, click Insert.
  15. In the Insert ribbon, click Web Part.
  16. Under Filter By, choose Media and Content.
  17. Select the Silverlight Web Part, and click Add.
  18. Paste the URL for the XAP file (copied to clipboard in step 11 above) into the URL box and click OK.
  19. If necessary, resize the Silverlight Web Part to center contents. This can be done by clicking the down arrow above the Web Part and clicking Edit Web Part. The tool pane will open on the right side of the screen and a new width and height can be entered. Click OK in the toolpane to apply the changes.

Task 3 – Testing the End-to-End Solution

  1. Start the EmployeeInfoService console application by right clicking the project in Visual Studio and selecting Debug » Start New Instance.
    1. Wait for "Press [Enter] to exit..." to be written to the console.
  2. On the SharePoint page where you’ve hosted the EmployeeInfo Silverlight application, click the Get Employees button.

    Silverlight will call into your console application via Windows Azure and the .NET service bus, and display the list of employees in the data grid.

Summary

Consuming on-premise WCF services from SharePoint is easily accomplished via a Silverlight application running in a Silverlight Web Part. The chief mechanism which allows SharePoint to communicate with back-end systems protected by firewalls is the Azure AppFabric Service bus.

In this lab, you learned how to create a basic WCF service in a console application, and expose an endpoint for that service in the AppFabric service bus. You also learned how to consume data returned by that service with a Silverlight Application hosted in SharePoint.