Questions-And-Answers/ Question 1: What Is WCF?: Answer
Questions-And-Answers/ Question 1: What Is WCF?: Answer
Questions-And-Answers/ Question 1: What Is WCF?: Answer
com/uploadfile/8ef97c/wcf-interviewquestions-and-answers/
Question 1: What is WCF?
Answer:
WCF is a platform for building distributed businesses and deploying services among various
endpoints in Windows. WCF was initially called Indigo and we can build service-oriented
applications and provide interoperability.
WCF or Windows Communication Foundation is a programming model to create service
oriented applications. It is used to create and deploy the service that is accessible to lots of
different clients. It provides an environment where you can create a service which can be
accessible to Windows clients as well as Linux clients or any others. It provides more
features compared to web services.
WCF is a Microsoft technology to create service oriented application. Before the WCF, the
Web Service was used to create services but that type of service is only accessible to
Windows client hosted on HTTP protocol. But WCF services are accessible with different
protocols like http, tcp, msmq, etc. A few sample scenarios include:
Introduction to WCF
1
Unification
o COM+ Services
o Web Services
o .NET Remoting
o Microsoft Message Queuing
Interoperability
Service Orientation
WCF Architecture
There are four major layers that provide developers with a new service-oriented
programming model. The WCF architecture consists of the following layers.
Why WCF
1. A web service to exchange messages in XML format using HTTP protocol for
interoperability.
2. A remoting service to exchange messages in binary format using TCP protocol for
performance.
A service that supplies current data to others, such as a traffic report or other
monitoring service.
A dashboard application that polls one or more services for data and presents
it in a logical presentation.
Service Orientation
Interoperability
Service Metadata
Data Contracts
Security
Durable Messages
Transactions
Extensibility
Advantages of WCF
1. Service Oriented
2. Location Independent
3. Language Independent
4. Platform Independent
5
WCF can be configured to work independently of SOAP and use RSS instead.
Web Service
WCF
ng
Model
WCF
XML
Transmission Optimization
Can be accessed through HTTP, TCP, Can be accessed through HTTP, TCP,
Custom
Security
A Service
A Service Repository
A Service Bus
Application Front End: The application front end is decoupled from the services. Each
service has a contract that defines what it will do and one or more interfaces to implement
the contract.
A Service: It has the methods with the defined contracts and the implementation of the
business logic to connect the DB or other service.
A Service Repository: The service repository provides a home for the services and the
service bus provides an industry-standard mechanism for connecting to and interacting with
the services.
Are web-services SOA?
SOA is thinking, it's an architectural concept and web service is one of the technical
approach to complete it. Web services are the preferred standards to achieve SOA.
SOA services are located in a directory. UDDI describes where we can get the web
service. This nothing but implementation of SOA registry.
[ServiceContract(Name="MyService", Namespace="http://tempuri.org")]
2.
3.
4.
[OperationContract]
5.
6.
Service Contract:
A service contract defines the operations which are exposed by the service to the outside
world. A service contract is the interface of the WCF service and it tells the outside world
what the service can do. It may have service-level settings, such as the name of the service
and namespace for the service.
Operation Contract:
An Operation Contract defines the method exposed to the client to exchange the
information between the client and server. An Operation Contract describes what
functionality is to be given to the client, such as addition, subtraction and so on.
It can be defined as in the following:
1.
2.
3.
[OperationContract]
4.
5.
[OperationContract]
11
6.
7.
Data Contract:
Data Contracts define the data type for variables that are the same as get and set
properties but the difference is that a Data Contract in WCF is used to serialize and
deserialize the complex data. It defines how data types are serialized and deserialized.
Using serialization, you can convert an object into a sequence of bytes that can be
transmitted over a network. Using de-serialization, you reassemble an object from a
sequence of bytes that you receive from a calling application.
Example:
DataContract
1.
2.
3.
4.
5.
[DataMember]
6.
7.
8.
get
9.
10.
return _Name;
11.
12.
set
13.
14.
_Name = value;
15.
16.
}
}
17. }
12
Message Contract
When an operation contract required to pass a message as a parameter or return value as
a message, the type of this message will be defined as message contract. A message
contract defines the elements of the message (like as Message Header, Message Body), as
well as the message-related settings, such as the level of message security.
Message contracts give you complete control over the content of the SOAP header, as well
as the structure of the SOAP body.
Fault Contract:
A fault contract defines errors raised by the service, and how the service handles and
propagates errors to its clients. An operation contract can have zero or more fault contracts
associated with it.
The following is the syntax to raise the custom error in WCF:
1.
[ServiceContract]
2.
3.
4.
[OperationContract]
5.
[FaultContract(typeof (Student))]
6.
7.
8.
[DataContract]
9.
10. {
11.
12.
13.
[DataMember]
14.
15.
16.
get
17.
13
18.
return _Name;
19.
20.
set
21.
22.
_Name = value;
23.
24.
25.
[DataMember]
26.
27.
28.
get
29.
30.
return _City;
31.
32.
set
33.
34.
_City = value;
35.
36.
37. }
data contract. User defined object are explicit or Complex type, for which you have to define
a Data contract using [DataContract] and [DataMember] attribute.
A data contract can be defined as follows:
It describes the external format of data passed to and from service operations.
It defines how data types are serialized and deserialized. Through serialization, you
convert an object into a sequence of bytes that can be transmitted over a network.
Through deserialization, you reassemble an object from a sequence of bytes that
you receive from a calling application.
1.
[DataContract]
2.
3.
4.
Answer
A Message Contract is used to control the structure of a message body and serialization
process. It is also used to send / access information in SOAP headers. By default WCF
takes care of creating SOAP messages according to service DataContracts and
OperationContracts.
[MessageContract]
2.
3.
4.
5.
Message Header
A Message Header is applied to a member of a message contract to declare the member
within the message header.
1.
[MessageContract]
2.
3.
4.
[MessageHeader]
16
5.
6.
[MessageContract]
2.
3.
4.
[MessageBodyMember]
5.
6.
17
Question 12: What is End Points and how many types of End points?
Answer
Endpoints provide the configuration required for the communication and create the
complete WCF service application.
An Endpoint is a piece of information that tells WCF how to build the runtime
communication channels to send and receive messages. An endpoint consists of the three
things address, binding and contract.
18
A binding that specifies how a client can communicate with the endpoint.
Address: The address uniquely identifies the endpoint and tells potential consumers
of the service where it is located. It is represented in the WCF object model by
theEndpointAddress class. An EndpointAddress class contains:
19
Binding: The binding specifies how to communicate with the endpoint. This
includes:
Contracts: The contract outlines what functionality the endpoint exposes to the
client. A contract specifies:
20
In WCF every service are associated with unique address. The address provided two
imported elements the location of services and the transport protocol which will help to
communicate with the services .WCF support the following transport schemes. Here is the
answer for what are the supported transport protocols in WCF.
HTTP/HTTPS
TCP
IPC
Peer Network
MSMQ
Service BUS
21
ABCs of WCF
Transport - Defines the base protocol to be used like HTTP, Named Pipes, TCP, and
MSMQ are some type of protocols.
The following table gives some list of protocols supported by WCF binding.
Binding
Description
BasicHttpBinding
WSHttpBinding
WSDualHttpBinding
WSFederationHttpBin
ding
22
transactions.
NetMsmqBinding
NetNamedPipeBinding
NetPeerTcpBinding
NetTcpBinding
23
Prepare Phase - In this phase, the transaction manager checks whether all the
entities are ready to commit for the transaction or not.
Commit Phase - In this phase, the commitment of entities get started in reality.
Question 16: What are the possible ways of hosting a WCF service?
Answer: A WCF service can be self-hosting using a console application or Windows Forms
applications. Hosting a WCF service in any managed .Net application is called self-hosting.
Now the following is the procedure for creating a WCF service and hosting it in a console
application. Hosting Environment Requirements:
Reliability: What happens when your service somehow breaks? How does this
affect other consumers?
24
Versioning: Do you need to support older versions of the service? Do you know who
is consuming your services?
Deployment: What is your deployment model? Are you installing through the
Microsoft Installer process and Visual Studio deployment packages, or is xcopy
sufficient?
The following are the various options available for hosting a WCF Service:
1. Self-Hosting
2. Windows Service
3. Internet Information Services (IIS)
4. Windows Activation Services (WAS)
For more details visit the following link:
25
Is easy to use: With only a few lines of code you have your service running.
Is flexible: You can easily control the lifetime of your services through
the Open() andClose() methods of ServiceHost<T>.
Supports all bindings and transports: Self-hosting doesn't limit you to out-of-thebox bindings and transports whatsoever. On Windows XP and Windows Server
2003, IIS limits you to HTTP only.
Limited availability: The service is reachable only when the application is running.
Limited features: Self-hosted applications have limited support for high availability,
easy manageability, robustness, recoverability, versioning, and deployment
scenarios. At least, out-of-the-box WCF doesn't provide these, so in a self-hosted
scenario you have to implement these features yourself; IIS, for example, comes
with several of these features by default.
2. WCF Service host: WCF supports four types of hosting, IIS, Windows Process
Activation Services (WAS), self-hosting and Windows Services.
Binding: A binding that specifies how a client can communicate with the service.
Contract: A Contract that specifies what can the service do for us.
WCF Overview
Answer 8: IIS hosting: if we are hosting a WCF Service in IIS (version 5 or 6), only the
HTTP option is available as the transport protocol. In later versions of Internet Information
Services (IIS), we can use any other protocol (TCP/IP, MSMQ, NamedPipes and so on.) as
transport protocol.
If we host our service under IIS then we have all the features of IIS like process recycling,
ideal shutdown etc. Visual Studio provides two different ways to host our WCF service in a
local IIS in all are familiar with Publishing Wizard. Here we will discuss the second way
using Visual Studio only in a simple manner to host our WCF service in local IIS. To host the
WCF services follow the steps below.
The updated configuration for System.ServiceModel in the web.config will be as follows:
1.
2.
3.
4.
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name=StudentServiceBehavior>
5.
<serviceMetadata httpGetEnabled=true/>
6.
7.
</serviceBehaviors>
8.
</behaviors>
9.
<services>
10.
11.
12.
13.
14.
15.
16.
<identity>
<dns value=localhost/> </identity>
</endpoint>
<endpoint address=mex binding=mexHttpBinding contract=IMetadataExchange/
> </service>
</services>
17. </system.serviceModel>
28
29
When the client must call operations and is not affected by the result of the operation
at the operation level.
1.
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
2.
3.
4.
[OperationContract(IsOneWay = true)]
5.
6.
[OperationContract(IsOneWay = true)]
7.
8.
[OperationContract(IsOneWay = true)]
9.
10.
[OperationContract(IsOneWay = true)]
11.
30
12. }
using System;
2.
using System.Net.Security;
3.
namespace System.ServiceModel
4.
5.
[AttributeUsage(AttributeTargets.Method)]
6.
7.
8.
public OperationContractAttribute();
9.
10.
11.
get;
31
12.
set;
13.
14.
15.
16.
get;
17.
set;
18.
19.
20.
21.
get;
22.
23.
24.
25.
get;
26.
set;
27.
28.
29.
30.
get;
31.
set;
32.
33.
34.
35.
get;
36.
set;
37.
38.
32
39.
40.
get;
41.
set;
42.
43.
44.
45.
get;
46.
set;
47.
48.
49.
50.
get;
51.
set;
52.
53.
54. }
The client has nothing to do anything specific to invoke one way operation.
For more details visit the following link:
33
XMLSerializer
NetDataContractSerializer
DataContractSerializer
WCF deserializes WCF messages into .Net objects and serializes .Net objects into WCF
messages. WCF provides DataContractSerializer by default with a servicecontract. We can
change this default serializer to a custom serializer like XMLSerializer.
1.
[XmlSerializerFormat]
2.
[ServiceContract]
3.
4.
5.
[OperationContract]
6.
7.
The XmlSerializerFormat attribute above the ServiceContract means this serializer is for all
operation contracts. You can also set a separate contract for each operation.
XMLSerializer
We can find XMLSerializer in the System.Xml.Serialization namespace. WCF supports this
serialization from .Net 1.0. It is used by default with the ASP.Net webservices (ASMX).
NetDataContractSerializer
NetDataContractSerializer is analogous to .Net Remoting Formatters. It implements
IFormatter and it is compatible with [Serializable] types. It is not recommended for service
oriented design.
DataContractSerializer
DataContractSerializer is a default serializer for WCF. We need not to mention
34
2.
bindingBeingUsed.TransactionFlow = "true";
<bindings>
<wsHttpBinding>
<binding name="binding1" transactionFlow="true" />
</wsHttpBinding>
</bindings>
wsHttpBinding
netTcpBinding
35
netNamedPipeBinding
wsDualHttpBinding
wsFederationHttpBinding
Description
Property
maxConcurrentSessi
ons
This specifies the maximum number of sessions at one time within the
service host object. The default value is 10 (WCF 4.0 increases that to
100 * Processor Count).
1.
2.
3.
4.
5.
<configuration>
<system.serviceModel>
<services>
<service .... .... .... </service>
</services>
36
6.
7.
8.
9.
10.
11.
12.
13.
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceThrottling maxConcurrentCalls="16" maxConcurrentSessions="100" max
ConcurrentInstances="10" />
<serviceMetadata httpGetEnabled="true" /> </behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
14. </configuration>
Question 26: What is WCF Concurrency and How many modes are of
Concurrency in WCF?
Answer: WCF Concurrency means Several computations are executing simultaneously.
WCF concurrency helps us configure how WCF service instances can serve multiple
requests at the same time. You will need WCF concurrency for the below prime reasons;
there can be other reasons as well but these stand out as important reasons:
We can use the concurrency feature in the following three ways:
Single
Multiple
Reentrant
Single: A single request will be processed by a single thread on a server at any point of
time. The client proxy sends the request to the server, it process the request and takes
another request.
The following is the declaration of Concurrency.Single:
Multiple: Multiple requests will be processed by multiple threads on the server at any point
of time. The client proxy sends multiple requests to the server. Requests are processed by
the server by spawning multiple threads on the server object.
Reentrant: The reentrant concurrency mode is nearly like the single concurrency mode. It
is a single-threaded service instance that receives requests from the client proxy and it
unlocks the thread only after the reentrant service object calls the other service or can also
call a WCF client through call back.
1.
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple]
2.
3.
4.
38
Question 28: What is Exception Handling in WCF? What are the ways
for WCF Exception Handling?
39
Answer: Exception handling is critical to all applications for troubleshooting the unexpected
problems in applications. The Windows Communication Framework (WCF) provides several
options for handling exceptions in WCF services. This article discusses these approaches
and describes the advantages and disadvantages of each. The following options are
provided to handle exceptions in WCF:
1. Using returnUnknownExceptionsAsFaults: Debugging Mode
2. Using FaultException: Best Option.
3. Using IErrorHandler: Only when the exception can't be handled by Fault
Exception handling in WCF
2.
3.
if(user.isValid())
4.
5.
//Create User
40
6.
7.
else
8.
9.
10.
11. }
Example
1.
2.
3.
4.
5.
try
6.
7.
8.
9.
catch (Exception ex
10.
11.
12.
13.
14.
15. }
the classes that reside in the System.Diagnostic namespace. The important classes are
Trace, TraceSource and TraceListener.
Configuring WCF to emit tracing information/Define Trace Source, we have the following
options:
System.ServiceModel
System.ServiceModel.MessageLogging
System.ServiceModel.IdentityModel
System.ServiceModel.Activation
System.Runtime.Serialization
System.IO.Log
Cardspace
Example
1.
2.
3.
4.
configuration>
<system.diagnostics>
<sources>
<source name="System.ServiceModel"
5.
switchValue="Information, ActivityTracing"
6.
propagateActivity="true">
7.
8.
<listeners>
<add name="traceListener"
9.
type="System.Diagnostics.XmlWriterTraceListener"
10.
11.
12.
13.
</listeners>
</source>
</sources>
42
14.
</system.diagnostics>
15. </configuration>
Question 30: What are the Various Types of Bindings WCF Supports?
Answer: Binding describes how a client is going to communicate to WCF service. Binding
is used as per client need. It supports different types of protocol to communicate with client
and different types of encoding to transfer the data over the internet. So, basically binding is
nothing but it is a way of communication between client and service as per client need.
43
Basic binding
This binding is provided by the BasicHttpBinding class. It is designed to expose a WCF
service as an ASMX web service, so that old clients (that are still using an ASMX web
service) can consume the new service. By default, it uses the HTTP protocol for transport
and encodes the message in UTF-8 text format. You can also use HTTPS with this binding.
Web binding
This binding is provided by the WebHttpBinding class. It is designed to expose WCF
services as HTTP requests using HTTP-GET and HTTP-POST. It is used with REST based
services that may provide output in XML or JSON format. This is very much used with social
networks for implementing a syndication feed.
Web Service (WS) binding:
This binding is provided by the WSHttpBinding class. It is like a basic binding and uses
HTTP or HTTPS protocols for transport. But this is designed to offer various WS - *
specifications such as WS Reliable Messaging, WS - Transactions, WS - Security and so
on which are not supported by Basic binding.
wsHttpBinding= basicHttpBinding + WS-* specification
WS Dual binding:
This binding is provided by the WsDualHttpBinding class. It is like a WsHttpBinding except it
supports bi-directional communication which means both clients and services can send and
receive messages.
TCP binding:
This binding is provided by the NetTcpBinding class. It uses TCP protocol for
communication between two machines within intranet (means same network). It encodes
the message in binary format. This is a faster and more reliable binding compared to the
HTTP protocol bindings. It is only used when the communication is WCF-to-WCF which
means both client and service should have WCF.
IPC binding:
This binding is provided by the NetNamedPipeBinding class. It uses named pipe for
communication between two services on the same machine. This is the most secure and
44
Whenever the client sends a request to a WCF service, what exactly happens behind the
scenes? Basically after making a client request the WCF service will create a service class
instance at the service that will do the operations involved and then it will return the
response back to the client. In this request and response process the service instance
45
[ServiceContract]
2.
interfaceIMyContract
3.
{...}
4.
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
5.
classMyService:IMyContract
6.
{...}
Per-Session Service: A new Instance will be created for every new client session and the
scope of that object will be the scope of that session.
1.
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
2.
classMyService:IMyContract
3.
{...}
Singleton Service: A single instance will be created for the service object that will take care
of all the requests coming from the same client or a different one.
By decorating the service with a service behavior, an Instance Context mode can be set.
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
For more details visit the following link:
46
The WCF service generally accepts and returns the base type. If you expect the service to
accept and return an inherited type then we use the knowntype attribute.
When passing parameters and return values between a client and a service, both endpoints
share all of the data contracts of the data to be transmitted.
1.
[DataContract]
2.
[KnownType(typeof (Student))]
3.
[KnownType(typeof (Teacher))]
4.
publicabstractclass Person
5.
6.
[DataMember]
7.
publicint Code
8.
9.
get;
10.
set;
11.
12.
[DataMember]
13.
publicstring Name
14.
15.
get;
16.
set;
17.
18. }
The basicHttpBinding binding is used in order to provide support for older clients that
expect a legacy ASMX Web service. The TransportCredentialOnly security mode option
passes the user credentials without encrypting or signing the messages.
BasicHttpBinding is suitable for communicating with ASP.NET Web Service (ASMX) based
services that conform to the WS-Basic Profile that conforms with Web Services.
This binding uses HTTP as the transport and text/XML as the default message
encoding.
This binding does not support WS-* functionalities like WS- Addressing, WSSecurity, WS-ReliableMessaging.
Start Visual Studio and select New Project from the Start page or from the File
menu, select New and then Project.
After selecting, a dialog will pop up showing all the templates provided by Visual
Studio.
From the Installed Templates select C# then inside that select WCF and inside that
you will select WCF Service Application.
BasicHttpBinding
WsHttpBinding
48
Security
support
BasicProfile 1.1.
WS-* specifications.
SOAP
version
SOAP 1.1
messaging
specifications.
order.
Default
security
options
Security
options
Basic
Certificate
One of the biggest differences you must have noticed is the security aspect. Bydefault,
BasicHttpBinding sends data in plain text while WsHttpBinding sends it in an encrypted
and secured manner. To demonstrate the same, let's make two services, one
using BasicHttpBindingand the other using WsHttpBinding and then let's see the security
aspect in a more detailed manner.
For more details visit the following link:
security policies for protecting messages and for authenticating and authorizing calls. WCF
provide a very easy and rich configurable environment to implement security.WCF supports
following securities:
Message
Transport
TransportWithMessageCredential
Message Security
Message security uses the WS-Security specification to secure messages. The message is
encrypted using the certificate and can now safely travel over any port using plain http. It
provides end-to-end security.
Transport Security
Transport security is a protocol implemented security so it works only point to point. As
security is dependent on protocol, it has limited security support and is bounded to the
protocol security limitations.
TransportWithMessageCredential:
This we can call a mixture of both Message and Transport security implementation.
For more details visit the following link:
message handling in WCF is ok for small size messages but for the large size messages
this approach is not good. So to overcome this problem Streaming in WCF come into
action.
Steaming and Binding
1. TCP, IPC and HTTP bindings support streaming.
2. For all the Binding streaming is disabled by default.
3. Streaming of the message should be enabled in the binding to override the buffering
and enable the streaming.
4. TransferMode property should be set according to the desired streaming mode in the
bindings.
5. Type of TransferMode property is enum TransferMode
Configuring Streaming in Config file
1.
2.
3.
4.
5.
6.
7.
8.
9.
<system.serviceModel>
<services>
<service name="OneWayService.Service1" behaviorConfiguration="OneWayService.Servi
ce1Behavior">
<!-- Service Endpoints -->
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="StreamedHtt
p" contract="OneWayService.IService1">
<identity>
<dns value="localhost" /> </identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /
> </service>
10.
</services>
11.
<bindings>
12.
13.
<basicHttpBinding>
<binding name="StreamedHttp" transferMode="Streamed" /> </basicHttpBinding>
51
14.
</bindings>
15.
<behaviors>
16.
17.
<serviceBehaviors>
<behavior name="OneWayService.Service1Behavior">
18.
<serviceMetadatahttpGetEnabled="true" />
19.
20.
21.
</serviceBehaviors>
</behaviors>
22. </system.serviceModel>
Streaming in WCF
Message Pattern: A message in WCF is very similar to messages in the real world.
52
It describes how the programs will exchange message each other. There are three way of
communication between source and destination,
There is no need to call a Java class from a C# class. When they want to talk with each
other they just send a message to each other. In the Next programming industry though it's
fine and cool to communicate via messages but there should be some standardization of
those messages. Then, when people try to exchange data between two programs they send
the standardized message to get it done.
53
Message integrity
Message confidentiality.
Request / Response
One-Way
Duplex
Message Exchange Patterns describes the way of communication between Client and
Server means how client and server would be exchange messages to each other. There are
three types of message exchange patterns.
Request/Response
Request / Response is a very common MEP. To set this pattern we need to set the
IsOneWay property of OperationContractAttribute as false. And the default value of the
IsOneWay property is false. So ultimately we do not need to set this property. It is set by
default. That is why it is very easy to implement.
1.
[ServiceContract]
2.
publicvinterface RequestReplyService
3.
55
4.
[OperationContract]
5.
6.
7.
[OperationContract(IsOneWay = false)]
8.
voidSaveData(string value);
9.
One-Way:
Set the IsOneWay property of OperationContractAttribute to true for a OneWay message
exchange pattern. Suppose you send a message to a service. This pattern is used when
the service does some operation and you do not want a response back. For example you
want to change the status of a transaction from pending to completed and you do not want
to get a confirmation from the service that the status is changed. You can use a OneWay
pattern.
1.
[ServiceContract]
2.
3.
4.
[OperationContract(IsOneWay=true)]
5.
6.
Duplex:
The duplex MEP is a two-way message channel. When the client sends a message to the
service to instantiate some long-running processing and requires notification back from the
service, a duplex MEP is applicable.
There are two types of contacts, ServiceContract and CallbackContract required to
implement a duplex MEP. This MEP is declared by associating a CallbackContract with the
ServiceContract. It is done through a CallbackContract property of ServiceContract.
56
57
When a service is configured PerCall, every client gets a new service instance. The above
diagram shows how a PerCall instance works:
1. Client calls the proxy and proxy forwards the call to service.
2. WCF creates an instance and calls the method call.
3. When method call returns, WCF calls IDisponsible if implemented.
PerSession Service
WCF maintains a logical session between client and service in Persession instance mode.
A new instance of the service class is created for each client.
The following given diagram represents the request from the client using Persession service
instance mode:
58
When should you use per call, per session, and single mode?
Per call:
Your service holds intensive resources like connection objects and huge memory
objects.
Scalability is a prime requirement. You would like to have a scaled out architecture.
Per session:
Single:
Description
Allows us to create and consume ASMX-style services within WCF.
No Security provided for the messages.
BasicHttpBinding
webHTTPBinding
wsHttpBinding
wsDualHttpBinding
means the both client and server can both send and receive
messages
wsFederationHttpBin
ding
netTCPBinding
netPeerTCPBinding
Used when you require more security for Peer to Peer Communication
60
as netTCPBinding.
Binding for asynchronous communication using Microsoft Message
netMsMqBinding
Queue (MSMQ).
Best when you need to execute service operations in a queued
manner.
MSMQ in WCF (Two Way Communication Between Client And Server): Part II
OR
Introduction to MSMQ
same name but each method should differ from another in the context of input and output of
the function. No two methods must have the same type parameters. Either they must differ
in the number of parameters or in the type of the parameters.
You can also refer to Method Overloading as a compile-time polymorphism since the calling
method knows the address of the called method and the method addresses are resolved at
compile time. This is also called as Early Binding.
Example:
1.
[ServiceContract]
2.
3.
4.
[OperationContract(Name = GetScheduledEventsByDate)]
5.
6.
[OpeartionContract(Name = GetScheduledEventsByDateRange)]
7.
8.
the SOAP header and the SOAP body. A SOAP envelope contains several pieces of key
information in the form of elements.
SOAP Header:
Using a SOAP header, we can pass useful information about the services to the outer world
if needed; it's just for information sharing. Any child elements of the header element are
called "header blocks". This provides a mechanism for grouping logical data together.
SOAP Body:
This element contains the actual SOAP message for communication with the SOAP
receiver; a message can contain zero or more bodies. Any information intended to be
exchanged when the message reaches the intended destination goes in the message body.
63
1. Duplex service allows calling back some operation (function) on the client.
2. Duplex service also knows as Call Backs.
3. All Binding does not support duplex service.
4. Duplex communication is not standard. They are absolute Microsoft feature.
5. wsDualHttpBinding supports duplex communication over HTTP binding.
6. Duplex communication is possible over netTcpBinding and netNamedPipeBinding
1.
2.
3.
4.
5.
6.
7.
8.
Request-Response
One-Way
Duplex
3. When we want that function call is not blocking and at the same time we want
something out of the function (response) for our application.
4. When we want a two-way communication mechanism.
For more details visit the following link:
Sr.
Trace
No
Level
Off
Event
Categor
Tracing Details
Traced Events
y
-
(No Tracing)
Ignores tracing.
All unexpected events
OutOfMemoryException
ThreadAbortException
Critical
StackOverFlowException
ConfigurationErrorsException
Events
SEHException
immediately.
Error
Negative
Events
Warning
Negative
Events
2) Rejected credentials
Information Positive
Events
66
application execution.
6
Verbose
ActivityTraci
ng
All
Positive
Events
communication between
Scalability of Service
Performance of Service
Durability of Service
Transactions
Service Queues
Instance Management can be seen as a set of techniques to decide which service instance
will serve a client request and when.
Basically there are three instance modes in WCF:
68
Authentication
Authorization
Reduce IT pain
Information cards are virtual representations of a person's identity that are assured by a
particular party. Information cards are analogous to real-world identity cards such as
passports, driver's licenses, credit cards, and employee ID cards.
Sample Code: To show the usage of DerivativesCalculator which help in adding
Information card which require no external reference to do so.
1.
namespace DerivativesCalculator
2.
3.
4.
5.
6.
7.
8.
9.
}
}
69
10. }
Information cards are more flexible than simple user names and passwords.
Information cards employ strong cryptography, which makes their use more secure
than passwords.
Information cards can potentially present any type of identity claim that makes sense
to all of the interacting parties and which users are willing to release.
Hosting In WCF
Hosting WCF services in IIS is easier and it is almost like hosting ASP.NET applications and
ASMX. IIS also provides the same capabilities to WCF services as like ASP.NET
applications. Lets talk about these in detail
IIS Hosting
There are several benefits in Hosting WCF Services in IIS,
Automatic Activation
One of the most important benefits is Automatic Activation which means the service
is not required to be running in advance. Whenever the service receives any
message from the client, then it only launches and processes the request. We can
also call it a Message Based Activation which means a message comes from the
70
Process Recycling
Process Recycling => Recycle the process every 120 minutes . Hope you are aware
that for any request you made in the browser, the worker process gets created on
the server side to service the request. Every 120 minutes (if you configured in such a
way), the worker process will be recreated/refreshed/recycled to avoid any memory
leaks/performance issues. Due to which, the performance of the server will be
increased. So, if we host WCF Service in IIS, you can enjoy these benefits for your
WCF server. Otherwise, you need to write custom code in order to provide these
benefits to your WCF Server when you do the Self Hosting. Frequent checking
keeps your system from getting into a problem
Configuration Steps
Step 1- Create a service library.
71
In the above snapshot, you can find that IServiceLib is the contract defined and ServiceImp
is the class implemented in the IServiceLib
Step 3- Open the App.config file and define the service name, address, endpoint, binding
and service behaviors. Please use the below- attached snapshot for reference.
72
Step 4- Create WCF Service project and name it as WCFServiceApp to host it in IIS.
Step 5- Once you create the project, please delete the .cs files because we have already
defined the contracts and implementation in another project (Step 2). Add the reference of
the WCFService Library into this project.
73
Step 6- Open the .svc file and update the service tag into a Service implementation class
details.Hope you remember that we had updated the Service name in step 2. The same
name should be updated in the Service tag, as mentioned in the below snapshot
Step 7- Right click the .svc file and browse. You should be able to browse the content in
browser, as you see in the following snapshots
74
75
Until this point, you were able to create the library files that it referred in the service
application .
Step 8- Finally, you need to add the application to IIS. Open the IIS and right click the
default website. Add the current application into IIS. Refer to the below snapshot for details.
76
Step 9- Once it is added, select your site and right click the .svc file. You should be able to
browse.
Summary
77
IIS Hosting is a simpler way of WCF hosting and it provides a lot of benefits, like Message
based activation and Process Recycling to avoid giving the system any problems.
78