Share via


Section 1: Consuming a Windows Azure-Hosted WCF Service from SharePoint

Overview

Silverlight Web Parts make it easy to interact with WCF services, including those hosted in Windows Azure, from SharePoint.

Objectives

In this lab, you will:

  • Create a simple WCF service and deploy it to Windows Azure.
  • Create a Silverlight application which consumes the WCF service and deploy it to a SharePoint site.

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: Hosting a WCF Service in Windows Azure

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 as administrator and open the lab project by selecting File » Open » Project.
    1. Browse to the SPToWinAzureWCF.sln file located at Before folder of this lab and select it.
    2. Click Open to open the solution.

Task 2 – Implementing and Configuring the WCF Service

In this task, you will implement a service operation on the SalaryService WCF service, and modify the web.config file to configure WCF hosting for the service.

  1. In the SalaryServiceWebRole project, open the file SalaryService.svc.cs.
  2. Add the following code under the //TODO: 5.1.1 comment to define the SalaryService class and it’s AdjustSalaryForInflation method:
  3. C#

    [ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class SalaryService : SalaryServiceWebRole.ISalaryService { public double AdjustSalaryForInflation(double startingSalary, double inflationPercent) { double newSalary = startingSalary * (1 + inflationPercent / 100); return newSalary; } }

  4. The above code performs a simple calculation to determine what salary adjustment should be made given a starting salary and an annual inflation percentage. The ServiceBehavior attribute ensures that client requests from any address are accepted. The AspNetCompatibilityRequirements attributed is needed to ensure compatibility with Silverlight.
  5. Open the Web.Config file.
  6. Add the following to the System.ServiceModel section to configure hosting of the WCF service, under the //TODO: 5.1.2 comment:

    XML

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/> <services> <service behaviorConfiguration="SalaryServiceWebRole.CloudWCFServiceBehavior" name="SalaryServiceWebRole.SalaryService"> <endpoint address="" binding="basicHttpBinding" contract="SalaryServiceWebRole.ISalaryService" /> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="SalaryServiceWebRole.CloudWCFServiceBehavior"> <!--The useRequestHeadersForMetadataAddress behavior is contained in the KB981002- WCF: Hotfix rollup upodate. This behavior is required for WCF to correctly serve metadata when behind a load balancer (which is the case in Windows Azure)--> <useRequestHeadersForMetadataAddress> <defaultPorts> <add scheme="http" port="81"/> <add scheme="https" port="444"/> </defaultPorts> </useRequestHeadersForMetadataAddress> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> </behaviors>

    About the System.ServiceModel configuration above:

    For this example we are exposing a metadata exchange (MEX) endpoint in addition to the service main endpoint. This will expose the service metadata and thus allow service references to be added to this service in Visual Studio.

    The useRequestHeadersForMetadataAddress behavior is a special behavior that is defined in KB981002- WCF: Hotfix rollup update. It allows WCF to serve correct metadata behind load balancers. Windows Azure web roles are load balanced between one or more physical servers.

Task 3 – Adding a Cross-Domain Policy File

In this task, you will create a client access policy file to allow Silverlight clients to make cross-domain calls to the WCF service. Any Silverlight-enabled WCF service which must allow Silverlight clients to consume it from outside of the domain where the WCF service is hosted must have this file exposed at the root level of its address.

  1. Right-click the SalaryServiceWebRole 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 clientaccesspolicy.xml and click Add. The new XML file will open in Visual Studio.
  5. Add the following under the XML declaration tag:

    XML

    <access-policy> <cross-domain-access> <policy> <allow-from http-request-headers="SOAPAction"> <domain uri="*"/> </allow-from> <grant-to> <resource path="/" include-subpaths="true"/> </grant-to> </policy> </cross-domain-access> </access-policy>

    The above clientaccesspolicy.xml file allows access by callers from any domain to any path within the root URL where the WCF service is hosted. In a production scenario, the allow-from domain and grant-to paths would likely be much more restrictive.

  6. Set the SalaryService.svc as start up page and Demo51CloudApp as start up project. Run Demo51CloudApp project in the local simulation environment by hitting the F5 key. This causes the web roles to run on your local machine.

Task 4 – Publishing the WCF Service to Windows Azure

In this task, you will publish the SalaryService to you Windows Azure account.

  1. Clean and Build the SalaryServiceWebRole.
  2. Clean and Build the Demo51CloudApp solution.
  3. Right-click on the Demo51CloudApp, and select Publish.
  4. There are two ways to publish the service to Windows Azure.
    1. Create a service package, uploading it to Windows Azure.
    2. Directly deploying to Windows Azure.

      In this case, we’ll be creating the service package and upload it to Windows Azure. To do so, select the Create Service Package Only option in the Publish dialog box, and select OK.

      Figure 1

      Publish dialog box

  5. The service package will now be created in a folder named Publish inside the bin directory. You can access it under the following folder of this lab:\Source\Sec1 -AzureFromSPOnPrem\Before\Demo51CloudApp\bin\Debug\Publish\Two files are created at the above location. – The service package file (.cspkg) and the service configuration file (.cscfg)
  6. The next step is to upload the published files to windows azure and activate them. To do so, Open Internet Explorer, and go to https://windows.azure.com. Login with your Azure credentials. If you do not have a Windows Azure Account, sign-up for a new one.
  7. Create a new Hosted service by clicking the New Hosted Service from the ribbon menu.

    Figure 2

    Ribbon menu

  8. Configure the new service as follows:
    1. Choose a subscription: Select the name of Azure subscription. (You would have provided this information while signing up for Azure account.)
    2. Name of the Service: Provide a user friendly name to the service.
    3. URL prefix of your service: This is a unique URL. Choose an URL that is available. Note: When you delete this service, the URL is immediately available to others.
    4. Region or Affinity group: This is the physical location of the Azure datacenter hosting your service. Choose a region.
    5. Deployment Options: Select “Deploy to stage environment”. It is possible to directly publish the service to a production environment also. But as a best practice, publish the service to a staging environment, and test it on staging before publishing it to Production.
    6. Deployment Name: A user friendly name that helps to identify this service.
    7. Package Location: Select “Browse Locally”, and browse to the .cspkg file that you published earlier and select the file.
    8. Configuration file: Select “Browse Locally, and browse to the.cscfg file that you published earlier and select the file.
    9. Click OK to complete creating the new hosted service.

      Figure 3

      New Hosted Service Dialog

  9. If you see a warning, click Yes to override and submit. This is a warning that this deployment is a single instance deployment. For a 99.95% uptime Microsoft recommends at least 2 instances. You can always increase the number of instances in the Production deployment by changing it in the configuration file

    Figure 4

    Warning

  10. It could take a few minutes for the staging environment to be ready. The image below shows a Staging environment when ready.

    Figure 5

    Staging environment

    The DNS name on the right panel is the staging URL

  11. Next , publish the service to production. To do this, first select the service deployed to Windows Azure. Then, from the ribbon menu, select Swap VIP.

    Figure 6

    Ribbon menu

  12. Click OK to swap the bits deployed in Staging with the bits in production.

    Note:
    If the production slot is not empty, the contents of the production will be moved to Staging.

    Figure 7

    Swap VIPs

    Once deployed to production, test the service from Internet Explorer by navigating to the path where the service is deployed.

    Figure 8

    Internet Explorer

Exercise 2: Create a Silverlight Application to Consume the WCF Service

Task 1 – Implementing the Silverlight Application

In this exercise you will create a Silverlight application to invoke the WCF service.

  1. Expand the SalarySLDisplay project in Solution Explorer.
  2. Right click References and select Add Service Reference.
  3. Enter the URL for your service in Azure. For example,http://mysalaryservice001.cloudapp.net/SalaryService.svc
  4. Click Go.
  5. For the Namespace, enter SalaryService.
  6. Click OK to generate the proxy classes and configuration.

    Figure 9

    Add Service Reference Dialog

  7. Open the MainPage.xaml.cs file.
  8. Add the following code to the Button_Click method, after the //TODO: 5.1.4 comment.

    C#

    SalaryServiceClient client = new SalaryServiceClient(); client.AdjustSalaryForInflationCompleted += new EventHandler<AdjustSalaryForInflationCompletedEventArgs>(client_AdjustSalaryForInflationCompleted); client.AdjustSalaryForInflationAsync(double.Parse(txtCurrentSalary.Text), double.Parse(txtInflationPercent.Text));

    The above code creates an instance of the SalaryService proxy, and initiates an asynchronous call to the AdjustSalaryForInflation method. Silverlight only allows async calls to WCF services (to avoid tying up the main UI thread and hence hanging the UI), so when a service reference is added to a Silverlight project, the given async operation equivalent and completion events are automatically added to the proxy class.

  9. Add the following method to the MainPage class, after the //TODO: 5.1.5 comment.
  10. C#

    void client_AdjustSalaryForInflationCompleted(object sender, AdjustSalaryForInflationCompletedEventArgs e) { if (e.Error == null) { this.lblNewSalary.Content = string.Format("{0:C}", e.Result); this.Storyboard1.Begin(); } else { MessageBox.Show("An error occurred: \r\n\r\n" + e.Error.Message); } }

    The above method executes when the call to the AdjustSalaryForInflation WCF service call completes. While the service call is executed on a background thread, the completion handler is invoked on the UI thread, which is the only thread from which UI updates are permitted.

  11. Right click the SalarySLDisplay project and select Build.

Task 2 – Adding the SalarySLDisplay Silverlight Application to Your SharePoint Site

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

  1. Log into 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 SalarySLDisplay project.
  7. Select the file SalarySLDisplay.xap.
  8. Click Open.
  9. Click OK.
  10. An entry in the document library appears for SalarySLDisplay.
  11. Right click the SalarySLDisplay entry’s Name column and select Copy Shortcut.
  12. Navigate to the Home page in your SharePoint site.
  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.
  20. When the Silverlight web part is displayed on the page, enter a Current Salary and Annual Inflation Percent into the text boxes.
  21. Click Get Adjusted Salary to test consuming the WCF service.
  22. You may see a popup window appear which asks you if you want to Display Mixed Content.

    Figure 10

    Pop-up window

  23. If you see this pop click Yes.
  24. To prevent the popup from displaying in the future in Internet Explorer click Tools and select Options.
  25. Select the Security tab.
  26. Click Custom Level.
  27. Located Display mixed content and select Enable.

    Figure 11

    Security settings

  28. Click OK.
  29. Click Yes.
  30. Click OK.

Summary

Consuming Windows Azure-Hosted WCF services from SharePoint is easily accomplished via a Silverlight application running in a Silverlight Web Part. In fact, from the perspective of SharePoint and Silverlight it is no different from consuming a WCF service which is not hosted in Windows Azure. In this lab, you learned how to create a basic WCF service in a Windows Azure web role. You also learned how to create a cross-domain policy file which enables Silverlight applications to call outside of the site in which they’re deployed, enabling access to cloud services. Finally, you learned how to reference a WCF service in the cloud from a Silverlight application, and display that application in a Silverlight web part in SharePoint.