Hosting WCF Services in Windows Activation Service

indows Activation Service (WAS), introduced with Windows Vista, is the new process activation mechanism that ships with IIS 7.0. WAS builds on the existing IIS 6.0 process and hosting models, but is much more powerful because it provides support for other protocols besides HTTP, such as TCP and Named Pipes.

By hosting the Windows Communication Foundation (WCF) services in WAS, you can take advantage of WAS features such as process recycling, rapid failover protection, and the common configuration system, all of which were previously available only to HTTP-based applications. This article explores the steps involved in using WAS to host and consume WCF services.

Hosting Options for WCF
When hosting WCF services, you now have three choices:

  1. Windows Activation Service (WAS) hosting environment
  2. Executable (.exe) applications (including Console and Windows Forms applications)
  3. Windows Services

The WAS hosting environment is a broad concept that extends the ASP.NET HTTP pipeline hosting concept primarily used for ASMX web services. WAS is implemented as a Windows service in Windows Vista. As a standalone Windows component it’s completely separate from the legacy IIS host and does not carry all the overhead associated with IIS while still providing a flexible and stable hosting environment for WCF services. In addition, by providing a protocol-agnostic activation mechanism (meaning you aren’t limited to HTTP), WAS allows you to choose the most appropriate protocol for your needs

A WCF service hosted in WAS works similarly to an ASMX Service. For the HTTP protocol, it relies on the ASP.NET HTTP pipeline to transfer data. For non-HTTP protocols such as TCP and Named Pipes, WAS leverages the extensibility points of ASP.NET to transfer data. These extensibility hooks are implemented in the form of protocol handlers that manage communication between the worker process and the Windows service that receives incoming message. There are two types of protocol handlers: Process Protocol Handler (PPH) and App Domain Protocol Handler (ADPH). When the WAS activates a worker process instance, it first loads the required process protocol process handlers and then the the app domain protocol handlers.

What You Need
  • Visual Studio 2005 Professional RTM
  • Microsoft Windows Vista
  • Microsoft Windows Vista SDK

Setting up WAS
Before getting into the steps involved in setting up WAS, create a new WCF Service project named WASHostedService through Visual Studio 2005. I’ve used C# for the examples here, but you can easily translate them to VB.NET.

 
Figure 1. WAS Hosting for Non-HTTP Protocols: To make your WCF services available for remote invocation through TCP, Named Pipe and MSMQ protocol bindings, turn on the WCF Non-HTTP Activation feature through the Windows Features dialog box.

In Windows Vista, you need to perform two steps to host WCF services in WAS. First, install the WCF Non-HTTP activation components. To do that, go to the Start menu ?> Control Panel ?> Programs and Features, and then click “Turn Windows Components On or Off” in the left pane. Expand the Microsoft .NET Framework 3.0 node and ensure that the “Windows Communication Foundation Non-HTTP Activation” feature is checked as shown in Figure 1.

Second, to use a non-HTTP protocol such as TCP or Named Pipes, you need to add the site binding to the WAS configuration. As an example, here’s how you’d bind the default web site to the TCP protocol. Go to the Start menu ?> Programs ?>Accessories. Right click on the “Command Prompt” item, and select “Run as administrator” from the context menu. You’ll see a command prompt that has the requested elevated administrator permissions so you can execute administrator commands. Execute the following command:

   Windowssystem32inetsrvappcmd.exe set       site "Default Web Site" --      +bindings.[protocol='net.tcp',bindingInformation='808:*']

That command adds the net.tcp site binding to the default web site by modifying the applicationHost.config file located in the Windowssystem32inetsrvconfig directory.

After binding the default web site to the appropriate protocol, you need to enable the individual web applications to support the same protocol. To enable net.tcp for the WASHostedService site, run the following command from an administrator-level command prompt:

   %windir%system32inetsrvappcmd.exe set app       "Default Web Site/MyProjects/DevX/WASHostedService"       /enabledProtocols:http,net.tcp

Now that you have set up the web site and application, you are ready to create a service and host it in WAS.

Creating the Service
To start, add a service named HelloWorldService.svc to the WASHostedService project. The newly added HelloWorldService.svc contains the following lines of code.

   <%@ ServiceHost Language="C#"      Debug="true" Service="HelloWorldService"     CodeBehind="~/App_Code/HelloWorldService.cs" %>

Note that the HelloWorldService.svc has a code-behind file named HelloWorldService.cs that Visual Studio places in the App_Code directory. Open up the HelloWorldService.cs file and modify its code as follows:

   using System;   using System.ServiceModel;      [ServiceContract()]   public interface IHelloWorldService   {      [OperationContract]      string HelloWorld(string input);   }      public class HelloWorldService : IHelloWorldService   {      public string HelloWorld(string input)      {         return "Hello: " + input;      }   }

The preceding code decorates the interface IHelloWorldService definition with the [ServiceContract] attribute to indicate that this interface contains the service operation definitions. To expose the individual methods in the interface as service operations, you specify the [OperationContract] attribute. After defining the service contract in an interface, you can then implement the methods inside the actual class?HelloWorldService in this case.

After creating the service, you need to specify the service behavior in the configuration file. Configuring the service behavior in an external configuration file lets you customize the service behavior without having to modify and recompile the service code. To host the HelloWorldService in WAS, modify the Web.config file in the service project as follows:

                                                                                                                                                                                                                                                   

Through its attributes, the element under specifies the name of the service as well as the name of the behavior configuration that you want to use to control the service’s behavior. The element also contains another child element named where you specify the address, contract, and binding for the service. Note that the contract attribute is set to the name of the interface?IHelloWorldService. To expose the service through TCP binding, set the binding attribute to netTcpBinding. Finally, the separate element defines specific characteristics of the TCP binding, such as security.

Creating the Client
To test the HelloWorld service, create a new Visual C# Windows Forms application and name it WASHostedServiceClient.

 
Figure 2. Svcutil.exe Output: The Svcutil.exe utility downloads a service’s WSDL file using that and related service metadata to create a client side proxy and configuration file.

Next, you’ll need to create a proxy for the WCF service described earlier in this article. You’ll also need to create a configuration file containing the settings required to connect to the service. You can accomplish both tasks through the Service Model Metadata Utility (svcutil.exe), which builds a proxy and corresponding configuration file based on a published service’s metadata. For example, here’s the command to run svcutil.exe to create a proxy and configuration file for the HelloWorldService:

   svcutil.exe net.tcp://localhost/MyProjects/DevX/      WASHostedService/HelloWorldService.svc/mex

Figure 2 shows the output produced by the preceding command.

The output from Figure 2 has two files:

  1. A WCF proxy (a C# class file in this case) that translates method calls to messages dispatched to the service.
  2. An output.config file (with the settings based on the service configuration) that clients can use to communicate with the service.

Now add the created proxy file to the WASHostedServiceClient project. Also rename the output.config file created with svcutil to App.config and add that to the WASHostedServiceClient project as well. The App.config file contains a number of configuration entries related to the invocation behavior of the client. The following code highlights the important sections of the App.config file:

                                                                                                                                

The element is the root of the service client configuration section. Inside that are the and elements where you specify the binding details and endpoint details respectively.

At this point, you are ready to consume the service by writing code against the proxy. To do that, add a command button named btnHelloWorld to the form and modify its Click event-handling code as follows:

   private void btnHelloWorld_Click(object sender, EventArgs e)   {      HelloWorldServiceClient client = new HelloWorldServiceClient();      MessageBox.Show(client.HelloWorld("Thiru"));   }

The implementation simply invokes the HelloWorld() method of the HelloWorldService using the proxy class (generated through the svcutil utility) from the previous section and displays the results of the invocation via a message box.

You’ve seen the steps involved in using TCP binding to host the service in WAS. The next section discusses how to use Named Pipe binding to host a service in WAS.

Using Named Pipe Activation
As part of the implementation of this service, it’s important to understand the basics of data contracts and their role in returning complex type data from the service.

Just as in the previous example, you first need to bind the net.pipe protocol to the default web site. Use the following command from an elevated administrator command prompt.

   Windowssystem32inetsrvappcmd.exe set site       "Default Web Site" -+bindings.[protocol='net.pipe',      bindingInformation='*']

Then enable the named pipe activation for the WASHostedService virtual directory as follows:

   Windowssystem32inetsrvappcmd.exe set app       "Default Web Site/MyProjects/DevX/WASHostedService"       /enabledProtocols:http,net.pipe

The preceding command enables net.pipe support for the WASHostedService application.

You define a data contract by decorating a class, structure, or enumeration with the [DataContract] attribute and identifying the members by placing [DataMember] attributes on the fields or properties of the class. Here’s an example. Add a new class file named Product.cs to the WASHostedService project and modify its code as follows:

   using System;   using System.Runtime.Serialization;      [DataContract]   public class Product   {      [DataMember]      public int ProductID;         [DataMember]      public string Name;         [DataMember]      public string ProductNumber;          }   

You can leverage the data contract from a WCF service. Add a WCF service named ProductService.svc to the project and modify its code-behind file as shown in Listing 1:

The GetProductByProductID() method in Listing 1 is straightforward. It retrieves a connection string from the Web.config file, opens a database connection, creates a SQL command string and a SqlCommand object, and executes the query against the database using the SqlCommand.ExecuteReader() method. It loops through the data returned in the resultant SqlDataReader object, filling a new Product object with the retrieved values, then returns that to the client.

To configure the Named Pipe binding for this service, add the section shown below directly underneath the / element in the app.config file:

                

The configuration sets the behaviorConfiguration and binding values to ProductServiceBehavior and netNamedBinding respectively. You can define these (starting with NetNamedPipeBinding) by adding the following lines of code directly underneath the / section as shown below:

                             

Finally, define the ProductServiceBehavior by adding the following section to the // section.

                

That’s all you have to do to support Named Pipe binding from the service side.

Consuming the Product Service
From the client side, just as in the previous example, the first step in consuming a service is to create a proxy and configuration file for the client. Again, you use svcutil.exe. For the ProductService, you can accomplish that with the following line of code from the command prompt.

   svcutil.exe net.pipe://localhost/MyProjects/DevX/      WASHostedService/ProductService.svc?WSDL

That creates a proxy file and a configuration file. Add the created proxy file to the WASHostedServiceClient project. From the output.config file, copy the and sections to the App.config file. I’ve highlighted these sections in the output.config file shown below:

                                                                                                                 

To test the service, add a command button named btnGetProduct and a list box named lstResults to the form and modify the button’s Click event as follows:

 
Figure 3. Testing the ProductService: When you enter a product id in the text box and click on the Get Product button, the Windows form invokes the GetProductByProductID() method to get the product details and displays the results in the list box control.
   private void btnGetProduct_Click(      object sender, EventArgs e)   {      ProductServiceClient client = new          ProductServiceClient();      Product prod = client.GetProductByProductID         (Convert.ToInt32(txtProductID.Text));      lstResults.Items.Clear();      lstResults.Items.Add(prod.ProductID.ToString());      lstResults.Items.Add(prod.Name);      lstResults.Items.Add(prod.ProductNumber);               }

The preceding code passes in a user-entered ProductID value to the service, which retrieves the product details and returns a Product object. Finally, it displays the product detail results in the list box. Figure 3 shows the output produced by the Windows form.

   

This article showed you the steps involved in using WAS to host WCF services and examples of how to use TCP and Named Pipe bindings to host and consume the WCF services. You’ve seen how to use some key WCF concepts?including the use of configuration files?to define the service behavior. To consume the services, you saw how to use the Service Model Metadata Utility (svcutil.exe) to create proxies and configuration, both for simple data types and for more complex types that require data contracts. All in all, WAS is both a more powerful and more flexible host for WCF services than IIS, and is a welcome addition to developers’ toolkits.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS