Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

Friday, September 14, 2012

WCF Data Services

What is OData?

OData (known as Open Data Protocal) is a web protocal for querying and updating data. It is used to expose and access information from a variety of sources like relational databases, file systems, web sites etc.
What are WCF Data Services?
WCF Data Services are used to expose and consume data via web services accessed over HTTP.

How do you access WCF Data Services?
WCF Data Services uses the OData protocol for addressing and updating resources. So, these services can be accessed from any client that supports OData. OData enables requesting and writing data to resources using Atom(a set of standards for exchanging and updating data as XML) and JSON(a text-based data exchange format).

Tuesday, September 11, 2012

Overloading in WCF

Using the "Name" we can achieve operational overloading

interface IInterfaceName
{
  [OperationContract (Name = "aliasName1")]
  int MethodName (int param1, int param2);

  [OperationContract (Name = "aliasName2")]
  double MethodName (double param1, double param1);
}


Monday, September 10, 2012

WCF – Interview Questions with Answers


What is WCF?
Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types.

WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that support it. WCF is Microsoft’s unified programming model for building service-oriented applications with managed code. It extends the .NET Framework to enable developers to build secure and reliable transacted Web services that integrate across platforms and interoperate with existing investments.

Windows Communication Foundation combines and extends the capabilities of existing Microsoft distributed systems technologies, including Enterprise Services, System.Messaging, Microsoft .NET Remoting, ASMX, and WSE to deliver a unified development experience across multiple axes, including distance (cross-process, cross-machine, cross-subnet, cross-intranet, cross-Internet), topologies (farms, fire-walled, content-routed, dynamic), hosts (ASP.NET, EXE, Windows Presentation Foundation, Windows Forms, NT Service, COM+), protocols (TCP, HTTP, cross-process, custom), and security models (SAML, Kerberos, X509, username/password, custom).

What is service and client in perspective of data communication?
A service is a unit of functionality exposed to the world. The client of a service is merely the party consuming the service.

What is endpoint in WCF? or What is three major points in WCF?
Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service.

In WCF the relationship between Address, Contract and Binding is called Endpoint. The Endpoint is the fusion of Address, Contract and Binding.

1. Address : Specifies the location of the service which will be like http://Myserver/MyService.Clients will use this location to communicate with our service.

2. Contract : Specifies the interface between client and the server.It’s a simple interface with some attribute.

3. Binding : Specifies how the two paries will communicate in term of transport and encoding and protocols.

What is binding and how many types of bindings are there in WCF?

A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary).

A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.

WCF supports nine types of bindings.

1. Basic binding :
Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.

2. TCP binding :

Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.

3. Peer network binding :
Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.

4. IPC binding :
Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding.

5. Web Service (WS) binding :
Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.

6. Federated WS binding :

Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.

7. Duplex WS binding :
Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client.

8. MSMQ binding :

Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.

9. MSMQ integration binding :

Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.

What is contracts in WCF?
In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does.

WCF defines four types of contracts.
1. Service contracts : Describe which operations the client can perform on the service.

2. Data contracts : Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types.

3. Fault contracts : Define which errors are raised by the service, and how the service handles and propagates errors to its clients.

4. Message contracts : Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.

What is address in WCF and how many types of transport schemas are there in WCF?
Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address. This contains the location of the service and transport schemas.

WCF supports following transport schemas
1. HTTP
2. TCP
3. Peer network
4. IPC (Inter-Process Communication over named pipes)
5. MSMQ

The sample address for above transport schema may look like

http://localhost:81
http://localhost:81/MyService
net.tcp://localhost:82/MyService
net.pipe://localhost/MyPipeService
net.msmq://localhost/private/MyMsMqService
net.msmq://localhost/MyMsMqService

What is the difference WCF and Web services?
1. Web services can only be invoked by HTTP. While Service or a WCF component can be invoked by any protocol and any transport type.

2. Second web services are not flexible. But Services are flexible. If you make a new version of the service then you need to just expose a new end point. So services are agile and which is a very practical approach looking at the current business trends.

How can we host a service on two different protocols on a single server?
Let’s first understand what this question actually means. Let’s say we have made a service and we want to host this service using HTTP as well as TCP.

You must be wondering why to ever host services on two different types of protocol. When we host a service it’s consumed by multiple types of client and it’s very much possible that they have there own protocol of communication. A good service has the capability to downgrade or upgrade its protocol according the client who is consuming him.

Let’s do a small sample in which we will host the ServiceGetCost on TCP and HTTP protocol.

Once we are done the server side coding its time to see make a client by which we can switch between the protocols and see the results. Below is the code snippet of the client side for multi-protocol hosting

How does WCF work?
Follows the ‘software as a service’ model, where all units of functionality are defined as services.

A WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal (connection) for communication with either clients (applications) or other services.

Enables greater design flexibility and extensibility of distributed systems architectures.

A WCF application is represented as a collection of services with multiple entry points for communications.

What are the main components of WCF?
1.Service: The working logic or offering, implemented using any .Net Language©.

2.Host:
 The environment where the service is parked. E.g. exe, process, windows service

3.Endpoints: The way a service is exposed to outside world.

Explain transactions in WCF.
Transactions in WCF allow several components to concurrently participate in an operation. Transactions are a group of operations that are atomic, consistent, isolated and durable. WCF has features that allow distributed transactions. Application config file can be used for setting transaction timeouts.

What are different isolation levels provided in WCF?
The different isolation levels:

1. READ UNCOMMITTED: – An uncommitted transaction can be read. This transaction can be rolled back later.

2. READ COMMITTED :-
 Will not read data of a transaction that has not been committed yet

3. REPEATABLE READ: – Locks placed on all data and another transaction cannot read.

4. SERIALIZABLE:- Does not allow other transactions to insert or update data until the transaction is complete.

How do I serialize entities using WCF?
LINQ to SQL supports serialization as XML via WCF by generating WCF serialization attributes and special serialization specific logic during code-generation. You can turn on this feature in the designer by setting serialization mode to ‘Unidirectional’. Note this is not a general solution for serialization as unidirectional mode may be insufficient for many use cases.

What is End point ?
Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint.

The Endpoint is the fusion of Address, Contract and Binding.

Monday, June 20, 2011

WCF Transfer mode


Transfer mode

In our normal day today life, we need to transfer data from one location to other location. If data transfer is taking place through WCF service, message size will play major role in performance of the data transfer. Based on the size and other condition of the data transfer, WCF supports two modes for transferring messages

Buffer transfer

When the client and the service exchange messages, these messages are buffered on the receiving end and delivered only once the entire message has been received. This is true whether it is the client sending a message to the service or the service returning a message to the client. As a result, when the client calls the service, the service is invoked only after the client's message has been received in its entirety; likewise, the client is unblocked only once the returned message with the results of the invocation has been received in its entirety.

Stream transfer

When client and Service exchange message using Streaming transfer mode, receiver can start processing the message before it is completely delivered. Streamed transfers can improve the scalability of a service by eliminating the requirement for large memory buffers. If you want to transfer large message, streaming is the best method.

StreamRequest

In this mode of configuration, message send from client to service will be streamed

StreamRespone

In this mode of configuration, message send from service to client will be streamed.

Configuration

<system.serviceModel>     <services >       <service behaviorConfiguration="ServiceBehavior"  name="MyService">         <endpoint address="" binding="netTcpBinding"          bindingConfiguration="MyService.netTcpBinding" contract="IMyService">           <identity>             <dns value="localhost"/>           </identity>         </endpoint>         <endpoint address="mex" binding="mexHttpBinding"          contract="IMetadataExchange"/>       </service>     </services>     <behaviors>       <serviceBehaviors>         <behavior name="ServiceBehavior">           <serviceMetadata httpGetEnabled="true"/>           <serviceDebug includeExceptionDetailInFaults="true "/>         </behavior>       </serviceBehaviors>     </behaviors>     <bindings >       <netTcpBinding>         <binding name="MyService.netTcpBinding"          transferMode="Buffered" closeTimeout ="0:01:00" openTimeout="0:01:00"></binding>       </netTcpBinding>     </bindings>   </system.serviceModel> 

Differences between Buffered and Streamed Transfers

BufferedStreamed
Target can process the message once it is completely received.Target can start processing the data when it is partially received
Performance will be good when message size is smallPerformance will be good when message size is larger(more than 64K)
Native channel shape is IDuplexSessionChannelNative channels are IRequestChannel and IReplyChannel



Streaming

Client and Service exchange message using Streaming transfer mode, receiver can start processing the message before it is completely delivered. Streamed transfers can improve the scalability of a service by eliminating the requirement for large memory buffers. If you want to transfer large message, streaming is the best method.

Supported Bindings

  • BasicHttpBinding
  • NetTcpBinding
  • NetNamedPipeBinding

Restrictions

There are some restriction, when streaming is enabled in WCF
  • Digital signatures for the message body cannot be performed
  • Encryption depends on digital signatures to verify that the data has been reconstructed correctly.
  • Reliable sessions must buffer sent messages on the client for redelivery if a message gets lost in transfer and must hold messages on the service before handing them to the service implementation to preserve message order in case messages are received out-of-sequence.
  • Streaming is not available with the Message Queuing (MSMQ) transport
  • Streaming is also not available when using the Peer Channel transport

I/O Streams

WCF uses .Net stream class for Streaming the message. Stream in base class for streaming, all subclasses like FileStream,MemoryStream, NetworkStream are derived from it. Stream the data, you need to do is, to return or receive a Stream as an operation parameter.
[ServiceContract] public interface IMyService {     [OperationContract]     void SaveStreamData(Stream emp);      [OperationContract]     Stream GetStreamData();  } 
Note:
  1. Stream and it's subclass can be used for streaming, but it should be serializable
  2. Stream and MemoryStream are serializable and it will support streaming
  3. FileStream is non serializable, and it will not support streaming

Streaming and Binding

Only the TCP, IPC, and basic HTTP bindings support streaming. With all of these bindings streaming is disabled by default.TransferMode property should be set according to the desired streaming mode in the bindings.
public enum TransferMode {    Buffered, //Default    Streamed,    StreamedRequest,    StreamedResponse } public class BasicHttpBinding : Binding,... {    public TransferMode TransferMode    {get;set;}    //More members }
  • StreamedRequest - Send and accept requests in streaming mode, and accept and return responses in buffered mode
  • StreamResponse - Send and accept requests in buffered mode, and accept and return responses in streamed mode
  • Streamed - Send and receive requests and responses in streamed mode in both directions
  • Buffered -Send and receive requests and responses in Buffered mode in both directions

Streaming and Transport

The main aim of the Streaming transfer mode is to transfer large size data, but default message size is 64K. So you can increase the message size using maxReceivedMessageSize attribute in the binding element as shown below.
<system.serviceModel>     <bindings >       <netTcpBinding>         <binding name="MyService.netTcpBinding"          transferMode="Buffered" maxReceivedMessageSize="1024000">         </binding>       </netTcpBinding>     </bindings>   </system.serviceModel>

WCF Events


Events

Events allow the client or clients to be notified about something that has occurred on the service side. An event may result from a direct client call, or it may be the result of something the service monitors. The service firing the event is called the publisher, and the client receiving the event is called the subscriber.

  • Publisher will not care about order of invocation of subscriber. Subscriber can be executed in any manner.
  • Implementation of subscriber side should be short duration. Let us consider the scenario in which you what to publish large volume of event. Publisher will be blocked, when subscriber is queued on previous subscription of the event. These make publishers to put in wait state. It may lead Publisher event not to reach other subscriber.
  • Large number of subscribers to the event makes the accumulated processing time of each subscriber could exceed the publisher's timeout
  • Managing the list of subscribers and their preferences is a completely service-side implementation. It will not affect the client; publisher can even use .Net delegates to manage the list of subscribers.
  • Event should always one-Way operation and it should not return any value

Definition

    public interface IMyEvents     {         [OperationContract(IsOneWay = true)]         void Event1();     } 
Let us understand more on Event operation by creating sample service
Step 1 : Create ClassLibrary project in the Visual Studio 2008 and name it as WCFEventService as shown below.
Step 2:
Add reference System.ServiceModel to the project
Create the Event operation at the service and set IsOnwWay property to true. This operation should not return any value. Since service has to communicate to the client, we need to use CallbackContract for duplex communication. Here we are using one operation to subscribe the event and another for firing the event.
public interface IMyEvents     {         [OperationContract(IsOneWay = true)]         void Event1();     }     [ServiceContract(CallbackContract = typeof(IMyEvents))]    public interface IMyContract    {        [OperationContract]        void DoSomethingAndFireEvent();         [OperationContract]        void SubscribeEvent();     } 
Step 3: Implementation of the Service Contract is shown below.
In the Subscription operation, I am using Operationcontext to get the reference to the client instance and Subscription method is added as event handler to the service event. DoSomethingAndFireEvent operation will fire the event as shown.
MyPublisher.cs
   [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]    public  class MyPublisher : IMyContract     {         static Action m_Event1 = delegate { };          public void SubscribeEvent()         {             IMyEvents subscriber = OperationContext.Current.GetCallbackChannel();             m_Event1 += subscriber.Event1;         }          public static void FireEvent()         {             m_Event1();         }          public void DoSomethingAndFireEvent()         {             MyPublisher.FireEvent();                    }     } 
Step 4: Create the Console application using Visual Studio 2008 and name it as WcfEventServiceHost. This application will be used to self-host the service.
Step 5: Add System.ServiceModel and WcfEventService as reference to the project.
static void Main(string[] args)         {             Uri httpUrl = new Uri("http://localhost:8090/MyPublisher/");             ServiceHost host = new ServiceHost(typeof(WcfEventService.MyPublisher), httpUrl);             host.Open();             Console.WriteLine("Service is Hosted at {0}", DateTime.Now.ToString());             Console.WriteLine("Host is running...Press  key to stop the service.");             Console.ReadLine();             host.Close();         }   
Step 6: Use Duplex binding to support Callback operation.
Web.Config
<system.serviceModel>     <services >       <service behaviorConfiguration="ServiceBehavior"         name="WcfEventService.MyPublisher">         <endpoint address="http://localhost:8090/MyPublisher"          binding="wsDualHttpBinding" contract="WcfEventService.IMyContract">           <identity>             <dns value="localhost"/>           </identity>         </endpoint>         <endpoint address="mex" binding="mexHttpBinding"          contract="IMetadataExchange"/>       </service>     </services>     <behaviors>       <serviceBehaviors>         <behavior name="ServiceBehavior">           <serviceMetadata httpGetEnabled="true"/>           <serviceDebug includeExceptionDetailInFaults="true "/>         </behavior>       </serviceBehaviors>     </behaviors>   </system.serviceModel> 
Step7: Run the host application as shown below.
Step 8: Create the console application using visual studio and name it as WcfEventServiceClient as shown below. This application will act a client which is used to subscribe the event from service.
Step 9: Create the proxy class as shown below. Use DuplexClientBase to create the proxy, because it will support bidirectional communication. Create the contractor which will accept InstanceContext as parameter.
EventServiceClient.cs
 class EventServiceClient:DuplexClientBase,IMyContract      {         public EventServiceClient(InstanceContext eventCntx)             : base(eventCntx)         {                      }          public void  DoSomethingAndFireEvent()         {             base.Channel.DoSomethingAndFireEvent();         }          public void SubscribeEvent()         {             base.Channel.SubscribeEvent();         }            } 
Step 10: Implementation of IMyEvents at client side is shown below. This method will be called when service publish the event.
class MySubscriber : IMyEvents     {        public void Event1()         {             Console.WriteLine("Event is subscribed from the              service at {0}",DateTime.Now.ToString() );         }        }
Step 11: Main method of the client side you can find the creating Subscription instance and it passed to service usingInstanceContext
 static void Main(string[] args)         {             IMyEvents evnt = new MySubscriber();             InstanceContext evntCntx = new InstanceContext(evnt);              EventServiceClient proxy = new EventServiceClient(evntCntx);             Console.WriteLine("Client subscribe the event              from the service at {0}",DateTime.Now.ToString());             proxy.SubscribeEvent();             Console.WriteLine("Client call operation which will fire the event");             proxy.DoSomethingAndFireEvent();             Console.ReadLine();         } 
Step 12: Run the client application and you see the when event is fired from the service. Subscriber got notification.


Introdution to WCF 4.0


Introdution to WCF 4.0

This article explains about the new features introduced in WCF 4.0.
.Net framework comes with new features and improved areas of WCF. It was mainly focused on simplifying the developer experience, enabling more communication scenario and providing rich integration with WWF.
The following items specifies the new features of WCF 4.0
Simplified configuration
This new feature shows simplification of WCF configuration section by providing default endpoint, binding and behavior configuration. It is not mandatory to provide endpoint while hosting service. Service will automatically create new endpoint if it does find any endpoint while hosting service. These changes make it possible to host configuration-free services.
Discovery service
There are certain scenario in which endpoint address of the service will be keep on changing. In that kind of scenario, client who consume this service also need to change the endpoint address dynamically to identify the service. This can be achieved using WS-Discovery protocol.
Routing service
This new feature introduces routing service between client and actual business service. This intermediated service Act as broker or gateways to the actual business services and provides features for content based routing, protocol bridging and error handling
REST Service
There are few features helps while developing RESTful service.
  • Automatic help page that describes REST services to consumer
  • Support for declarative HTTP catching
Workflow service
  • Improves development experience
  • Entire service definition can be define in XAML
  • Hosting workflow service can be done from .xamlx file, without using .svc file
  • Introduce new “Context” bindings like BasicHttpContextBinding, WSHttpContextBinding, or NetTcpContextBinding
  • In .Net4.0, WorkflowServiceHost class for hosting workflow services was redesigned and it is available inSystem.ServiceModel.Activities assembly. In .Net3.5, WorkflowServiceHost class is available inSystem.WorkflowServices assembly
  • New messaging activities SendReply and ReceiveReply are added in .Net4.0
Conclusion:
This article explain new featues introduced in WCF 4.0

WCF Binding


Binding

Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements.
Binding has several characteristics, including the following:
  • Transport
    Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols.
  • Encoding (Optional)
    Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K).
  • Protocol(Optional)
    Defines information to be used in the binding such as Security, transaction or reliable messaging capability

    Bindings and Channel Stacks

    In WCF all the communication details are handled by channel, it is a stack of channel components that all messages pass through during runtime processing. The bottom-most component is the transport channel. This implements the given transport protocol and reads incoming messages off the wire. The transport channel uses a message encoder to read the incoming bytes into a logical Message object for further processing.

    Figure 1: Bindings and Channel Stacks (draw new diagram)
    After that, the message bubbles up through the rest of the channel stack, giving each protocol channel an opportunity to do its processing, until it eventually reaches the top and WCF dispatches the final message to your service implementation. Messages undergo significant transformation along the way.
    It is very difficult for the developer to work directly with channel stack architecture. Because you have to be very careful while ordering the channel stack components, and whether or not they are compatible with one other.
    So WCF provides easy way of achieving this using end point. In end point we will specify address, binding and contract. To know more about end point. Windows Communication Foundation follows the instructions outlined by the binding description to create each channel stack. The binding binds your service implementation to the wire through the channel stack in the middle.

    Types of Binding

    Let us see more detailed on predefined binding

    BasicHttpBinding

    • It is suitable for communicating with ASP.NET Web services (ASMX)-based services that comfort with WS-Basic Profile conformant Web services.
    • This binding uses HTTP as the transport and text/XML as the default message encoding.
    • Security is disabled by default
    • This binding does not support WS-* functionalities like WS- Addressing, WS-Security, WS-ReliableMessaging
    • It is fairly weak on interoperability.

    WSHttpBinding

    • Defines a secure, reliable, interoperable binding suitable for non-duplex service contracts.
    • It offers lot more functionality in the area of interoperability.
    • It supports WS-* functionality and distributed transactions with reliable and secure sessions using SOAP security.
    • It uses HTTP and HTTPS transport for communication.
    • Reliable sessions are disabled by default.

    WSDualHttpBinding

    This binding is same as that of WSHttpBinding, except it supports duplex service. Duplex service is a service which uses duplex message pattern, which allows service to communicate with client via callback.
    In WSDualHttpBinding reliable sessions are enabled by default. It also supports communication via SOAP intermediaries.

    WSFederationHttpBinding

    This binding support federated security. It helps implementing federation which is the ability to flow and share identities across multiple enterprises or trust domains for authentication and authorization. It supports WS-Federation protocol.

    NetTcpBinding

    This binding provides secure and reliable binding environment for .Net to .Net cross machine communication. By default it creates communication stack using WS-ReliableMessaging protocol for reliability, TCP for message delivery and windows security for message and authentication at run time. It uses TCP protocol and provides support for security, transaction and reliability.

    NetNamedPipeBinding

    This binding provides secure and reliable binding environment for on-machine cross process communication. It uses NamedPipe protocol and provides full support for SOAP security, transaction and reliability. By default it creates communication stack with WS-ReliableMessaging for reliability, transport security for transfer security, named pipes for message delivery and binary encoding.

    NetMsmqBinding

    • This binding provides secure and reliable queued communication for cross-machine environment.
    • Queuing is provided by using MSMQ as transport.
    • It enables for disconnected operations, failure isolation and load leveling

    NetPeerTcpBinding

    • This binding provides secure binding for peer-to-peer environment and network applications.
    • It uses TCP protocol for communication
    • It provides full support for SOAP security, transaction and reliability.


WCF Hosting


WCF Hosting

In this part of the tutorial we are going to see the four different way of hosting the WCF service. WCF service cannot exist on its own; it has to be hosted in windows process called as host process. Single host process can host multiple servers and same service type can be hosted in multiple host process. As we discussed there are mainly four different way of hosting the WCF service.
Multiple hosting and protocols supported by WCF.Microsoft has introduced the WCF concept in order to make distributed application development and deployment simple.
Hosting EnvironmentSupported protocol
Windows console and form applicationHTTP,net.tcp,net.pipe,net.msmq
Windows service application (formerly known as NT services)HTTP,net.tcp,net.pipe,net.msmq
Web server IIS6http, wshttp
Web server IIS7 - Windows Process Activation Service (WAS)HTTP,net.tcp,net.pipe,net.msmq
A summary of hosting options and supported features.
FeatureSelf-HostingIIS HostingWAS Hosting
Executable Process/ App DomainYesYesYes
ConfigurationApp.configWeb.configWeb.config
ActivationManual at startupMessage-basedMessage-based
Idle-Time ManagementNoYesYes
Health MonitoringNoYesYes
Process RecyclingNoYesYes
Management ToolsNoYesYes


IIS 5/6 Hosting

The main advantage of hosting service in IIS is that, it will automatically launch the host process when it gets the first client request. It uses the features of IIS such as process recycling, idle shutdown, process health monitoring and message based activation. The main disadvantage of using IIS is that, it will support only HTTP protocol.
Let as do some hands on, to create service and host in IIS
Step 1:Start the Visual Studio 2008 and click File->New->Web Site. Select the 'WCF Service' and Location as http. This will directly host the service in IIS and click OK.
Step 2: I have created sample HelloWorld service, which will accept name as input and return with 'Hello' and name. Interface and implementation of the Service is shown below.
IMyService.cs
[ServiceContract] public interface IMyService {     [OperationContract]     string HelloWorld(string name);      }
MyService.cs
public class MyService : IMyService {      #region IMyService Members      public string HelloWorld(string name)     {         return "Hello " + name;     }      #endregion } 
Step 3: Service file (.svc) contains name of the service and code behind file name. This file is used to know about the service.
MyService.svc
<%@ ServiceHost Language="C#" Debug="true"  Service="MyService" CodeBehind="~/App_Code/MyService.cs" %>
Step 4: Server side configurations are mentioned in the config file. Here I have mention only one end point which is configured to 'wsHttpBinding', we can also have multiple end point with differnet binding. Since we are going to hosted in IIS. We have to use only http binding. We will come to know more on endpoints and its configuration in later tutorial. Web.Config
<system.serviceModel>   <services>    <service behaviorConfiguration="ServiceBehavior" name="MyService">  <endpoint address="http://localhost/IISHostedService/MyService.svc"   binding="wsHttpBinding" contract="IMyService">  <identity>  <dns value="localhost"/>  </identity>  </endpoint>  <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>    </service>  </services>  <behaviors>   <serviceBehaviors>     <behavior name="ServiceBehavior">  <!-- To avoid disclosing metadata information,   set the value below to false and remove the   metadata endpoint above before deployment -->       <serviceMetadata httpGetEnabled="true"/>  <!-- To receive exception details in faults for   debugging purposes, set the value below to true.    Set to false before deployment to avoid disclosing exception information -->  <serviceDebug includeExceptionDetailInFaults="false"/>  </behavior>    </serviceBehaviors>   </behaviors> </system.serviceModel> 
Note:
You need to mention the service file name, along with the Address mention in the config file. IIS Screen shot
This screen will appear when we run the application.
Step 5: Now we successfully hosted the service in IIS. Next we have to consume this service in client application. Before creating the client application, we need to create the proxy for the service. This proxy is used by the client application, to interact with service. To create the proxy, run the Visual Studio 2008 command prompt. Using service utility we can create the proxy class and its configuration information.
svcutil  http://localhost/IISHostedService/MyService.svc
After executing this command we will find two file generated in the default location.
  • MyService.cs - Proxy class for the WCF service
  • output.config - Configuration information about the service.
Step 6: Now we will start creating the Console application using Visual Studio 2008(Client application).
Step 7: Add the reference 'System.ServiceModel'; this is the core dll for WCF.
Step 8: Create the object for the proxy class and call the HelloWorld method.
static void Main(string[] args)         {             //Creating Proxy for the MyService               MyServiceClient client = new MyServiceClient();              Console.WriteLine("Client calling the service...");              Console.WriteLine(client.HelloWorld("Ram"));              Console.Read();          }
Step 9: If we run the application we will find the output as shown below.

I hope you have enjoyed the Service hosted in IIS. Now let start the look on the self hosted service.

Self Hosting

In web service, we can host the service only in IIS, but WCF provides the user to host the service in any application (e.g. console application, Windows form etc.). Very interestingly developer is responsible for providing and managing the life cycle of the host process. Service can also be in-pro i.e. client and service in the same process. Now let's us create the WCF service which is hosted in Console application. We will also look in to creating proxy using 'ClientBase' abstract class.
Note: Host process must be running before the client calls the service, which typically means you have to prelaunch it.
Step 1: First let's start create the Service contract and it implementation. Create a console application and name it as MyCalculatorService. This is simple service which return addition of two numbers.
Step 2: Add the System.ServiceModel reference to the project.
Step 3: Create an ISimpleCalculator interface, Add ServiceContract and OperationContract attribute to the class and function as shown below. You will know more information about these contracts in later session. These contracts will expose method to outside world for using this service.
IMyCalculatorService.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel;  namespace MyCalculatorService {     [ServiceContract()]     public interface ISimpleCalculator     {         [OperationContract()]         int Add(int num1, int num2);     }  }
Step 4: MyCalculatorService is the implementation class for IMyCalculatorService interface as shown below.
MyCalculatorService.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text;  namespace MyCalculatorService {     class SimpleCalculator : ISimpleCalculator     {         public int Add(int num1, int num2)         {             return num1 + num2;         }      } }
Step 5: Now we are ready with service. Let's go for implementing the hosting process. Create a new console application and name it as 'MyCalculatorServiceHost'
Step 6: ServiceHost is the core class use to host the WCF service. It will accept implemented contract class and base address as contractor parameter. You can register multiple base addresses separated by commas, but address should not use same transport schema.
Uri httpUrl  = new Uri("http://localhost:8090/MyService/SimpleCalculator");  Uri tcpUrl  = new Uri("net.tcp://localhost:8090/MyService/SimpleCalculator");  ServiceHost host  = new ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl, tcpUrl);
Multiple end points can be added to the Service using AddServiceEndpoint() method. Host.Open() will run the service, so that it can be used by any client.
Step 7: Below code show the implementation of the host process.
  using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using System.ServiceModel.Description;  namespace MyCalculatorServiceHost {     class Program     {         static void Main(string[] args)         {             //Create a URI to serve as the base address             Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator");             //Create ServiceHost             ServiceHost host              = new ServiceHost(typeof(MyCalculatorService.SimpleCalculator), httpUrl);             //Add a service endpoint             host.AddServiceEndpoint(typeof(MyCalculatorService.ISimpleCalculator)             , new WSHttpBinding(), "");             //Enable metadata exchange             ServiceMetadataBehavior smb = new ServiceMetadataBehavior();             smb.HttpGetEnabled = true;             host.Description.Behaviors.Add(smb);             //Start the Service             host.Open();              Console.WriteLine("Service is host at " + DateTime.Now.ToString());             Console.WriteLine("Host is running... Press  key to stop");             Console.ReadLine();          }     } } 
Step 8: Service is hosted, now we need to implement the proxy class for the client. There are different ways of creating the proxy
  • Using SvcUtil.exe, we can create the proxy class and configuration file with end points.
  • Adding Service reference to the client application.
  • Implementing ClientBase class
Of these three methods, Implementing ClientBase is the best practice. If you are using rest two method, we need to create proxy class every time when we make changes in Service implementation. But this is not the case for ClientBase. It will create the proxy only at runtime and so it will take care of everything.
MyCalculatorServiceProxy.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using MyCalculatorService; namespace MyCalculatorServiceProxy {     public class MyCalculatorServiceProxy :          //WCF create proxy for ISimpleCalculator using ClientBase         ClientBase,         ISimpleCalculator     {         public int Add(int num1, int num2)         {             //Call base to do funtion             return base.Channel.Add(num1, num2);         }     } }
Step 9: In the client side, we can create the instance for the proxy class and call the method as shown below. Add proxy assembly as reference to the project.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel;  namespace MyCalculatorServiceClient {     class Program     {         static void Main(string[] args)         {             MyCalculatorServiceProxy.MyCalculatorServiceProxy proxy ;             proxy= new MyCalculatorServiceProxy.MyCalculatorServiceProxy();             Console.WriteLine("Client is running at " + DateTime.Now.ToString());             Console.WriteLine("Sum of two numbers... 5+5 ="+proxy.Add(5,5));             Console.ReadLine();         }     } }
Step 10 : End point (same as service) information should be added to the configuration file of the client application.
<?xml version="1.0" encoding="utf-8" ?> <configuration>   <system.serviceModel>     <client>       <endpoint address ="http://localhost:8090/MyService/SimpleCalculator"                  binding ="wsHttpBinding"                 contract ="MyCalculatorService.ISimpleCalculator">                </endpoint>     </client>   </system.serviceModel> </configuration> 
Step 11: Before running the client application, you need to run the service. Output of the client application is shown below.

This self host shows advantage such as in-Pro hosting, programmatic access and it can be used when there need singleton service. I hope you have enjoyed the Self hosting session, now let go for hosting using Windows Activation service.

Windows Activation Service

Windows Activation service is a system service available with Windows vista and windows server 2008. It is available with IIS 7.0 and it is more powerful compared to IIS 6.0 because it supports Http, TCP and named pipes were IIS 6.0 supports only Http. It can be installed and configured separately.
Hosting WCF in Activation service takes many advantages such as process recycling, isolation, idle time management and common configuration system. WAS hosted service can be created using following steps
  1. Enable WCF for non-http protocols
  2. Create WAS hosted service
  3. Enable different binding to the hosted service

Enable WCF for non-http protocols

Before Start creating the service we need to configure the system to support WAS. Following are the step to configure WAS.
  1. Click Start -> Control Panel -> programs and Features and click 'Turn Windows Components On or Off' in left pane.
  2. Expand 'Microsoft .Net Framework 3.0' and enable "Windows Communication Foundation HTTP Activation" and "Windows Communication Foundation Non- HTTP Activation".
  3. Next we need to add Binding to the Default Web site. As an example, we will 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.
  4. Execute the following command
  5. C:\Windows\system32\inetsrv> appcmd.exe set site "Default Web Site" -+bindings.[protocol='net.tcp',
  6. bindingInformation='808:*']

  • That command adds the net.tcp site binding to the default web site by modifying the applicationHost.config file located in the "C:\Windows\system32\inetsrv\config" directory. Similarly we can add different protocols to the Default Web site.
  • Create WAS hosted service

    Step 1: Next we are going to create the service, Open the Visual Studio 2008 and click New->WebSite and select WCF Service from the template and Location as HTTP as shown below.
    Step 2: Create the Contract by creating interface IMathService and add ServiceContract attribute to the interface and add OperationContract attribute to the method declaration.
    IMathService.cs
    using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text;   [ServiceContract] public interface IMathService {      [OperationContract]     int Add(int num1, int num2);      [OperationContract]     int Subtract(int num1, int num2);  }
    Step 3: Implementation of the IMathService interface is shown below.
    MathService.cs
    using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text;  public class MathService : IMathService {     public int Add(int num1, int num2)     {         return num1 + num2;     }      public int Subtract(int num1, int num2)     {         return num1 - num2;     } }
    Step 4: Service file is shown below.
    MathService.svc
    <%@ ServiceHost Language="C#" Debug="true" Service="MathService"  CodeBehind="~/App_Code/MathService.cs" %>
    Step 5: In web.Config file, create end point with 'netTcpBinding' binding and service metadata will be published using Metadata Exchange point. So create the Metada Exchange end point with address as 'mex' and binding as 'mexTcpBinding'. Without publishing the service Metadata we cannot create the proxy using net.tcp address (e.g svcutil.exe net.tcp://localhost/WASHostedService/MathService.svc )
    Web.Config
    <system.serviceModel> <services>  <service name="MathService" behaviorConfiguration="ServiceBehavior">  <!-- Service Endpoints -->  <endpoint binding="netTcpBinding"   contract="IMathService" >  </endpoint>   <endpoint address="mex"    binding="mexTcpBinding" contract="IMetadataExchange"/>   </service> </services> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <!-- To avoid disclosing metadata information, set the value below  to false and remove the metadata endpoint above before deployment -->  <serviceMetadata httpGetEnabled="true"/>  <!-- To receive exception details in   faults for debugging purposes, set the value below to true.     Set to false before deployment to avoid disclosing     exception information -->  <serviceDebug includeExceptionDetailInFaults="false"/>  </behavior> </serviceBehaviors></behaviors> </system.serviceModel>

    Enable different binding to the hosted service

    1. Go to the Start menu -> Programs ->Accessories. Right click on the "Command Prompt" item, and select "Run as administrator" from the context menu.
    2. Execute the following command C:\Windows\system32\inetsrv>appcmd set app "Default Web Site/WASHostedServcie" /enabledProtocols:http,net.tcp
    Output will be shown below.
    Step 6: Now the service is ready to use. Next we can create the proxy class using service uttility and add the proxy class to the client application. Creat the proxy class using Visual Studio Command prompt and execute the command
    svcutil.exe net.tcp://localhost/WASHostedService/MathService.svc
    Proxy and configuration file are generated in the corresponding location.
    Step 6: Create the client application as shown below and add the reference 'System.ServiceModel', this is the core dll for WCF.
    Step 8: Add the proxy class and configuration file to the client application. Create the object for the MathServiceClient and call the method.
    Program.cs
     class Program     {         static void Main(string[] args)         {             MathServiceClient client = new MathServiceClient();             Console.WriteLine("Sum of two number 5,6");             Console.WriteLine(client.Add(5,6));             Console.ReadLine();          }     }
    The output will be shown as below.

    So this tutorial clearly explains about the hosting the WCF in Windows Activation Service. So next we can see how to host the service using Windows Service

    Windows Service Hosting

    In this tutorial we are going to see the hosting WCF service in Windows service. We will use same set of code used for hosting the WCF service in Console application to this. This is same as hosting the service in IIS without message activated. There is some advantage of hosting service in Windows service.
    • The service will be hosted, when system starts
    • Process life time of the service can be controlled by Service Control Manager for windows service
    • All versions of Windows will support hosting WCF service.
    Step 1: Now let start create the WCF service, Open the Visual Studio 2008 and click New->Project and select Class Library from the template.
    Step 2: Add reference System.ServiceModel to the project. This is the core assembly used for creating the WCF service.
    Step 3: Next we can create the ISimpleCalulator interface as shown below. Add the Service and Operation Contract attribute as shown below.
    ISimpleCalculator.cs
    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel;  namespace WindowsServiceHostedContract {     [ServiceContract]     public interface ISimpleCalculator     {         [OperationContract]         int Add(int num1, int num2);          [OperationContract]         int Subtract(int num1, int num2);          [OperationContract]         int Multiply(int num1,int num2);          [OperationContract]         double Divide(int num1, int num2);      } }
    Step 4: Implement the ISimpleCalculator interface as shown below.
    SimpleCalulator.cs
    using System; using System.Collections.Generic; using System.Linq; using System.Text;  namespace WindowsServiceHostedService {     class SimpleCalculator         : ISimpleCalculator     {           public int Add(int num1, int num2)         {             return num1+num2;         }          public int Subtract(int num1, int num2)         {              return num1-num2;         }          public int Multiply(int num1, int num2)         {              return num1*num2;         }          public double Divide(int num1, int num2)         {             if (num2 != 0)                 return num1 / num2;             else                 return 0;         }       } }
    Step 5: Build the Project and get the dll. Now we are ready with WCF service, now we are going to see how to host the WCF Service in Windows service. Note: In this project, I have mention that we are creating both Contract and Service(implementation) are in same project. It is always good practice if you have both in different project.
    Step 6: Open Visual Studio 2008 and Click New->Project and select Windows Service.
    Step 7: Add the 'WindowsServiceHostedService.dll' as reference to the project. This assembly will going to act as service.
    Step 8: OnStart method of the service, we can write the hosting code for WCF. We have to make sure that we are using only one service host object. On stop method you need to close the Service Host. Following code show how to host WCF service in Windows service.
    WCFHostedWindowsService.cs
    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.ServiceModel; using System.ServiceModel.Description;  namespace WCFHostedWindowsService {     partial class WCFHostedWindowsService : ServiceBase     {         ServiceHost m_Host;                  public WCFHostedWindowsService()         {             InitializeComponent();         }          protected override void OnStart(string[] args)         {             if (m_Host != null)             {                 m_Host.Close();             }             //Create a URI to serve as the base address             Uri httpUrl = new Uri("http://localhost:8090/MyService/SimpleCalculator");             //Create ServiceHost             m_Host = new ServiceHost             (typeof(WindowsServiceHostedService.SimpleCalculator), httpUrl);             //Add a service endpoint             m_Host.AddServiceEndpoint             (typeof(WindowsServiceHostedService.ISimpleCalculator), new WSHttpBinding(), "");             //Enable metadata exchange             ServiceMetadataBehavior smb = new ServiceMetadataBehavior();             smb.HttpGetEnabled = true;             m_Host.Description.Behaviors.Add(smb);             //Start the Service             m_Host.Open();           }          protected override void OnStop()         {             if (m_Host != null)             {                 m_Host.Close();                 m_Host = null;             }         }         static void Main()         {             ServiceBase[] ServicesToRun;             ServicesToRun = new ServiceBase[]     {      new WCFHostedWindowsService()     };             ServiceBase.Run(ServicesToRun);          }     } }
    Step 9: In order to install the service we need to have the Installer class for the Windows service. So add new Installer class to the project, which is inherited from the Installer class. Please find the below code for mentioning the Service name, StartUp type etc of the service.
    ServiceInstaller.cs
    using System; using System.Collections.Generic; using System.Text; using System.ServiceProcess; using System.Configuration.Install; using System.ComponentModel; using System.Configuration;   namespace WCFHostedWindowsService {     [RunInstaller(true)]     public class WinServiceInstaller : Installer     {         private ServiceProcessInstaller process;         private ServiceInstaller service;          public WinServiceInstaller()         {             process = new ServiceProcessInstaller();             process.Account = ServiceAccount.NetworkService;             service = new ServiceInstaller();             service.ServiceName = "WCFHostedWindowsService";             service.DisplayName = "WCFHostedWindowsService";             service.Description = "WCF Service Hosted";             service.StartType = ServiceStartMode.Automatic;             Installers.Add(process);             Installers.Add(service);         }     } }
    Step 10: Build the project, we will get the WCFHostedWindowsService.exe. Next we need to install the service using Visual Studio Command Prompt. So open the command prompt by clicking Start->All Programs-> Microsoft Visual Studio 2008-> Visual Studio Tools-> Visual Studio Command Prompt Using installutil utility application, you can install the service as shown below.
    Step 11: Now service is Hosted sucessfully and we can create the proxy class for the service and start using in the client applcaiton.