Consuming a Windows Azure-Hosted WCF Service from SharePoint by dandanhuanghuang

VIEWS: 5 PAGES: 16

									Hands-On Lab
Consuming a Windows Azure-Hosted WCF
Service from SharePoint Using JQuery
Lab version:    1.0.0
Last updated:   12/4/2011
CONTENTS

OVERVIEW ................................................................................................................................................... 3

EXERCISE 1: HOSTING A WCF SERVICE IN WINDOWS AZURE ........................................................... 4
       Task 1 – Beginning the Exercise ............................................................................................................ 4
       Task 2 – Implementing and Configuring the WCF Service .................................................................... 4

EXERCISE 2: CREATE A HTML WEB PART TO CONSUME THE WCF SERVICE USING JQUERY ..... 7
       Task 1 – Implementing the HTML Web Page ........................................................................................ 7
       Task 2 – Adding a WebPart to your SharePoint Site to call the WCF service using JQuery. ............... 11

SUMMARY .................................................................................................................................................. 16
Overview
Any SharePoint Web Part that uses HTML and JavaScript (Ex: HTML forms Web Part or a Visual Web
Part) make it easy to consume WCF services using JQuery , including those hosted in Windows Azure,
from SharePoint. A Silverlight Web Part may also consume a WCF service by using the HTML DOM
Bridge. With this approach, Silverlight Web Parts send and receive data to the hosting SharePoint page.
The hosting SharePoint page uses JQuery to communicate with the WCF services.


Objectives
In this lab, you will:
        Create a simple WCF service and deploy it to Windows Azure.
        Create a HTML application which consumes the WCF service and deploy it to a SharePoint site
         as an HTML forms Web Part.



System Requirements
You must have the following items to complete this lab:

        Windows Azure SDK and Windows Azure Tools for Microsoft Visual Studio (March 2011)
        KB981002- WCF: Hotfix rollup in .NET 3.5 SP1 for Win 7 and Win 2k8 R2

        Access to a Windows Azure account



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.
            a. Browse to the SPToWinAzureWCFUsingJQuery.sln file located on the Before folder of
               the lab and select it.
            b. Click Open to open the solution. This solution contains the Windows Azure web role
               project and the Web project that consumes the Azure hosted WCF Service using JQuery.

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 ISalaryService.cs.
       2. Add the following code under the //TODO: 5.5.1 comment to set up the Operation contract.
        C#
        [WebInvoke(Method = "POST",
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        UriTemplate = "adjust")]



        When the service or client serializes parameters and return values to a message, it writes them
        within infrastructure-provided XML elements and is wrapped. The WebMessageBodyStyle
        enumeration specifies whether to wrap parameters and return values. By setting the
        WebMessageBodyStyle to WrappedRequest, the requests are wrapped but the responses are
        not wrapped.
        RequestFormat = WebMessageFormat.Json
        WebMessageFormat is the enumeration that specifies the format of the input and the output
        formats of the request and response. In this case, the format is set to JSON.
       3. In the SalaryServiceWebRole project, open the file SalaryService.svc.cs.
       4. Add the following code under the //TODO: 5.5.2 comment to define the SalaryService class
          and it’s AdjustSalaryForInflation method:
        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;
                }
            }
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.
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.5.3 comment:
XML
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <services>
      <service
behaviorConfiguration="SalaryServiceWebRole.CloudWCFServiceBehavior"
                name="SalaryServiceWebRole.SalaryService">
        <endpoint address=""
                   binding="webHttpBinding"
behaviorConfiguration="JsonEndpointBehavior"
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>
<endpointBehaviors>
      <behavior name="JsonEndpointBehavior">
        <webHttp/>
      </behavior>
</endpointBehaviors>
    </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.
       7. Right click the SalaryService.svc file and select Set As Start Page.
       8. Right click the Demo55CloudApp project and select Set As a StartUp Project. Run
          Demo55CloudApp project in the local simulation environment by hitting the F5 key. This
          causes the web roles to run on your local machine.

         Note: As a good practice, run the solution in the local simulation environment to make sure
         the service works fine locally. This also provides a good way to debug the solution.



       9. Build the Solution and publish the Demo55CloudApp project to your Windows Azure
          account by right-clicking on the Demo55CloudApp project and selecting Publish. Follow the
          instructions in Lab 1 to publish the service to Azure.
       10. Browse to the service information page to verify that SalaryService service is active. For
           example, http://mysalaryservice.cloudapp.net/SalaryService.svc.




Exercise 2: Create a HTML Web Part to
Consume the WCF Service using JQuery
Task 1 – Implementing the HTML Web Page


Any client application that implements HTML and JavaScript (Ex: HTML forms Web Part or a Visual Web
Part) can consume WCF services using JQuery, including those hosted in Windows Azure, from
SharePoint. In this exercise, you will create a HTML Web Part. This same code sample can be used in a
SharePoint Visual Web Part.
In this exercise you will create a HTML Web page to invoke the WCF service.
      1. Expand the SalaryDisplayWeb project in Solution Explorer.
2. Open SalaryDisplay.html
3. Add the following under the //TODO: 5.5.4 comment:
JavaScript
$(document).ready(HolJQuerySPOnPrem.Initialize);


jQuery has a $(document).ready() function which is invoked after the DOM is loaded and before
the page contents are loaded. It means you don't have to have body onload events and can
completely remove all JavaScript from your HTML by attaching events to elements independent
of the HTML after the DOM has loaded.
4. Add the following JavaScript code under the //TODO: 5.5.5 comment:
JavaScript
$.ajax({
      data: data,
      cache: false,
      success: HolJQuerySPOnPrem.ReceiveData,
      type: "POST",
      dataType: "json",
      contentType: "application/json",
      url:
"http://[URLPrefix_Of_Your_AzureService].cloudapp.net/salaryservice.svc/adjust
"
  });


This code performs an asynchronous HTTP (Ajax) request.

The "success:" attribute calls a function request succeeds. The function gets passed three
arguments: The data returned from the server, formatted according to the dataType parameter;
a string describing the status; and the jqXHR object
The "datatype:" attribute is the type of data that you're expecting back from the server. If none
is specified, jQuery will try to infer it based on the MIME type of the response. In this case, we
are setting the datatype to Json to get a Json response from the WCF Service.
5. Replace [URLPrefix_Of_Your_AzureService] with the actual url prefix of the azure service
   that you published in exercise 1 of this Lab.
   Ex: http://mysalaryservice.cloudapp.net/salaryservice.svc/adjust
6. Note the reference to http://ajax.microsoft.com/ajax/jquery/jquery-1.4.4.min.js
   The Microsoft AJAX Library itself is self-contained, written in JavaScript, and stored in a
   couple of .js files. This means that any programming environment that accepts JavaScript can
   successfully use the Microsoft AJAX Library provided that the constituent files are properly
   referenced
7. Right click the SalaryDisplayWeb project and select Build.
8. Right click the SalaryDisplay.html file and click View in Browser.
9. Type 75000 as Starting Salary, and type 5 as Inflation. Click Get Adjusted Salary button.
If you see an Internet Explorer warning, click Yes.




Figure 1
Internet Eplorer warning



This Warning is presented to the user because the browser is making a cross-host Ajax call (to
ajax.microsoft.com)      to prevent the popup from displaying in the future in Internet Explorer
click Tools and select Options.
       Select the Security tab.

       Click Custom Level.
       Located Display mixed content and select Enable.
Figure 2
Security Settings Dialog


      Click OK.
      Click Yes.
      Click OK.
Verify that a response is received and the Adjusted Salary is displayed.
        Figure 3
        Adjusted salary page



Task 2 – Adding a WebPart to your SharePoint Site to call the WCF service using JQuery.
In this task, you will create a simple WebPart from the HTML code snippet from exercise 1.
       1. Open Internet Explorer browser and browse to your SharePoint site.
       2. Click Site Actions, then click then Edit Page.
       3. Under the Editing Tools menu, click Insert.
       4. In the Insert ribbon, click Web Part.
       5. From the list of available categories, select Forms. Then, select HTML Form Web Part.
Figure 4
HTML Form Web Part


6. Click Add.
7. Click the drop-down menu on the inserted Web Part, and then click Edit Web Part




Figure 5
HTML Form Web Part drop/down menu


8. Click Source Editor button.
Figure 6
HTML Form Web Part


9. Clear the contents in the Text Editor window.
10. Copy the contents of the SalaryDisplay.html and paste it in the Text Editor window.
Figure 7
Text Editor Window


11. Click Save.
12. Click OK in the Message from webpage dialog box.




Figure 8
   Message from Webpage dialog


  13. Click the OK button in the HTML Form Web Part configuration pane.




   Figure 9
   HTML Form Web Part


  14. On the ribbon, click the Save & Close.
  15. Test the Web Part again. Type 75000 as Starting Salary, and type 5 as Inflation. Click Get
      Adjusted Salary button.




   Figure 10
   HTML Form Web Part


16. The Azure WCF Service is called and the Adjusted Salary is displayed.
Summary
Consuming Windows Azure-Hosted WCF services from SharePoint is easily accomplished via AJAX and
JQuery. In fact, from the perspective of SharePoint, JQuery 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. Finally, you learned how to call a WCF service from client
applications using JQuery.

								
To top