Generating Clients and Services with Indigo

In this fifth part of a ten-part series on the Windows Communication Foundation (WCF), aka Indigo, you'll learn how to use tools to generate clients and services. 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 / 1
April 10, 2008
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Lab: Using Tools to Generate Clients and Services 

In this lab, you will generate service code using two approaches: by adding a service to an existing host and by generating a new service library, both using Visual Studio templates. To configure service endpoint for the host, this time you'll use the Service Configuration Editor. To generate client proxies and related configuration you'll use the ServiceModel Metadata Utility (SvcUtil). Both of these tools are available through the Solution Explorer in Visual Studio.

Visual Studio extensions for WCF will be part of the next release of Visual Studio, code-named "Orcas." As such, the user interfaces and features of these extensions may change from the time of this writing.

Using the WCF Service template

In this first section of the lab, you'll create a new service using the WCF Service template and add it to an existing project. This template will add a sample service contract and service type to the project, along with the required service model assembly references. Since you will be adding the WCF Service to an executable project (the host), the template will also generate some code for hosting the service.

  1. Start by opening an existing Visual Studio solution that contains two projects: a shell console client and host. The solution is located at<YourLearningWCFPath>\ Labs\Chapter1\HelloIndigo\HelloIndigo.sln.
  2. First, you will add a new service to the host project. From Solution Explorer, right-click on theHostproject node and select Add -> New Item. Select the WCF Service template and name the file HelloIndigoService.cs.
  3. Open HelloIndigoService.cs in the code window and add a namespace qualifier for the service contract, then modify the service operation name and signature to match the following code in bold:

      [ServiceContract(Namespace=http://www.thatindigogirl.com/ samples/2006/06)]
      public interface IHelloIndigoService
      {
        [OperationContract]
       
    string HelloIndigo();
     
    }

  4. Modify the service implementation in the same file to implement the correct operation signature. This is how the resulting service type should look:

      public class HelloIndigoService : IHelloIndigoService
      {
        public string HelloIndigo()
        {
          return "Hello Indigo";
        }
      }

  5. The WCF Service template also generated a helper class for hosting the service, namedMyServiceHost, located beneath the service type. You're going to edit this class and remove the hardcoded base address provided to theServiceHostinstance.

    Locate theStartService()method inMyServiceHostand modify it so that a base address is no longer passed to theServiceHost constructor. The resulting changes are shown here:

      internal static void StartService()
      {

        myServiceHost = new ServiceHost(typeof(HelloIndigoService));
        myServiceHost.Open();
      }

  6. You're going to use the hosting helper class to initialize theServiceHost for the service. Go to theHostproject and open Program.cs. Modify theMain()entry point so that it looks as follows:

      static void Main(string[] args)
      {
        try
        {
          MyServiceHost.StartService();
          Console.WriteLine("Press <ENTER> to terminate the host application");
          Console.ReadLine();
        }
        finally
        {
          MyServiceHost.StopService();
        }
      }

  7. Compile theHostproject.

At this point, you have defined a service inside theHostproject and added code to host the service, but the implementation is incomplete. TheServiceHostrequires at least one endpoint before clients can invoke the service.

Configuring service endpoints using the Service Configuration Editor

In this section, you will provide an endpoint for the ServiceHost--this time using the Service Configuration Editor. Unlike in the previous lab, endpoints will be configured using an external application configuration file. As such, you'll open the application configuration file for the Host application using the tool to configure ServiceHost endpoints in that file.

  1. Go to theHostproject and right-click on the app.config file. Select Edit WCF Configuration. You'll see the Service Configuration Editor interface shown in Figure 1-21. Go to the Tasks pane and click "Create a New Service"; the New Service Element Wizard will be displayed.

    Follow these instructions as you go through each page in the wizard:

    a. On the first page, you are asked to provide the service type. Browse to<YourLearningWCFPath>\Labs\Chapter1\HelloIndigo\Host\Bin\Debug and select Host.exe. The Type Browser dialog (shown in Figure 1-22) will listHost.HelloIndigoServiceas the only service available in the assembly. Select it from the list and click Open. Click Next to continue.

    b. Now you will be asked to specify a service contract. There is only one service contract implemented byHelloIndigoService, so the selected service contract should beHost.IHelloIndigoService. Click Next to continue.

    c. Select HTTP as your service communication mode and click Next.

    d. Select Basic Web Services interoperability as your interoperability method and click Next.

    e. Now you'll be asked to provide an endpoint address. Here you can provide a relative address by clearing the current text and typing "HelloIndigoService." Click Next.

    f. Review the configuration you have chosen for the service, then click Finish. 


    Figure 1-21.  Service Configuration Editor for WCF
  2. Go to the Configuration pane in the Service Configuration Editor interface and expand the Endpoints folder beneathHost.HelloIndigoService. Select the only endpoint labeled (Empty Name).

    Go to the Service Endpoint pane, and in the General tab, provide the namebasicHttpas shown in Figure 1-23. At this point, you have created a single, relative service endpoint.


    Figure 1-22.  The service type browser lists all service types in a particular assembly


    Figure 1-23.  Configuring a service endpoint using the Service Configuration Editor
  3. In this lab, the client will generate a proxy using SvcUtil. To support this, you'll enable the metadata exchange behavior by adding a behavior to the service configuration.

    Go to the Configuration section and expand the Advanced folder. Select Service Behaviors and go to the Tasks pane to select New Service Behavior Configuration.

    Go to the Behavior pane and set the configuration name toserviceBehavior. Click the Add button to add a behavior element and selectserviceMetadata from the list provided.

    Go to the Configuration pane and you'll now see a newserviceMetadatanode beneathserviceBehavior. Select the node and review the default settings in the General tab.
  4. The behavior must be explicitly associated to the service. Go to the Configuration pane and select the service node,Host.HelloIndigoService. Go to the Service pane and set theBehaviorConfigurationproperty toserviceBehavior(you can select it from the dropdown list).
  5. Enabling the metadata behavior is a good start, but a new endpoint is also required to support metadata exchange. Go to the Configuration pane, right-click on the Endpoints folder, and select New Service Endpoint.

    Go to the Service Endpoint pane and set the name tomex. In the Endpoint Properties section, set the Binding tomexHttpBinding. For the Contract property type, selectIMetadataExchange.
  6. In order to support metadata exchange, the host must have a base address for the metadata exchange protocol being used. In addition, since you supplied a relative address for the service endpoint, it also requires a base address matching the binding protocol. In this case, an HTTP base address will be used.

    Go to the Configuration pane and select theHost node beneathHost. HelloIndigoService. Go to the Host pane and select New to create a new base address. From the Base Address Editor, supply the following base address: http://localhost:8000/HelloIndigo.
  7. Save the configuration settings you just generated. Select File -> Save followed by File -> Exit. Return to Visual Studio and open the app.config for theHostproject. You will see a<system.serviceModel>section like the one shown in Example 1-5.
  8. Compile theHostproject and then run it. Leave the host running for the next step.

Example 1-5. Service model configuration generated by Service Configuration Editor

<system.serviceModel>
  <behaviors>
    <serviceBehaviors>
      <behavior name="serviceBehavior">
        <serviceMetadata />
      </behavior>
    </serviceBehaviors>
  </behaviors>
 
<services>
    <service behaviorConfiguration="serviceBehavior" name="Host.HelloIndigoService" >
      <endpoint address="HelloIndigoService" binding="basicHttpBinding"
name="basicHttp" contract="Host.IHelloIndigoService" />
     
<endpoint binding="mexHttpBinding" name="mex" contract="IMetadataExchange" />
     
<host>
       
<baseAddresses>
          <add baseAddress="http://localhost:8000/HelloIndigo" />
        </baseAddresses>
      </host>
    </service>
  </services>   
</system.serviceModel>

You just created a declarative configuration for theServiceHost, instead of programmatically initializing its base addresses and service endpoints. In addition, you enabled the service metadata behavior and created a metadata exchange endpoint so that clients can generate a proxy using SvcUtil. That's the next step.

Generating a proxy with Add Service Reference

It's time to generate code for the client to consume the service, starting by generating a client proxy. To achieve this you will use the Add Service Reference functionality exposed by Visual Studio, which uses the ServiceModel Metadata Utility (SvcUtil) to generate a proxy and configuration settings for that proxy.

  1. Go to theClient project and from Solution Explorer, right-click on theClientproject node and select Add Service Reference. The dialog presented requires you to provide a valid base address to the service. Supply the base address http:// localhost:8000/HelloIndigo and leave the Service reference name aslocalhost. When you close this dialog, a service proxy and configuration file will be generated for the client application. Stop debugging so you can add code to the client application.

    To see the proxy, go to theClientproject and expand the Service References folder. Beneath it you will see localhost.map, and beneath that localhost.cs--the latter of which contains the proxy.

    A new configuration file, app.config, was also added to the project. This contains the service model configuration for the proxy. Later I'll talk about how these things come together.
  2. Add code to the client application to invoke the service using the generated proxy. Go to theClientproject and open Program.cs. Add code to theMain()entry point as shown in bold in Example 1-6.
  3. Compile the solution and run theHostproject, followed by theClient. The client's console output should show the result of invoking the service'sHelloIndigo operation.

Example 1-6. Using a generated proxy to invoke a service

static void Main(string[] args)
{
 
localhost.HelloIndigoServiceClient proxy = new
Client.localhost.HelloIndigoServiceClient()
  string s = proxy.HelloIndigo();
  Console.WriteLine(s);

  Console.WriteLine("Press <ENTER> to terminate Client.");
  Console.ReadLine();
}

This concludes one technique for generating a service,ServiceHostconfiguration, and a client proxy.

Creating a WCF Service Library

In this section, you will generate a service using another technique: adding a new class library that includes a WCF service. The WCF Service Library template is a quick and easy way to generate a new class library with a sample service contract, service type, and the appropriate assembly references.

  1. Go to the Solution Explorer and right-click on the solution node. Select Add -> New Project and select the WCF Service Library template. Name the projectHelloIndigo.
  2. Rename the class file from Class1.cs to HelloIndigoService.cs.
  3. Modify the service contract that is supplied by the project template. Open HelloIndigoService.cs in the code window and provide a namespace for theServiceContractAttributeand change the interface definition to look as follows:

      [ServiceContract(Namespace=http://www.thatindigogirl.com/ samples/2006/06)]
      public interface IHelloIndigoService 
      {
        [OperationContract]
        string HelloIndigo();
      }

  4. Now, modify the service implementation so that it implements the new contract. Rename the service toHelloIndigoServiceand implementIHelloIndigoServiceas shown here:

      public class HelloIndigoService: IHelloIndigoService
      {
        public string HelloIndigo()
        {
          return "Hello Indigo";
        }
      }


    Compile theHelloIndigoproject.

    The default data contract created when you used the WCF Service template is not necessary for this lab.
  5. Now you will modify the existing host project so that it hosts this new service. Go to theHostproject and open HelloIndigoService.cs. Comment the entire service contract and implementation to avoid collision with theHelloIndigolibrary you're about to reference.
  6. Add a reference to theHelloIndigoclass library project. Right-click on theHostnode and select Add Reference. From the Projects tab, select theHelloIndigoproject.
  7. TheServiceHostmust be modified to refer to the service type from this project. In the HelloIndigoService.cs file, find theStartService()method and modify theServiceHost constructor to use the fully qualified name of the service,HelloIndigo.HelloIndigoService, as shown here:

      myServiceHost = new ServiceHost(typeof(HelloIndigo.HelloIndigoService));
  8. You'll also have to edit the service model section of the configuration file to use the correct service and contract types. Go to theHost project and open the app.config file. Change the service type and contract type for the<service>configuration section as shown here in bold:

      <service behaviorConfiguration="serviceBehavior" name="HelloIndigo.
      HelloIndigoService">
        <endpoint address="HelloIndigoService" binding="basicHttpBinding" name="basicHttp" contract="HelloIndigo.IHelloIndigoService" />

      <!-- other settings -->

    </service>

  9. Test the solution again by compiling and running theHostand then theClient.

Now you have learned how to create a new class library with a sample WCF service and seen the changes required to the service model configuration andServiceHostto reference a different service type.

Generating a proxy using the Service Model Metadata Utility

In this section, you will generate a client proxy using the SvcUtil directly instead of using Add Service Reference. The purpose of this exercise is to show you how to exercise greater control over the generation of proxies and configuration settings.

  1. First, run theHostproject so that the endpoint is available to generate a proxy.

    From the Windows Start menu, find the Microsoft Visual Studio 2005 program group and launch the Visual Studio 2005 Command Prompt. Run the following command to generate a new proxy for the client application and replace the application configuration settings generated previously: 

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

    The output should look similar to Figure1-24.

    The/d:option for SvcUtil allows you to provide a path where output files will be generated. In the Preface, I explained that I would be using the term <YourLearningWCFPath> to refer to your base path--where you unzipped the file provided with the book. Thus, if your base path is c:\LearningWCF, then your SvcUtil command in this example would be: 

      svcutil /d:c:\LearningWCF\Labs\ Chapter1\HelloIndigo\Client   /o:serviceproxy.cs/config:app.config
      http://localhost:8000/HelloIndigo

    If your path includes spaces, such as c:\Learning WCF, then you will have to provide quotes to the path, as shown here:

      svcutil /d:"c\Learning WCF\Labs\ Chapter1\HelloIndigo\Client"   /o:serviceproxy.cs/config:app.config
    http://locahost:8000/
      HelloIndigo
  2. To use this proxy you'll have to modify the client application. Go to theClient project. If you select the "Show all files" icon in Solution Explorer, you'll see a new file beneath the project node. Right-click serviceproxy.cs and select "Include in Project." Right-click localhost.map beneath Service References and select "Exclude from Project."

    Now open Program.cs and modify the code that constructs the service proxy. The proxy that was generated does not belong to a namespace, so you must remove the fully qualified name forHelloIndigoServiceClient. The resulting code is:

      using (HelloIndigoServiceClient proxy = new HelloIndigoServiceClient())
  3. Compile and run the solution once again.

Now let's examine some of the ideas introduced in this lab in greater detail.


Figure 1-24.  Output generated when SvcUtil generates a service proxy and configuration settings for the client

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 3 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials