Using Service Templates with Indigo

In this sixth part of a ten-part series on the Windows Communication Foundation (WCF), aka Indigo, you'll learn how to work with service templates. This article is excerpted from chapter 1 of the book Learning WCF A Hands-on Guide, written by Michele Leroux Bustamante (O'Reilly, 2007; ISBN: 0596101627). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 2
April 17, 2008
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Service Templates

This lab introduces several Visual Studio templates for generating service code. In an existing project--no matter whether it is a class library, console application, Windows application, or web site--you can add a new WCF Service. This template generates a sample service contract and service type to get you started. If you add the WCF Service to an executable project, the template also supplies a helper class for hosting the service. When you want to create a class library for your services, you can create a WCF Service Library project. This template creates a new class library, including a sample service contract and service type. In this case, the assumption is that you'll create a separate host for the service (my personal preference). Using each of these templates also adds the appropriate service model assembly references to save you the trouble.

Service templates for web sites are slightly different from other projects because the hosting environment is slightly different. The overall result is the same--sample code is generated and assembly references are added. The difference is that an additional file is generated with a .svc extension for web hosting. You'll see this in the next lab.

ServiceModel Metadata Utility

The ServiceModel Metadata Utility is a command-line tool that is installed with the Windows SDK for .NET 3.0--an executable file named svcutil.exe. This tool can be used for two key purposes:

  1. To generate code and configuration settings from metadata
  2. To generate metadata from code and configuration

With SvcUtil you can export and import metadata, validate services, and manipulate how types are generated and shared between services and clients. Add Service Reference uses SvcUtil to generate proxies and configuration, but from the command line, you can exercise greater control over this process.

This lab illustrates a very simple command-line instruction for generating a proxy and configuration file from a metadata exchange endpoint as follows:

  svcutil /d:<YourLearningWCFPath>\Labs\ Chapter1\HelloIndigo\Client  /o:serviceproxy.cs
  /config:app.config http://localhost:8000/HelloIndigo

You can also suppress the generation of configuration output with the following instruction:

  svcutil /d:<YourLearningWCFPath>\Labs\ Chapter1\HelloIndigo\Client  /o:serviceproxy.cs
  /config:noconfig http://localhost:8000/HelloIndigo

To see all the options for SvcUtil, from the command line you can type:

  svcutil /?

Using Add Service Reference to generate the client configuration and proxy will work for many cases, but there are some cases in which you need to exercise control over things such as how arrays are handled, to make asynchronous calls to the proxy, and to share types with the service. I'll explore other uses for SvcUtil throughout this book.

Service Configuration Editor

The Service Configuration Editor is another tool that is installed with the Windows SDK for .NET 3.0--an executable file named svcconfigeditor.exe. This tool is a wizard that helps you configure service model settings for WCF clients and services. You can launch the Service Configuration Editor directly from Solution Explorer to edit the <system.serviceModel> section for any client or host application configuration file (as the lab illustrates). The wizard guides you through steps to configure services, bindings, behaviors, and more, which is particularly useful when you are new to WCF since you may not be familiar with each section of the configuration file.

The service model configuration for clients and service are both encapsulated within the<system.serviceModel>configuration section so you can use this tool to edit both sides. When starting from scratch, you can use the tool to add new services or client endpoints, to attach behaviors to services or endpoints, to supply base addresses for the host, to supply metadata exchange endpoints, and even to customize binding configurations (something I'll talk about in Chapter 3). For existing applications, you may just use the tool to view settings and make minor changes.

As I show you configuration settings throughout this book, I'll talk about many settings in the<system.serviceModel>section--all of which can be configured using the Service Configuration Editor. But you'll find that as you gain more experience with<system.serviceModel>settings, it is much more productive to edit the configuration file directly, relying on Intellisense.

ServiceModel Configuration

This lab illustrates the use of declarative configuration settings to configure the ServiceHost and the client proxy--although, in the latter case, you generated the configuration. Both ServiceHost and proxy types rely on programmatic or declarative configuration to initialize endpoints and configure behaviors. The latter technique provides greater deployment flexibility while programmatic settings enable you to enforce certain settings. In this section I'll focus on the service model configuration settings.

All configuration settings related to the service model are contained within the<system.serviceModel>section new to WCF. Any application configuration file can contain this section, which means app.config for executables, and web.config for web sites. The service model is vast and there are many configuration options, most of which will be explored throughout the book. However, the core elements of this configuration you will repeatedly use are:<services>,<client>,<bindings>,<behaviors>. Table 1-1 provides a brief explanation of each section.

Table 1-1. Summary of core <system.ServiceModel> sections

SectionDescription
<services>This element contains one or more<service>definitions. Each<service>section is associated with a particular service type and includes any base addresses and endpoints to be exposed for that type.
<client>This element contains one or more<endpoint>definitions for each service endpoint the client may consume. Each individual<endpoint>includes an address, binding, and contract matching a service endpoint. Client proxies select an endpoint to configure the client communication channel.
<bindings>This element contains one or more binding configuration sections. This makes it possible to customize a binding instead of using the defaults provided by a standard binding, such asBasicHttpBinding. I'll explore bindings in Chapter 3.
<behaviors>This element contains<serviceBehaviors>and<clientBehaviors>. At the host, the <service>configuration section may reference an element from the<serviceBehaviors>section to apply local behavioral settings to the service. At the client, endpoints defined in the<client> section may reference an element from the<clientBehaviors>section to apply local behavioral settings to the client communication channel.

Service model configuration settings can also be set at runtime through the proxy orServiceHost; however, declarative configuration is often preferred to hardcoding settings in code. You can modify configuration files without impacting the compiled service or client code and this supports more flexible deployment scenarios.

Throughout this book, you will see examples that configure the service model in code where there are practical applications for it.

ServiceHost Initialization

The first lab illustrates how to configure the ServiceHost programmatically. This lab illustrates how to configure the ServiceHost declaratively using the service model configuration section. But how does the ServiceHost know which configuration section to use? When the ServiceHost is opened, it reads the <services>section looking for a<service>element that matches its service type. From the lab, consider thisServiceHostconstructor:

  ServiceHost myServiceHost = new ServiceHost(typeof(HelloIndigo.HelloIndigoService));

TheServiceHostwill look for a<service>section using the nameHelloIndigo.HelloIndigoService, as shown here:

  <service behaviorConfiguration="serviceBehavior"
 
name="HelloIndigo.HelloIndigoService" >
   
<host>...</host>
   
<endpoint... />
   
<endpoint... />
 
</service>

The<service>element can include base addresses and service endpoints, as shown previously in Example 1-5. You can supply a base address for any protocol so that you can expose relative service endpoints over that protocol. The following illustrates the<host>section with base addresses for HTTP, TCP, and named pipe protocols:

  <host>
   
<baseAddresses>
     
<add baseAddress="http://localhost:8000/HelloIndigo" />
     
<add baseAddress="net.tcp://localhost:9000/HelloIndigo" />
     
<add baseAddress="net.pipe://localhost/HelloIndigo" />
    </baseAddresses
>
  </host>

One or more<endpoint>sections may also be provided. As discussed previously, an endpoint is defined by an address, contract, and binding. If address is omitted altogether, the base address for the related binding protocol is used (and required). If the address omits the full URI, it is appended to the base address matching the binding protocol. However, you can specify a complete address that ignores the base address. The following illustrates these three choices for an endpoint configuration:

  <endpoint binding="basicHttpBinding" name="basicHttp" contract="Host.
  IHelloIndigoService" /> 
  <endpoint address="HelloIndigoService" binding="basicHttpBinding" name="basicHttp"
  contract="Host.IHelloIndigoService" />
  <endpoint address="http://localhost:8001/HelloIndigo/
HelloIndigoService"
  binding="basicHttpBinding"  name="basicHttp" contract="Host.IHelloIndigoService" />

Endpoints have to be unique for a particular service. When multiple endpoints are exposed by a service, they must differ in address, contract, or transport protocol.

There are several reasons why a service may expose multiple endpoints, including the following:

  • The service implements multiple contracts, each requiring its own endpoint
  • The same or different service contracts must be accessible over multiple protocols
  • The same or different service contracts must be accessible by clients with different binding requirements, possibly related to security, reliable messaging, message size, or transactions

    These topics will be explored throughout the book.

Enabling Metadata Exchange

A metadata exchange endpoint is required to support the dynamic generation of proxy and configuration for client applications. You must explicitly enable metadata exchange by adding the endpoint and enabling the metadata exchange behavior.

A metadata exchange (mex) endpoint is just like any other service endpoint in that it requires an address, contract, and binding. The address for a metadata exchange endpoint requires a base address for the selected binding protocol. The contract must beIMetadataExchange, a predefined service contract belonging to theSystem.ServiceModel.Descriptionnamespace (see Example 1-7).

Example 1-7. IMetadataExchange contract as defined by the service model

[ServiceContract(ConfigurationName="IMetadataExchange",Name=
"IMetadataExchange", Namespace="http://schemas.microsoft.com/ 2006/04/mex")]

public interface IMetadataExchange
{
 
[OperationContract(Action="http://schemas.xmlsoap.org/ws/2004/ 09/transfer/Get", ReplyAction="http://schemas.xmlsoap.org/ws/ 2004/09/transfer/GetResponse", AsyncPattern=true)]
IAsyncResult BeginGet(Message request,AsyncCallback callback,object state);

  Message EndGet(IAsyncResult result);

  [OperationContract(Action="http://schemas.xmlsoap.org/ws/2004/ 09/transfer/Get", ReplyAction=http://schemas.xmlsoap.org/ws/ 2004/09/transfer/GetResponse)]
  Message Get(Message request);
}

As for the binding, there are several predefined mex bindings, includingMexHttpBinding,MexHttpsBinding,MexTcpBinding, andMexNamedPipeBinding. That means you can expose a mex endpoint over HTTP, HTTPS, TCP, or named pipes and have SvcUtil consume those endpoints.

Like any other endpoint, metadata exchange endpoints can also be consumed at runtime by clients. Applications can call mex endpoints to dynamically generate proxies or just to request information about the associated service.

The following illustrates a service exposing two TCP endpoints: one for the service, another for metadata exchange:

  <service behaviorConfiguration="serviceBehavior"
  name="HelloIndigo.HelloIndigoService">
    <endpoint address="HelloIndigoService" binding="netTcpBinding" name="netTcp"
 
contract="HelloIndigo.IHelloIndigoService" />
    <endpoint binding="mexTcpBinding" name="mex" contract="IMetadataExchange" />
    <host>
      <baseAddresses>
        <add baseAddress="net.tcp:// localhost:9000/HelloIndigo" />
      </baseAddresses>
    </host>
  </service>

Supplying the endpoint is not sufficient on its own. The service metadata behavior must also be enabled. Example 1-5 shows you how to enable the behavior by associating a service behavior to the service and including the<serviceMetadata>element. Once the behavior is enabled, you can use SvcUtil for proxy generation against any mex endpoint. For example, to generate a service proxy and configuration using the TCP endpoint with SvcUtil, you can type this instruction at the command line:

  svcutil /d:<YourLearningWCFPath>\Labs\ Chapter1\HelloIndigo\Client  /o:serviceproxy.cs
  /config:app.config
net.tcp://localhost:9000/HelloIndigo/mex

It might seem a little annoying at first that you have to enable metadata exchange before you can generate a client proxy. This opt-in behavior is actually a good thing in the long run. You don't want your services exposing endpoints of which you aren't aware or that you dont want to support.

 

Please check back next week for the continuation of this article.

blog comments powered by Disqus
BRAINDUMP ARTICLES

- Microsoft Windows 8 Committed to Cloud Compu...
- Independent Developers Favor Windows Phone 7
- Dell Introduces VMware-based Cloud
- Microsoft and Skype Agree to Acquisition Deal
- Transfer Contacts in Microsoft Outlook
- Zune`s Next Steps
- Safari Books Online Review
- Does Microsoft Get Touch Screens Now?
- Microsoft`s Record Quarterly Earnings Not En...
- Basic Operations and Registers in Assembly
- Assembly Coding within Visual C/C++ IDE
- New Microsoft Office Coming with a Twist
- Microsoft`s FUSE Labs Unveils Spindex Social...
- HP Slate with Windows 7: Dead or Alive?
- Windows Phone 7 Mobile OS to Rival Android a...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 10 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials