Consuming WCF Services

In the previous sections, you learned about the different hosting options you have. The chosen hosting scenario can have its influence on the consumer side. You can consume WCF services in several ways. If you are using WCF on the client side, you will be very productive because WCF comes with tools that can generate proxy classes to call WCF services. WCF provides the standards and tools support primarily through SvcUtil.exe. You'll use this as the primary metadata interpretation tool. That, in combination with the WCF Framework's ability to leverage reflection to interrogate types adorned with the appropriate attributes, makes the generation and use of the WCF Framework less complicated than with existing frameworks. In addition, Visual Studio 2005 comes with easy-to-use features to add service references to your projects and seamlessly generate proxy classes for you.

Essentially, you have the following options:

  • Retrieve the WSDL from the service, and handcraft a proxy to call the service. This is a typical scenario when you don't have WCF on the client side. For this scenario, please refer to Chapter 13.

  • Use the Add Service Reference features of Visual Studio 2005, and let it generate a proxy to use in your client.

  • Use the SvcUtil.exe tool to generate proxy classes.

In the following sections, we will go through the latter two options: Visual Studio 2005 and SvcUtil.exe.

Service Proxies

A service proxy enables you to work with services in an object-oriented way. Proxy classes abstract the communication model used by the service so you as a client developer are not directly aware you are talking to a (remote) service. It is as if you are calling local code. The proxy class implements the service interface of the service and thus enables you to call methods on the service interface as if these are local methods. Proxies are generated for any custom type that is used in the service interface. Listing 5-11 contains pieces of a generated proxy for the TradeService service in the QuickReturns Ltd. sample. It illustrates that on the client side a Quote is available that maps to the Quote object on the server side, although they are distinct classes. The Quote object serializes according to the contract so that on the service side it can be serialized into the service-side version of the Quote data contract. In addition, you can see the GetQuote and PlaceQuote methods calling a base class that will eventually make the call across the service boundary via the configured transport.

Example. Sample Generated Proxy for the TradeService Service
namespace SimpleClientWithProxy.ExchangeService
{
   [DataContract()]
public partial class Quote : object, IExtensibleDataObject
    {
      // Left out the Quote Datamembers in printed code, see sample code
   }
}

[GeneratedCode("System.ServiceModel", "3.0.0.0")]
[ServiceContract()]
public interface ITradeService
{
   [
      OperationContract(Action = "http://tempuri.org/ITradeService/GetQuote",
         ReplyAction = "http://tempuri.org/ITradeService/GetQuoteResponse")]
   Quote GetQuote(string ticker);

   [
      OperationContract(Action = "http://tempuri.org/ITradeService/PublishQuote",
         ReplyAction = "http://tempuri.org/ITradeService/PublishQuoteResponse")]
   void PublishQuote(Quote quote);
}

[GeneratedCode("System.ServiceModel", "3.0.0.0")]
public interface ITradeServiceChannel : ITradeService, IClientChannel
{
}

[GeneratedCode("System.ServiceModel", "3.0.0.0")]
public partial class TradeServiceClient : ClientBase<ITradeService>, ITradeService
{
   // Left out some constructors in printed code, see sample code

   public SimpleClientWithProxy.ExchangeService.Quote
							GetQuote(string ticker)
							{
							      return base.Channel.GetQuote(ticker);
							}
							   public void PublishQuote(
							SimpleClientWithProxy.ExchangeService.Quote quote)
							{
							 base.Channel.PublishQuote(quote);
							}
							}

Using Visual Studio 2005

Similar to ASP.NET proxy creation, if you right-click the project from the IDE, you'll see three options for adding references, as shown in Figure 5-17.

Adding a reference to a WCF service

The option you're looking for is Add Service Reference. This menu option is a wrapper around the SvcUtil.exe utility (which is explained in the next section), actually spawning a process with the necessary parameters. Once you've selected Add Service Reference, you'll see the dialog box shown in Figure 5-18.

Add Service Reference dialog box

Once you've clicked OK in the dialog box, the add-in spawns SvcUtil.exe, generating the necessary proxy class and the required configuration file (or modifying it) and adding the necessary references to the project. The project's references will now list the WCF assemblies.

NOTE

For this to work, you have to have the Windows ServiceHost running or change the URL to point to any of the services hosted in IIS (a URL pointing to any of the .svc files).

At this point, you're now ready to program your first service call in your service tier. The example solution file has been modified in the following ways to help you review the code:

  • Set Startup Projects on the solution has multiple projects selected.

  • The ExchangeServiceIISHost web project has Use dynamic ports set to false and a hard-coded setting for Port Number.

A brief explanation of the objects added to the project is necessary. During the SvcUtil.exe (Add Service Reference) call, we added the following items and references to the project automatically. Some are merely to aid the Visual Studio integration; others are required for the direct use of the service through the proxy.


Service references

Within this folder, we added two items. First, a "map" file provides support for the generation and regeneration of the proxy through the Visual Studio add-in. Second, ExchangeService.cs represents the concrete proxy class implementation that leverages the namespace System.ServiceModel to provide a simple integration class.


Configuration

The second item is the App.config file. An App.config file (automatically renamed during the Visual Studio build process to <assembly name>.config) provides the runtime WCF configuration parameters. What you will notice if you peek inside this file is a tremendous amount of settings, many of which are either defaulted or superfluous. A general approach is to generate the file and then manage the file using the WCF SvcConfigEditor.exe editor utility. This utility is located in the Windows SDK Bin directory. You can also find it in the Visual Studio 2005 Tools menu. Figure 5-19 shows the implementation of the tool.

SvcConfigEditor.exe

As you can see from the SvcConfigEditor.exe screen in Figure 5-19, you can manage a tremendous amount of detailed properties through configuration. This is one of the greatest strengths of WCF—the ability to control many aspects of an implementation without impacting the core service implementation. The concept that a service implementation doesn't need to change in order to migrate from an HTTP-based protocol to another message-oriented one is an example. To get more information about the features of the tool, refer to Chapter 3 of this book or the MSDN help.

Command-Line Implementation

An alternative method is to leverage the SvcUtil.exe utility directly instead of the Visual Studio add-in. Again, the Visual Studio add-in calls the SvcUtil.exe, with parameters, to generate the proxy when executed directly from within Visual Studio. You can see the command line and results of that command by viewing the Output window and setting the Show output in the drop-down list to Service Reference.

To generate manually, choose the CMD window by selecting Start All Programs Microsoft Windows SDK CMD. This command prompt is useful because its path is set to the binary directory where the SDK tools and utilities are located.

You'll use the SvcUtil.exe command-line tool to generate two outputs that could be used in the SimpleClientWithProxy project. However, the sample code that comes with this chapter used the Add Service Reference method described in the previous section. The steps described here explain how to generate the same outputs as Add Service Reference. The output files it generates are the client proxy source code file and the application configuration file. These files are then merged into the client project. The SvcUtil.exe can generate both. For this example, the following command (it is all a single line despite what's shown here) produces both a proxy class and a configuration file:

svcutil /config:app.config /out:"ExchangeService.cs" /language:csharp /n:*,
SimpleClientWithProxy.ExchangeService "http://localhost/ExchangeService/
ExchangeService.svc"

NOTE

For this to work, you need a running version of the Windows ServiceHost, or you have to change the URL to point to any of the services hosted in IIS (a URL pointing to any of the .svc files discussed in this chapter). In addition, your service requires the metadataexchange endpoint, as described in Chapter 3. The code that comes with this chapter has the metadataexchange endpoint configured, but it is left out of the inline code in this chapter!

The command is fairly self-explanatory. The /n switch indicates under which namespace the generated proxy class should fall. The last parameter is the URL of the service endpoint where schema information can be found. Note that the ?wsdl can be replaced by ?mex because SvcUtil.exe supports both methods of discovery. Further help is available by executing svcutil.exe /? from the command prompt.

The next step is to take the output files ExchangeService.cs and App.config and merge them into the project. You can just add the first file, ExchangeService.cs, directly to the project by choosing Add Existing Item from the Project menu in Visual Studio 2005.

You need to add the second file as an application configuration (App.config) file to the project. If the project does not already have an App.config file, you can add it by again choosing Add Existing Item from the Project menu. If there is already an existing App.config, you need to merge the section system.serviceModel, ensuring you take all the appropriate child elements.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset