Hosting WCF Services in Windows Activation Service

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.

devx-admin

devx-admin

Share the Post:
5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within the South Korean market. Many

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles (EVs) after just one day,

Electric Spare

Electric Cars Ditch Spare Tires for Efficiency

Ira Newlander from West Los Angeles is thinking about trading in his old Ford Explorer for a contemporary hybrid or electric vehicle. However, he has observed that the majority of

Solar Geoengineering Impacts

Unraveling Solar Geoengineering’s Hidden Impacts

As we continue to face the repercussions of climate change, scientists and experts seek innovative ways to mitigate its impacts. Solar geoengineering (SG), a technique involving the distribution of aerosols

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and Dell Technologies Inc. more time