Creating Services with the WCF

In this third part of a ten-part series on the Windows Communication Foundation (WCF), aka "Indigo," you will learn about message processing, services, and more. 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 / 3
March 27, 2008
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

Addresses

Each endpoint is associated with an address, identified by a URI. An address has a scheme, domain, port, and path in the following format: scheme://domain[:port]/ [path].

The scheme indicates the transport protocol being used, such as TCP, named pipes, HTTP, or MSMQ. Respectively, the schemes for these protocols are net.tcp, net.pipe, http, and net.msmq. The domain refers to either a machine name or web domain. Sometimes localhost is used for communications on the same machine. The port can be specified to use a specific communication port other than the default for the protocol identified by the scheme. For example, HTTP defaults to port 80. Here are some examples of valid base addresses before specifying a path:

  net.tcp://localhost:9000
  net.pipe://mymachinename
 
http://localhost:8000
  http://www.anydomain.com
 
net.msmq://localhost

A path is usually provided as part of the address to disambiguate service endpoints. The path does not usually include a filename for self-hosting, but with IIS (as you will see later in this chapter) a physical file is implicitly included in the address. These are valid self-hosting addresses that include paths:

  net.tcp://localhost:9000/ServiceA
  net.pipe://mymachinename/ServiceB  
  http://localhost:8000/Services/ ServiceA
  http://www.mydomain.com
/ServiceA
/Services/ ServiceA /ServiceA
  net.msmq://localhost/QueuedServices/ ServiceA

When you add endpoints to aServiceHost instance, you must specify a unique address for each endpoint. That means that you must vary at least one of the scheme, domain, port, or path specified.

Bindings

A binding describes the protocols supported by a particular endpoint, specifically, the following:

  1. The transport protocol, which can be TCP, named pipes, HTTP, or MSMQ
  2. The message encoding format, which determines whether messages are serialized as binary or XML, for example
  3. Other messaging protocols related to security and reliability protocols, plus any other custom protocols that affect the contents of the serialized message

There are a number of predefined bindings (called standard bindings) provided by the service model. These standard bindings represent a set of typical protocols representative of common communication scenarios. Bindings are discussed in detail in Chapter 3.

Metadata

Once the ServiceHost is configured for one or more endpoints, and communication channels are open, service operations can be invoked at each endpoint. This is according to the protocols supported by each endpoint. Clients invoke service operations at a particular endpoint. To do so, they need information about the endpoint, including the address, the binding, and the service contract. Information about service endpoints is part of the metadata for a particular service. Clients rely on this metadata to generate proxies to invoke the service.

Metadata can be accessed in two ways. TheServiceHostcan expose a metadata exchange endpoint to access metadata at runtime, or it can be used to generate a WSDL document representing the endpoints and protocols supported by the service. In either case, clients use tools to generate proxies to invoke the service.

You'll explore different ways to work with service metadata throughout this chapter, and Chapter 2 discusses metadata in further detail.

Proxies

Clients communicate with services using proxies. A proxy is a type that exposes operations representative of a service contract that hides the serialization details from the client application when invoking service operations. For WCF applications, proxies are based on the service contract, so if you have access to the service contract definition, you can create a proxy instance to invoke the service. Before the proxy instance can be used to call service operations, it must be provided with information about one of the endpoints exposed for that service contract--there is a one-to-one relationship between proxy and endpoint.

Tools also exist to generate proxies and endpoint configurations from metadata. In this chapter, you will learn how to create a proxy manually, without generating metadata, and how to use proxy generation tools. In either case, the client must open a communication channel with the service to invoke operations. This channel must be compatible with the channel exposed by theServiceHostfor communications to work.

Channels

 

Channels facilitate communication between clients and services in WCF. The ServiceHost creates a channel listener for each endpoint, which generates a communication channel. The proxy creates a channel factory, which generates a communication channel for the client. Both communication channels must be compatible for messages between them to be processed effectively. In fact, the communication channel is comprised of a layered channel stack--each channel in the stack is responsible for performing a particular activity while processing a message. The channel stack includes a transport channel, a message-encoding channel, and any number of message processing channels for security, reliability, and other features. Without getting into specifics, the binding controls which channels participate in the channel stack, as shown in Figure 1-16. (The details of channels and bindings are explored in Chapter 3.)


Figure 1-16.  Messages are processed by equivalent channels at the client and service

Behaviors

Behaviors also influence how messages are processed by the service model. While services and endpoints determine the core communication requirements and metadata shared with clients, a behavior modifies the way messages are processed as they flow through the channel stack. Behaviors are local to the client or service--thus, they are not included in metadata.

There are behaviors to control many service model features such as exposing metadata, authentication and authorization, transactions, message throttling, and more. Behaviors are enabled either in configuration or by applying behavior attributes to client proxies and services.

In this chapter, you'll learn how to apply the metadata behavior to a service, but other behaviors will be explored throughout this book as they relate to each feature.

Creating a New Service from Scratch

You're about to be introduced to the WCF service. This lab isn't your typical "Hello World"--it's "Hello Indigo"! In this lab, you will learn how to build a new WCF service and in the process learn the minimum requirements of service development and consumption. Here's a short list of things you'll accomplish:

  1. Create a new service contract and service implementation
  2. Programmatically configure a service host, its endpoints, and bindings
  3. Create a client application and open a client channel proxy to invoke the service

Now, before you start thinking "been there, done that," this simple lab will be slightly different because I'm going to give you some practical design tips that ensure configurability and appropriate decoupling of service, host, and client. In addition, I'll be diving deeper into basic concepts such as services, service contracts, endpoints, bindings,ServiceHost, and channels.


Lab: Creating Clients and Services Programmatically


In this first lab, you will create a new solution with three projects: a service, a host, and a client. When you run the service host, you'll expose a single service endpoint. The client application will access service operations through that endpoint. You'll host the service in a console application and invoke the service using a manually constructed proxy. This lab will teach you the basic requirements for creating, hosting, and consuming a service with WCF.

Creating a new service

The first thing you will do is create a new service contract with a single operation and implement this contract on a new service type.

  1. In this lab, everything begins from scratch, so you'll start by creating a new Visual Studio solution. Open a new instance of Visual Studio 2005. Select File -> New -> Project, and from the New Project dialog, create a new Blank Solution in the <YourLearningWCFPath>\Labs\Chapter1 directory. Name the solutionServiceFromScratch. Click OK to create the empty solution.
  2. Create the service project. From Solution Explorer, right-click on the solution node and select Add -> New Project. Select the Class Library template, name the projectHelloIndigo, and make sure the location path matches the solution at <YourLearningWCFPath>\Labs\Chapter1\ServiceFromScratch. Click OK to create the new project.
  3. Now you will create your first service contract. From Solution Explorer, rename the project's only class file to Service.cs. Open this file in the code window.

    Add a new interface namedIHelloIndigoServicein Service.cs. Add a single method to the interface,HelloIndigo, with the signature shown here:

      public interface IHelloIndigoService
      {
         string HelloIndigo();
      }

  4. Add a reference to theSystem.ServiceModelassembly. From Solution Explorer, right-click References and selectSystem.ServiceModelfrom the list. You'll also need to add the followingusingstatement to Service.cs:

      using System.ServiceModel;
  5. To turn this interface into a service contract, you'll need to explicitly decorate the interface with theServiceContractAttribute. In addition, each method should be decorated with theOperationContractAttributeto include it in the service contract. In this case, you'll makeIHelloIndigoServicea service contract and exposeHelloIndigo()as its only service operation by applying these attributes as shown here:

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


    Providing a namespace for theServiceContractAttributereduces the possibility of naming collisions with other services. This will be dicussed in greater detail in Chapter 2.
  6. In the same file, create a service type to implement the service contract. You can modify the existing class definition, renaming it toHelloIndigoService. Then add theIHelloIndigoServiceinterface to the derivation list and implementHelloIndigo()with the following code:

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

  7. Compile the service project.

At this point, you've created a service contract with a single operation and implemented it on a service type. The service is complete at this point, but to consume it from a client application, you will need to host it first.

Hosting a service

Next, add a new console application to the solution. This will be the host application. You'll instantiate a ServiceHost instance for the service type and configure a single endpoint.

  1. Go to the Solution Explorer and add a new Console Application project to the solution. Name the new projectHost.
  2. Add a reference to theSystem.ServiceModelassembly, and add the followingusingstatement to Program.cs:

      using System.ServiceModel;
  3. You will be writing code to host theHelloIndigoServicetype. Before you can do this, you must add a reference to theHelloIndigoproject.
  4. Create aServiceHostinstance and endpoint for the service. Open Program.cs in the code window and modify theMain()entry point, adding the code shown in Example 1-1. This code initializes aServiceHostinstance specifying the service type and a base address where relative service endpoints can be located. It also adds a single relative endpoint for the service. In this case, a base address is provided for HTTP protocol, and the relative endpoint uses one of the standard bindings,BasicHttpBinding, based on HTTP protocol.
  5. Compile and run the host to verify that it works. From Solution Explorer, right-click on theHostproject node and select "Set as Startup Project." Run the project (F5), and you should see console output similar to that shown in Figure 1-17.
  6. Stop debugging and return to Visual Studio.

Example 1-1. Code to programmatically initialize the ServiceHost

static void Main(string[] args)
{
  using (ServiceHost host = new ServiceHost(typeof(HelloIndigo.HelloIndigoService),
new Uri(http://localhost:8000/HelloIndigo)))
  {
    host.AddServiceEndpoint(typeof(HelloIndigo.IHelloIndigoService),
new BasicHttpBinding(), "HelloIndigoService");
    host.Open();

    Console.WriteLine("Press <ENTER> to terminate the service host");
    Console.ReadLine();
  }
}


Figure 1-17.  Console output for the host application

You now have a host application for the service. When it is running, clients will be able to communicate with the service. The next step is to create a client application.

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