WCF

Introduction

Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. It is designed using service-oriented architecture principles to support distributed computing where services have remote consumers. Clients can consume multiple services; services can be consumed by multiple clients. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an An endpoint can be a client of a service that requests data from a service endpoint. The messages can be as simple as a single character or word sent as XML, or as complex as a stream of binary data. A few sample scenarios include: A secure service to process business transactions. A service that supplies current data to others, such as a traffic report or other monitoring service. A chat service that allows two people to communicate or exchange data in real time. A dashboard application that polls one or more services for data and presents it in a logical presentation. Exposing a workflow implemented using Windows Workflow Foundation as a WCF service. A Silverlight application to poll a service for the latest data feeds.

Features of WCF

  • Service Orientation
  • Interoperability
  • Service Metadata
  • Data Contracts
  • Security
  • Multiple Transports and Encodings
  • Reliable and Queued Messages
  • Durable Messages
  • Transactions
  • AJAX and REST Support
  • Extensibility
Click here for more info. Click here!

What is the difference between WCF and ASMX Web services?

WCF
Web Services
ASMX web service is designed to send and receive messages using SOAP over HTTP onlyWCF service can exchange messages using any format (SOAP is default) over any transport protocol (HTTP, TCP/IP, MSMQ, Named Pipes etc).
Uses XML Serialization Data Contract Serialization
Hosted IIS Only Hosted in IIS, WAS (Windows Active service), Self-Host, and Console/Windows apps
Limited securityConsistent security models (WS-*) WS-Security, WS-Addressing, WS-Reliable Messaging, WS-Interoperability, WS-Transaction)

For more info. Click here!

What are the Endpoints in WCF? or Explain ABCs of endpoint?

Once service is ready, clients need information about service to communicate with it. This is where service endpoints come into picture.
A service endpoint has three parts or also called ABCs of an endpoint i.e. Address, Binding and Contract. Address: It defines “WHERE”. URL of the service location Binding: It defines “HOW”. How a client can communicate with the endpoint? Example HTTP, HTTPS, TCP or MSMQ etc.? Contract: It defines “WHAT”. What is the business logic behind the service?
One more important part is Behaviors - A set of behaviors that specify local implementation details of the endpoint.

What is a WCF Binding? How many different types of bindings available in WCF?

Bindings in WCF actually defines that how to communicate with the service. Binding specifies that what communication protocol as well as encoding method will be used. Optionally, binding can specify other important factors like transactions, reliable sessions and security. Another WCF Tutorial gives more detailed understanding of Binding concept in WCF. There are different built-in bindings available in WCF, each designed to fulfill some specific need.

              basicHttpBinding	Basic Web service communication. No security by default
              wsHttpBinding	Web services with WS-* support. Supports transactions
              webHttpBinding Defines a binding element that is used to configure endpoints for WCF Web services that respond to HTTP requests instead of SOAP messages.
              wsDualHttpBinding	Web services with duplex contract and transaction support
              wsFederationHttpBinding	Web services with federated security. Supports transactions
              msmqIntegrationBinding	Communication directly with MSMQ applications. Supports transactions
              netMsmqBinding	Communication between WCF applications by using queuing. Supports transactions
              netNamedPipeBinding	Communication between WCF applications on same computer. Supports duplex contracts and transactions
              netPeerTcpBinding	Communication between computers across peer-to-peer services. Supports duplex contracts
              netTcpBinding	Communication between WCF applications across computers. Supports duplex contracts and transactions
              udpBinding A configuration element used to configure the UdpBinding binding (User Datagram Protocol). It's connectionless protocol runs on top of IP network.
              mexHttpBinding Specifies the settings for a binding used for the WS-MetadataExchange (WS-MEX) message exchange over HTTP
              customBinding Provides full control over the messaging stack for the user.
              

How to configure the service for two different endpoints?

What are Contracts in WCF?

A Contract is basically an agreement between the two parties i.e. Service and Client. In WCF, Contracts can be categorized as behavioral or structural. Behavioral Contracts define that what operations client can perform on a service. ServiceContract => attribute is used to mark a type as Service contract that contains operations. OperationContract => attributes is used to mark the operations that will be exposed. Fault Contract => defines what errors are raised by the service being exposed. Structural Contracts DataContract => attribute define types that will be moved between the parties. MessageContract => attribute define the structure of SOAP message.

What is Data Contracts?

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. WCF uses a serialization engine called the Data Contract Serializer by default to serialize and deserialize data (convert it to and from XML). All .NET Framework primitive types, such as integers and strings, as well as certain types treated as primitives, such as DateTime and XmlElement, can be serialized with no other preparation and are considered as having default data contracts. Many .NET Framework types also have existing data contracts New complex types that you create must have a data contract defined for them to be serializable. By default, the DataContractSerializer infers the data contract and serializes all publicly visible types. All public read/write properties and fields of the type are serialized.

                      [DataContract]
                      public class PurchaseOrder
                      {
                      private int poId_value;

                      // Apply the DataMemberAttribute to the property.
                      [DataMember]
                      public int PurchaseOrderId
                      {

                      get { return poId_value; }
                      set { poId_value = value; }
                      }
                      }
                      

What is difference between Data contracts and Message contracts?

Data Contracts: WCF data contracts provide a mapping function between .NET CLR types that are defined in code and XML Schemas Definitions defined by the W3C organization (www.w3c.org/) that are used for communication outside the service. It is an agreement between parties service and a client that describes what type of data will be exchanged between them It controls the contents that is message body or payload data Enable interoperability through the XML Schema Definition (XSD) standard Message Contracts: Message contracts describe the structure of SOAP messages sent to and from a service and enable you to inspect and control most of the details in the SOAP header and body. Enable you to interoperate with any system that communicates through SOAP Gives you complete control over the SOAP message sent to and from a service by providing access to the SOAP headers and bodies directly. This allows use of simple or complex types to define the exact content of the SOAP parts.

Why is it useful to pass information in SOAP headers with Message contract?

Passing information in SOAP headers is useful if you want to communicate information from the operation signature. For example 1.Session or correlation information can be passed in headers, rather than adding additional parameters to operations or adding this information as fields in the data itself. 2. It is security, where you may want to implement a custom security protocol (bypassing WS-Security) and pass credentials or tokens in custom SOAP headers.3. It is signing and encrypting SOAP headers, where you may want to sign and/or encrypt some or all header information. All these cases can be handled with message contracts. The downside with this technique is that the client and service must manually add and retrieve the information from the SOAP header, rather than having the serialization classes associated with data and operation contracts do it for you.

Can't mix datacontracts and messagecontracts.

Because message-based programming and parameter-based programming cannot be mixed, so you cannot specify a DataContract as an input argument to an operation and have it returns a MessageContract, or specifies a MessageContract as the input argument to an operation and has it return a DataContract. You can mix typed and untyped messages, but not messageContracts and DataContracts. Mixing message and data contracts will cause a runtime error when you generate WSDL from the service. >

What is Message Exchange Patterns supported by WCF?

  1. Request/Response (Default)
  2. One Way
  3. Duplex
Request/Response It’s the default pattern. In this pattern, a response message will always be generated to consumer when the operation is called, even with the void return type. In this scenario, response will have empty SOAP body. One Way In some cases, we are interested to send a message to service in order to execute certain business functionality but not interested in receiving anything back. OneWay MEP will work in such scenarios. If we want queued message delivery, OneWay is the only available option. Duplex The Duplex MEP is basically a two-way message channel. In some cases, we want to send a message to service to initiate some longer-running processing and require a notification back from service in order to confirm that the requested process has been completed.

What is mexHttpBinding in WCF?

In order to generate proxy, we need service metadata and mexHttpBinding returns service metadata. If we look into our configuration file, service will have an endpoint with mexHttpBinding as follows: and service metadata behavior will be configured as follows: Before deployment of application to production machine, it should be disabled. In order to support other protocols, related bindings are mexHttpBinding, mexHttpsBinding, mexTcpBinding.

What are the different WCF Instance Activation Methods available?

WCF supports three different types of Instance Activation methods:

  1. Per Call
  2. Per Session
  3. Singleton

What are the different ways to handle concurrency in WCF?

There are three different ways to handle concurrency in WCF that are:

  1. Single
  2. Multiple
  3. Reentrant
Single: means at a given time, only a single request can be processed by WCF service instance. Other requests will be waiting until the first one is fully served. Multiple: means multiple requests can be served by multiple threads of a single WCF service instance. Reentrant: means a single WCF service instance can process one request at a given time but the thread can exit the service to call another service. We can apply these concurrency settings by putting ConcurrencyMode property in ServiceBehavior as follows: [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple] public class MyService : IMyService { }

What is WCF throttling?

WCF throttling enables us to regulate the maximum number of WCF instances, concurrent calls and concurrent sessions. Basic purpose is to control our WCF service performance by using Service throttling behavior. In configuration file we can set this behavior as follows:

                                                      
                                                        
                                                          
                                                      
                                                      
Above given values are the default ones, but we can update it after looking into the requirements of our application.

What is a fault contract?

                                                          Normally, by default, when some exception occurs at a WCF service level, it will not expose as it is to client. Reason is that WCF exception is a CLR exception and it
                                                          doesn’t make sense to expose it outside CLR because it contains internal details of service code like stack trace. So, WCF handles and returns error details to client
                                                          using Fault Contract. “So, fault contract is a contract that contains the details of possible exception(s) that might occur in a service code.”

                                                          [ServiceContract]
                                                          public interface IService1
                                                          {
                                                          [OperationContract]
                                                          [FaultContract(typeof(MyFaultDetails))]
                                                          int MyOperation1();
                                                          }
                                                          [DataContract]
                                                          public class MyFaultDetails
                                                          {
                                                          [DataMember]
                                                          public string ErrorDetails { get; set; }
                                                          }
                                                          In implementing service…..

                                                          public int MyOperation1()
                                                          {
                                                          Try{               //Do something……       }catch()
                                                          {
                                                          MyFaultDetails ex = new MyFaultDetails();
                                                          ex.ErrorDetails = “Specific error details here.“;
                                                          throw new FaultException(ex,“Reason: Testing…..“);
                                                          }
                                                          }
                                                          A user has a service with a one-way operation that includes a fault contract, and he gets an exception when he tries to host the service. Why?

This is true, because, to return faults, the service requires some form of a two-way communication channel, which is not there with one-way operations.

What are the core security concepts supported by WCF?

There are four core security Features Confidentiality: It’s a confirmation about the recipient. Only the valid recipient can read the message when it passed between service and client. Integrity: is to ensure that message received is not being tempered or changed during exchange. Authentication: is a way for the parties (sender and receiver) to identify each other. Authorization: ensures that what actions an authenticated user can perform?

Difference between Message Level security and Transport Level security?

Security can be configured at different levels in Windows Communication Foundation. Transport Level Security secures the transport (the pipe) over which the message passes through from client to a service. Message Level Security secures the message that is being transported from one end to another.