Sie sind auf Seite 1von 100

Introduction to WCF

Windows Communication Foundation (Code named Indigo) is a programming platform and runtime
system for building, configuring and deploying network-distributed services. It is te latest service
oriented tecnology! Interoperability is te fundamental caracteristics of WCF. It is unified
programming model provided in ."et Framework #.$. WCF is a combined features of Web %ervice,
&emoting, '%'( and C)'*. WCF provides a common platform for all ."+, communication.
-elow figures sows te different tecnology combined to form WCF.
Advantage
.. WCF is interoperable wit oter services wen compared to ."et &emoting,were te client
and service ave to be ."et.
/. WCF services provide better reliability and security in compared to 0%'1 web services.
#. In WCF, tere is no need to make muc cange in code for implementing te security model
and canging te binding. %mall canges in te configuration will make your re2uirements.
3. WCF as integrated logging mecanism, canging te configuration file settings will
provide tis functionality. In oter tecnology developer as to write te code.
Disadvantage
'aking rigt design for your re2uirement is little bit difficult. I will try to elp you on solving tese
difficulties in te following article.
Development Tools
Default template is available for WCF

1. WCF - Test Client tools for testing the WCF service.
'icrosoft provides inbuilt application to test te WCF application. ,is can be done by opening te
4isual %tudio command prompt and type te wcfClient Serviceurl sows below. ,is will elp te
developer to test te service before creating te client application.

1. WCF services can be debugged now in isual !tudio "##$. Wcfsvchost.e%e
will do it for &ou because service will be self hosted when &ou start
debugging.
Difference between WCF and Web service
Web service is a part of WCF. WCF offers muc more fle5ibility and portability to develop a
service wen comparing to web service. %till we are aving more advantages over Web service,
following table provides detailed difference between tem.
Features Web !ervice WCF
6osting It can be osted in II%
It can be osted in II%, windows activation
service, %elf-osting, Windows service
7rogramming
8Web%ervice9 attribute as to be added
to te class
8%erviceContraact9 attribute as to be added
to te class
'odel
8Web'etod9 attribute represents te
metod e5posed to client
8)perationContract9 attribute represents te
metod e5posed to client
)peration
)ne-way, &e2uest- &esponse are te
different operations supported in web
service
)ne-Way, &e2uest-&esponse, :uple5 are
different type of operations supported in
WCF
1';
%ystem.1ml.seriali<ation name space
is used for seriali<ation
%ystem.&untime.%eriali<ation namespace is
used for seriali<ation
+ncoding
1'; ..$, ',)'('essage
,ransmission )ptimi<ation
'ecanism), :I'+, Custom
1'; ..$, ',)', -inary, Custom
,ransports
Can be accessed troug 6,,7, ,C7,
Custom
Can be accessed troug 6,,7, ,C7,
"amed pipes, '%'(,7/7, Custom
7rotocols %ecurity %ecurity, &eliable messaging, ,ransactions
WCF Fundamental
In tis part of tutorial you are going to learn about some fundamental concepts in WCF. ,ese
concepts and terms will be used trougout tis tutorial.
+nd 7oint
-indings and -eavior
Contracts and %ervice ost
'essage and Cannel
WCF client and 'etadata
'nd(oint
WCF %ervice is a program tat e5poses a collection of +ndpoints. +ac +ndpoint is a portal for
communicating wit te world.
0ll te WCF communications are take place troug end point. +nd point consists of tree
components.
Address
-asically =&;, specifies were tis WCF service is osted .Client will use tis url to connect to te
service. e.g
ttp>??localost>@$A$?'y%ervice?%impleCalculator.svc
)inding
-inding will describes ow client will communicate wit service. ,ere are different protocols
available for te WCF to communicate to te Client. Bou can mention te protocol type based on
your re2uirements.
0 binding as several caracteristics, including te following>
,ransport -:efines te base protocol to be used like 6,,7, "amed 7ipes, ,C7, and '%'(
are some type of protocols.
+ncoding ()ptional) - ,ree types of encoding are available-,e5t, -inary, or 'essage
,ransmission )ptimi<ation 'ecanism (',)'). ',)' is an interoperable message
format tat allows te effective transmission of attacments or large messages (greater tan
C3D).
7rotocol()ptional) - :efines information to be used in te binding suc as %ecurity,
transaction or reliable messaging capability
,e following table gives some list of protocols supported by WCF binding.
)inding Description
-asic6ttp-inding -asic Web service communication. "o security by default
W%6ttp-inding Web services wit W%-E support. %upports transactions
W%:ual6ttp-inding Web services wit duple5 contract and transaction support
W%Federation6ttp-inding Web services wit federated security. %upports transactions
'sm2Integration-inding
Communication directly wit '%'( applications. %upports
transactions
"et'sm2-inding
Communication between WCF applications by using 2ueuing.
%upports transactions
"et"amed7ipe-inding
Communication between WCF applications on same computer.
%upports duple5 contracts and transactions
"et7eer,cp-inding
Communication between computers across peer-to-peer services.
%upports duple5 contracts
"et,cp-inding
Communication between WCF applications across computers.
%upports duple5 contracts and transactions
Contract
Collection of operation tat specifies wat te endpoint will communicate wit outside world.
=sually name of te Interface will be mentioned in te Contract, so te client application will be
aware of te operations wic are e5posed to te client. +ac operation is a simple e5cange pattern
suc as one-way, duple5 and re2uest?reply.
-elow figure illustrate te functions of +ndpoint
'%ample*
+ndpoints will be mentioned in te web.config file on te created service.
<system.serviceModel>
<services>
<service name="MathService"
behaviorConfiguration="MathServiceBehavior">
<endpoint
address="http:localhost:!"#"MyServiceMathService.svc"
contract="$MathService"
binding="%s&ttpBinding">
<service>
<services>
<behaviors>
<serviceBehaviors>
<behavior name="MathServiceBehavior">
<serviceMetadata http'et(nabled=")rue">
<service*ebug include(+ception*etail$n,aults="true" >
<behavior>
<serviceBehaviors>
<behaviors>
<system.serviceModel>

)inding and )ehavior
)inding
%imple definition for -inding describes ow te client will communicate wit service. We can
understand wit an e5ample.
Consider a scenario say, I am creating a service tat as to be used by two type of client. )ne of te
client will access %)07 using ttp and oter client will access -inary using ,C7. 6ow it can be
doneF Wit Web service it is very difficult to acieve, but in WCF its Gust we need to add e5tra
endpoint in te configuration file.
<system.serviceModel>
<services>
<service name="MathService"
behaviorConfiguration="MathServiceBehavior">
<endpoint address="http:localhost:!"#"MyServiceMathService.svc"
contract="$MathService"
binding="%s&ttpBinding">
<endpoint address="net.tcp:localhost:!"!"MyServiceMathService.svc"
contract="$MathService"
binding="net)cpBinding">
<service>
<services>
<behaviors>
<serviceBehaviors>
<behavior name="MathServiceBehavior">
<serviceMetadata http'et(nabled=")rue">
<service*ebug include(+ception*etail$n,aults="true" >
<behavior>
<serviceBehaviors>
<behaviors>
<system.serviceModel>

%ee ow simple it is in WCF. 'icrosoft is making everyting simple.cording to its scope> common
beaviors affect all endpoints globally, service beaviors affect only service-related aspects,
endpoint beaviors affect only endpoint-related properties, and operation-level beaviors affect
particular operations.
'%ample*
In te below configuration information, I ave mentioned te -eavior at %ervice level. In te
service beavior I ave mention te servie'etadata node wit attribute ttHet+nabledIJtrueJ. ,is
attribute will specifies te publication of te service metadata. %imilarly we can add more beavior
to te service.
<system.serviceModel>
<services>
<service name="MathService"
behaviorConfiguration="MathServiceBehavior">
<endpoint address="" contract="$MathService"
binding="%s&ttpBinding">
<service>
<services>
<behaviors>
<serviceBehaviors>
<behavior name="MathServiceBehavior">
<serviceMetadata http'et(nabled=")rue">
<service*ebug include(+ception*etail$n,aults="true" >
<behavior>
<serviceBehaviors>
<behaviors>
<system.serviceModel>

+ote*
0pplication can be controlled eiter troug coding, configuring or troug combination of bot.
%pecification mention in te configuration can also be overwritten in code.
Contracts and !ervice ,ost
Contracts
In WCF, all services are e5posed as contracts. Contract is a platform-neutral and standard way of
describing wat te service does. 'ainly tere are four types of contracts available in WCF
!ervice Contract
%ervice contracts describe te operation tat service can provide. For +g, a %ervice provide to know
te temperature of te city based on te <ip code, tis service is called as %ervice contract. It will be
created using %ervice and )perational Contract attribute.
,o know more on %ervice contract see %ervice contract tutorial.
Data Contract
:ata contract describes te custom data type wic is e5posed to te client. ,is defines te data
types, tat are passed to and from service. :ata types like int, string are identified by te client
because it is already mention in 1'; scema definition language document, but custom created
class or data types cannot be identified by te client e.g. +mployee data type. -y using
:ataContract we can make client to be aware of +mployee data type tat are returning or passing
parameter to te metod.
,o know more on :ataContract see :ataContract tutorial.
-essage Contract
:efault %)07 message format is provided by te WCF runtime for communication between Client
and service. If it is not meeting your re2uirements ten we can create our own message format. ,is
can be acieved by using 'essage Contract attribute.
,o know more on 'essage Contract see 'essage contract tutorial.
Fault Contract
%uppose te service I consumed is not working in te client application. I want to know te real
cause of te problem. 6ow I can know te errorF For tis we are aving Fault Contract. Fault
Contract provides documented view for error occurred in te service to client. ,is elps us to easy
identity, wat error as occurred.
,o know more on Fault Contract see Fault Contract tutorial.
!ervice ,ost
%ervice 6ost obGect is in te process of osting te WCF service and registering endpoints. It loads
te service configuration endpoints, apply te settings and start te listeners to andle te incoming
re2uest. System.ServiceModel.ServiceHost namespace old tis obGect. ,is obGect is created wile
self osting te WCF service.
In te below e5ample you can find tat WCF service is self osted using console application.
Creating uri for the hosting the service
-ri uri = ne% -ri."http:localhostCategoryService"/0
Creating the host ob1ect for MathService
Service&ost host = ne% Service&ost.typeof.CategoryService/2 uri/0
3dding endpoint to the &ost ob1ect
host.3ddService(ndpoint.typeof.$CategoryService/2ne% 4S&ttpBinding./2 uri/0
host.5pen./0 &osting the Service
Console.4rite6ine."4aiting for client invocations"/0
Console.7ead6ine./0
host.Close./0
-essage and Channel
-essage
WCF 'essage is te unit of data e5cange between client and service. It consists of several parts,
including a body and eaders.
WCF .untime
WCF runtime is te set of obGect responsible for sending and receiving message. For e5ample
formatting te message, applying security and transmitting and receiving message using various
protocol.
Channels*
Cannels are te core abstraction for sending message to and receiving message from an +ndpoint.
-roadly we can categories cannels as
Transport Channels
- ,andles sending and receiving message from networ/. (rotocols li/e ,TT(0 TC( name pipes
and -!-1.
(rotocol Channels
- Implements %)07 based protocol by processing and possibly modifying message. e.g. W%-
%ecurity and W%-&eliability.
WCF Client and -etadata
WCF Client
WCF client is a client application creates to e5pose te service operations as metod. 0ny
application can ost a WCF client, including an application tat ost a service. ,erefore it is
possible to create a service tat includes WCF clients of oter services.
0 client application is a managed application tat uses a WCF client to communicate wit anoter
application. ,o create a client application for a WCF service re2uires te following steps>
.. Het te 7ro5y class and service end point information
=sing SvcUtil.exe we can create pro5y class for te service and configuration information
for endpoints. +5ample type te following sentence in te 4isual studio command prompt,
tis will generate te class file and configuration file wic contain information about te
endpoints.
svcutil /language:vb /out:ClientCode.vb /config:app.config
http://localhost:!"!/MyService/SimpleCalculator.svc#wsdl
/. Call operations.
0dd tis class files in te client application. ,en create te obGect for tis class and invoke
te service operation. Configuration information we got from te above step as to be added
to te client application configuration file. Wen te client application calls te first
operation, WCF automatically opens te underlying cannel. ,is underlying cannel is
closed, wen te obGect is recycled.
Creating the pro+y on client side
MyCalculatorService8ro+y.MyService8ro+y pro+y
= ne% MyCalculatorService8ro+y.MyService8ro+y./0
Console.4rite6ine."Counter: " 9 pro+y.MyMethod.//0
#. Close te WCF client obGect.
0fter using te obGect created in te above steps, we ave to dispose te obGect. Cannel will
be closed wit te service, wen te obGect is cleared.
-etadata
Caracteristics of te service are described by te metadata. ,is metadata can be e5posed to te
client to understand te communication wit service. 'etadata can be set in te service by enabling
te %ervice'etadata node inside te servcie-eaviour node of te service configuration file.
<system.serviceModel>
<services>
<service name="MathService"
behaviorConfiguration="MathServiceBehavior">
<endpoint address="" contract="$MathService"
binding="%s&ttpBinding">
<service>
<services>
<behaviors>
<serviceBehaviors>
<behavior name="MathServiceBehavior">
<serviceMetadata http'et(nabled=")rue">
<service*ebug include(+ception*etail$n,aults="true" >
<behavior>
<serviceBehaviors>
<behaviors>
<system.serviceModel>
,is metadata can be viewed wile creating WCF client application using SvcUtil.exe
WCF Architecture
,e following figure illustrates te maGor components of WCF.
Figure .> WCF 0rcitecture
Contracts
Contracts layer are ne5t to tat of 0pplication layer. :eveloper will directly use tis contract to
develop te service. We are also going to do te same now. ;et us see briefly wat tese contracts
will do for us and we will also know tat WCF is working on message system.
!ervice contracts
- :escribe about te operation tat service can provide. +5ample, %ervice provided to know te
temperature of te city based on te <ip code, tis service we call as %ervice contract. It will be
created using %ervice and )perational Contract attribute.
Data contract
- It describes te custom data type wic is e5posed to te client. ,is defines te data types, are
passed to and from service. :ata types like int, string are identified by te client because it is
already mention in 1'; scema definition language document, but custom created class or
datatype cannot be identified by te client e.g. +mployee data type. -y using :ataContract we can
make client aware tat we are using +mployee data type for returning or passing parameter to te
metod.
-essage Contract
- :efault %)07 message format is provided by te WCF runtime for communication between
Client and service. If it is not meeting your re2uirements ten we can create our own message
format. ,is can be acieved by using 'essage Contract attribute.
(olicies and )inding
- %pecify conditions re2uired to communicate wit a service e.g security re2uirement to
communicate wit service, protocol and encoding used for binding.
!ervice .untime
- It contains te beaviors tat occur during runtime of service.
,rottling -eavior- Controls ow many messages are processed.
+rror -eavior - %pecifies wat occurs, wen internal error occurs on te service.
'etadata -eavior - ,ells ow and weter metadata is available to outside world.
Instance -eavior - %pecifies ow many instance of te service as to be created wile
running.
,ransaction -eavior - +nables te rollback of transacted operations if a failure occurs.
:ispatc -eavior - Controls ow a message is processed by te WCF Infrastructure.
-essaging
- 'essaging layer is composed of cannels. 0 cannel is a component tat processes a message in
some way, for e5ample, by autenticating a message. 0 set of cannels is also known as a cannel
stack. Cannels are te core abstraction for sending message to and receiving message from an
+ndpoint. -roadly we can categories cannels as
,ransport Cannels
6andles sending and receiving message from network. 7rotocols like 6,,7, ,C7, name
pipes and '%'(.
7rotocol Cannels
Implements %)07 based protocol by processing and possibly modifying message. +.g. W%-
%ecurity and W%-&eliability.
Activation and ,osting
- %ervices can be osted or e5ecuted, so tat it will be available to everyone accessing from te
client. WCF service can be osted by following mecanism
II%
Internet information %ervice provides number of advantages if a %ervice uses 6ttp as
protocol. It does not re2uire 6ost code to activate te service, it automatically activates
service code.
Windows 0ctivation %ervice
(W0%) is te new process activation mecanism tat sips wit II% K.$. In addition to 6,,7
based communication, WCF can also use W0% to provide message-based activation over
oter protocols, suc as ,C7 and named pipes.
%elf-6osting
WCF service can be self osted as console application, Win Forms or W7F application wit
grapical =I.
Windows %ervice
WCF can also be osted as a Windows %ervice, so tat it is under control of te %ervice
Control 'anager (%C').
WCF ,osting
In tis part of te tutorial we are going to see te four different way of osting te WCF service.
WCF service cannot e5ist on its own! it as to be osted in windows process called as ost process.
%ingle ost process can ost multiple servers and same service type can be osted in multiple ost
process. 0s we discussed tere are mainly four different way of osting te WCF service.
.. II% osting
/. %elf osting
#. Windows 0ctivation %ervice
3. Windows %ervice
'ultiple osting and protocols supported by WCF.'icrosoft as introduced te WCF concept in
order to make distributed application development and deployment simple.
,osting 'nvironment !upported protocol
Windows console and form application 6,,7,net.tcp,net.pipe,net.msm2
Windows service application (formerly known as ", services) 6,,7,net.tcp,net.pipe,net.msm2
Web server II%C ttp, wsttp
Web server II%K - Windows 7rocess 0ctivation %ervice (W0%) 6,,7,net.tcp,net.pipe,net.msm2
0 summary of osting options and supported features.
Feature !elf-,osting II! ,osting WA! ,osting
+5ecutable 7rocess? 0pp :omain Bes Bes Bes
Configuration 0pp.config Web.config Web.config
0ctivation 'anual at startup 'essage-based 'essage-based
Idle-,ime 'anagement "o Bes Bes
6ealt 'onitoring "o Bes Bes
7rocess &ecycling "o Bes Bes
'anagement ,ools "o Bes Bes
II! 234 ,osting
,e main advantage of osting service in II% is tat, it will automatically launc te ost process
wen it gets te first client re2uest. It uses te features of II% suc as process recycling, idle
sutdown, process ealt monitoring and message based activation. ,e main disadvantage of using
II% is tat, it will support only 6,,7 protocol.
;et as do some ands on, to create service and ost in II%
!tep 1*%tart te 4isual %tudio /$$@ and click File-L"ew-LWeb %ite. %elect te JWCF %erviceJ and
;ocation as ttp. ,is will directly ost te service in II% and click )D.

!tep "* I ave created sample 6elloWorld service, wic will accept name as input and return wit
J6elloJ and name. Interface and implementation of te %ervice is sown below.
I-&!ervice.cs
:ServiceContract;
public interface $MyService
<
:5perationContract;
string &ello4orld.string name/0
=
-&!ervice.cs
public class MyService : $MyService
<
>region $MyService Members
public string &ello4orld.string name/
<
return "&ello " 9 name0
=
>endregion
=
!tep 5* %ervice file (.svc) contains name of te service and code beind file name. ,is file is used
to know about te service.
-&!ervice.svc
<?@ Service&ost 6anguage="C>" *ebug="true"
Service="MyService" CodeBehind="A3ppBCodeMyService.cs" ?>
!tep 6* %erver side configurations are mentioned in te config file. 6ere I ave mention only one
end point wic is configured to Jws6ttp-indingJ, we can also ave multiple end point wit
differnet binding. %ince we are going to osted in II%. We ave to use only ttp 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$$S&ostedServiceMyService.svc"
binding="%s&ttpBinding" contract="$MyService">
<identity>
<dns value="localhost">
<identity>
<endpoint>
<endpoint address="me+" binding="me+&ttpBinding"
contract="$Metadata(+change">
<service>
<services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<CDD )o avoid disclosing metadata information2
set the value belo% to false and remove the
metadata endpoint above before deployment DD>
<serviceMetadata http'et(nabled="true">
<CDD )o receive e+ception details in faults for
debugging purposes2 set the value belo% to true.
Set to false before deployment to avoid disclosing e+ception information
DD>
<service*ebug include(+ception*etail$n,aults="false">
<behavior>
<serviceBehaviors>
<behaviors>
<system.serviceModel>
+ote*
Bou need to mention te service file name, along wit te 0ddress mention in te config file. II%
%creen sot

,is screen will appear wen we run te application.

!tep 2* "ow we successfully osted te service in II%. "e5t we ave to consume tis service in
client application. -efore creating te client application, we need to create te pro5y for te service.
,is pro5y is used by te client application, to interact wit service. ,o create te pro5y, run te
4isual %tudio /$$@ command prompt. =sing service utility we can create te pro5y class and its
configuration information.
svcutil http://localhost/IISHostedService/MyService.svc

0fter e5ecuting tis command we will find two file generated in te default location.
'y%ervice.cs - 7ro5y class for te WCF service
output.config - Configuration information about te service.
!tep 4* "ow we will start creating te Console application using 4isual %tudio /$$@(Client
application).

!tep 7* 0dd te reference J%ystem.%ervice'odelJ! tis is te core dll for WCF.

!tep $* Create te obGect for te pro5y class and call te 6elloWorld metod.
static void Main.string:; args/
<
Creating 8ro+y for the MyService
MyServiceClient client = ne% MyServiceClient./0
Console.4rite6ine."Client calling the service..."/0
Console.4rite6ine.client.&ello4orld."7am"//0
Console.7ead./0
=
!tep 8* If we run te application we will find te output as sown below.

I ope you ave enGoyed te %ervice osted in II%. "ow let start te look on te self osted service.
!elf ,osting
In web service, we can ost te service only in II%, but WCF provides te user to ost te service in
any application (e.g. console application, Windows form etc.). 4ery interestingly developer is
responsible for providing and managing te life cycle of te ost process. %ervice can also be in-pro
i.e. client and service in te same process. "ow letJs us create te WCF service wic is osted in
Console application. We will also look in to creating pro5y using $Client%ase$ abstract class.
+ote* ,ost process must be running before the client calls the service0 which t&picall& means
&ou have to prelaunch it.
!tep 1* First let9s start create the !ervice contract and it implementation. Create a console
application and name it as -&Calculator!ervice. This is simple service which return addition
of two numbers.

!tep "* Add the !&stem.!ervice-odel reference to the pro:ect.

!tep 5* Create an I!impleCalculator interface0 Add !erviceContract and ;perationContract
attribute to the class and function as shown below. <ou will /now more information about
these contracts in later session. These contracts will e%pose method to outside world for using
this service.
I-&Calculator!ervice.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace MyCalculatorService
{
[ServiceContract(!
pu"lic inter#ace $SimpleCalculator
{
[%perationContract(!
int &dd(int num'( int num);
*
*
!tep 6* -&Calculator!ervice is the implementation class for I-&Calculator!ervice interface
as shown below.
-&Calculator!ervice.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyCalculatorService
{
class SimpleCalculator + $SimpleCalculator
{
pu"lic int &dd(int num'( int num)
{
return num' , num);
*
*
*
!tep 2* +ow we are read& with service. =et9s go for implementing the hosting process. Create
a new console application and name it as 9-&Calculator!ervice,ost9

!tep 4* ServiceHost is the core class use to host the WCF service. It will accept implemented
contract class and base address as contractor parameter. <ou can register multiple base
addresses separated b& commas0 but address should not use same transport schema.
-ri .ttp-rl
/ ne0 -ri(1.ttp+22local.ost+34542MyService2SimpleCalculator1;
-ri tcp-rl
/ ne0 -ri(1net.tcp+22local.ost+34542MyService2SimpleCalculator1;
Service6ost .ost
/ ne0 Service6ost(typeo#(MyCalculatorService.SimpleCalculator( .ttp-rl(
tcp-rl;
-ultiple end points can be added to the !ervice using AddServiceEndpoint() method.
Host.Open() will run the service0 so that it can be used b& an& client.
!tep 7* )elow 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.7escription;
namespace MyCalculatorService6ost
{
class 8rogram
{
static void Main(string[! args
{
22Create a -9$ to serve as t.e "ase address
-ri .ttp-rl / ne0
-ri(1.ttp+22local.ost+34542MyService2SimpleCalculator1;
22Create Service6ost
Service6ost .ost
/ ne0 Service6ost(typeo#(MyCalculatorService.SimpleCalculator(
.ttp-rl;
22&dd a service endpoint
.ost.&ddService:ndpoint(typeo#(MyCalculatorService.$SimpleCalculator

( ne0 ;S6ttp<inding(( 11;


22:na"le metadata exc.ange
ServiceMetadata<e.avior sm" / ne0 ServiceMetadata<e.avior(;
sm".6ttpGet:na"led / true;
.ost.7escription.<e.aviors.&dd(sm";
22Start t.e Service
.ost.%pen(;
Console.;riteLine(1Service is .ost at 1 , 7ateTime.=o0.ToString(;
Console.;riteLine(16ost is running... 8ress >:nter? @ey to stop1;
Console.9eadLine(;
*
*
*
!tep $* !ervice is hosted0 now we need to implement the pro%& class for the client. There are
different wa&s of creating the pro%&
>sing !vc>til.e%e0 we can create the pro%& class and configuration file with end points.
Adding !ervice reference to the client application.
Implementing Client)ase?T@ class
;f these three methods0 Implementing Client)ase?T@ is the best practice. If &ou are using
rest two method0 we need to create pro%& class ever& time when we ma/e changes in !ervice
implementation. )ut this is not the case for Client)ase?T@. It will create the pro%& onl& at
runtime and so it will ta/e care of ever&thing.
-&Calculator!ervice(ro%&.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using MyCalculatorService;
namespace MyCalculatorService8roxy
{
pu"lic class MyCalculatorService8roxy +
22;CA create proxy #or $SimpleCalculator using Client<ase
Client<ase>$SimpleCalculator?(
$SimpleCalculator
{
pu"lic int &dd(int num'( int num)
{
22Call "ase to do #untion
return "ase.C.annel.&dd(num'( num);
*
*
*
!tep 8* In the client side0 we can create the instance for the pro%& class and call the method as
shown below. Add pro%& assembl& as reference to the pro:ect.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
namespace MyCalculatorServiceClient
{
class 8rogram
{
static void Main(string[! args
{
MyCalculatorService8roxy.MyCalculatorService8roxy proxy ;
proxy/ ne0 MyCalculatorService8roxy.MyCalculatorService8roxy(;
Console.;riteLine(1Client is running at 1 ,
7ateTime.=o0.ToString(;
Console.;riteLine(1Sum o# t0o num"ers... B,B /1,proxy.&dd(B(B;
Console.9eadLine(;
*
*
*
!tep 1# * 'nd point Asame as serviceB information should be added to the configuration file of
the client application.
>Cxml version/1'.41 encoding/1ut#D31 C?
>con#iguration?
>system.serviceModel?
>client?
>endpoint address /1.ttp+22local.ost+34542MyService2SimpleCalculator1
"inding /10s6ttp<inding1
contract /1MyCalculatorService.$SimpleCalculator1?

>2endpoint?
>2client?
>2system.serviceModel?
>2con#iguration?
!tep 11* )efore running the client application0 &ou need to run the service. ;utput of the
client application is shown below.

This self host shows advantage such as in-(ro hosting0 programmatic access and it can be used
when there need singleton service. I hope &ou have en:o&ed the !elf hosting session0 now let go
for hosting using Windows Activation service.
Windows Activation !ervice
Windows 0ctivation service is a system service available wit Windows vista and windows server
/$$@. It is available wit II% K.$ and it is more powerful compared to II% C.$ because it supports
6ttp, ,C7 and named pipes were II% C.$ supports only 6ttp. It can be installed and configured
separately.
6osting WCF in 0ctivation service takes many advantages suc as process recycling, isolation, idle
time management and common configuration system. W0% osted service can be created using
following steps
.. +nable WCF for non-ttp protocols
/. Create W0% osted service
#. +nable different binding to te osted service
'nable WCF for non-http protocols
-efore %tart creating te service we need to configure te system to support W0%. Following are
te step to configure W0%.
.. Click %tart -L Control 7anel -L programs and Features and click J,urn Windows
Components )n or )ffJ in left pane.
/. +5pand J'icrosoft ."et Framework #.$J and enable MWindows Communication Foundation
6,,7 0ctivationM and MWindows Communication Foundation "on- 6,,7 0ctivationM.
#. "e5t we need to add -inding to te :efault Web site. 0s an e5ample, we will bind te
default web site to te ,C7 protocol. Ho to te %tart menu -L 7rograms -L0ccessories. &igt
click on te MCommand 7romptM item, and select M&un as administratorM from te conte5t
menu.
3. +5ecute te following command
N. C>OWindowsOsystem#/OinetsrvL appcmd.e5e set site M:efault Web %iteM -*bindings.
8protocolIJnet.tcpJ,
bindingInformationIJ@$@>EJ9
,at command adds te net.tcp site binding to te default web site by modifying te
application6ost.config file located in te MC:&'indows&system()&inetsrv&configM directory.
%imilarly we can add different protocols to te :efault Web site.
Create WA! hosted service
!tep 1* "e5t we are going to create te service, )pen te 4isual %tudio /$$@ and click "ew-
LWeb%ite and select WCF %ervice from te template and ;ocation as 6,,7 as sown below.

!tep "* Create te Contract by creating interface I'at%ervice and add %erviceContract attribute to
te interface and add )perationContract attribute to te metod declaration.
I-ath!ervice.cs
using System0
using System.Collections.'eneric0
using System.6inE0
using System.7untime.SerialiFation0
using System.ServiceModel0
using System.)e+t0
:ServiceContract;
public interface $MathService
<
:5perationContract;
int 3dd.int numG2 int numH/0
:5perationContract;
int Subtract.int numG2 int numH/0
=
!tep 5* Implementation of te I'at%ervice interface is sown below.
-ath!ervice.cs
using System0
using System.Collections.'eneric0
using System.6inE0
using System.7untime.SerialiFation0
using System.ServiceModel0
using System.)e+t0
public class MathService : $MathService
<
public int 3dd.int numG2 int numH/
<
return numG 9 numH0
=
public int Subtract.int numG2 int numH/
<
return numG D numH0
=
=
!tep 6* %ervice file is sown below.
-ath!ervice.svc
<?@ Service&ost 6anguage="C>" *ebug="true" Service="MathService"
CodeBehind="A3ppBCodeMathService.cs" ?>
!tep 2* In web.Config file, create end point wit Jnet,cp-indingJ binding and service metadata will
be publised using 'etadata +5cange point. %o create te 'etada +5cange end point wit
address as Jme5J and binding as Jme5,cp-indingJ. Witout publising te service 'etadata we
cannot create te pro5y using net.tcp address (e.g svcutil.e5e
net.tcp>??localost?W0%6osted%ervice?'at%ervice.svc )
Web.Config
<system.serviceModel>
<services>
<service name="MathService" behaviorConfiguration="ServiceBehavior">
<CDD Service (ndpoints DD>
<endpoint binding="net)cpBinding"
contract="$MathService" >
<endpoint>
<endpoint address="me+"
binding="me+)cpBinding" contract="$Metadata(+change">
<service>
<services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<CDD )o avoid disclosing metadata information2 set the value belo%
to false and remove the metadata endpoint above before deployment DD>
<serviceMetadata http'et(nabled="true">
<CDD )o receive e+ception details in
faults for debugging purposes2 set the value belo% to true.
Set to false before deployment to avoid disclosing
e+ception information DD>
<service*ebug include(+ception*etail$n,aults="false">
<behavior>
<serviceBehaviors><behaviors>
<system.serviceModel>
'nable different binding to the hosted service
.. Ho to te %tart menu -L 7rograms -L0ccessories. &igt click on te MCommand 7romptM
item, and select M&un as administratorM from te conte5t menu.
/. +5ecute te following command C:&'indows&system()&inetsrv*appcmd set app +,efault
'eb Site/'-SHostedServcie+ /enabled.rotocols:http/net.tcp
)utput will be sown below.

!tep 4* "ow te service is ready to use. "e5t we can create te pro5y class using service uttility
and add te pro5y class to te client application. Creat te pro5y class using 4isual %tudio
Command prompt and e5ecute te command
svcutil.exe net.tcp://localhost/'-SHostedService/MathService.svc
7ro5y and configuration file are generated in te corresponding location.

!tep 4* Create te client application as sown below and add te reference JSystem.ServiceModelJ,
tis is te core dll for WCF.

!tep $* 0dd te pro5y class and configuration file to te client application. Create te obGect for te
'at%erviceClient and call te metod.
(rogram.cs
class 8rogram
<
static void Main.string:; args/
<
MathServiceClient client = ne% MathServiceClient./0
Console.4rite6ine."Sum of t%o number I2J"/0
Console.4rite6ine.client.3dd.I2J//0
Console.7ead6ine./0
=
=
,e output will be sown as below.

%o tis tutorial clearly e5plains about te osting te WCF in Windows 0ctivation %ervice. %o ne5t
we can see ow to ost te service using Windows %ervice
Windows !ervice ,osting
In tis tutorial we are going to see te osting WCF service in Windows service. We will use same
set of code used for osting te WCF service in Console application to tis. ,is is same as osting
te service in II% witout message activated. ,ere is some advantage of osting service in
Windows service.
,e service will be osted, wen system starts
7rocess life time of te service can be controlled by %ervice Control 'anager for windows
service
0ll versions of Windows will support osting WCF service.
!tep 1* "ow let start create te WCF service, )pen te 4isual %tudio /$$@ and click "ew-L7roGect
and select Class ;ibrary from te template.

!tep "* 0dd reference System.ServiceModel to te proGect. ,is is te core assembly used for
creating te WCF service.
!tep 5* "e5t we can create te 0SimpleCalulator interface as sown below. 0dd te %ervice and
)peration Contract attribute as sown below.
I!impleCalculator.cs
using System0
using System.Collections.'eneric0
using System.6inE0
using System.)e+t0
using System.ServiceModel0
namespace 4indo%sService&ostedContract
<
:ServiceContract;
public interface $SimpleCalculator
<
:5perationContract;
int 3dd.int numG2 int numH/0
:5perationContract;
int Subtract.int numG2 int numH/0
:5perationContract;
int Multiply.int numG2int numH/0
:5perationContract;
double *ivide.int numG2 int numH/0
=
=
!tep 6* Implement te 0SimpleCalculator interface as sown below.
!impleCalulator.cs
using System0
using System.Collections.'eneric0
using System.6inE0
using System.)e+t0
namespace 4indo%sService&ostedService
<
class SimpleCalculator
: $SimpleCalculator
<

public int 3dd.int numG2 int numH/
<
return numG9numH0
=
public int Subtract.int numG2 int numH/
<
return numGDnumH0
=
public int Multiply.int numG2 int numH/
<
return numGKnumH0
=
public double *ivide.int numG2 int numH/
<
if .numH C= "/
return numG numH0
else
return "0
=
=
=
!tep 2* -uild te 7roGect and get te dll. "ow we are ready wit WCF service, now we are going to
see ow to ost te WCF %ervice in Windows service. +ote* In tis proGect, I ave mention tat we
are creating bot Contract and %ervice(implementation) are in same proGect. It is always good
practice if you ave bot in different proGect.
!tep 4* )pen 4isual %tudio /$$@ and Click "ew-L7roGect and select Windows %ervice.

!tep 7* 0dd te J'indowsServiceHostedService.dllJ as reference to te proGect. ,is assembly will
going to act as service.

!tep $* )n%tart metod of te service, we can write te osting code for WCF. We ave to make
sure tat we are using only one service ost obGect. )n stop metod you need to close te %ervice
6ost. Following code sow ow to ost WCF service in Windows service.
WCF,ostedWindows!ervice.cs
using System0
using System.Collections.'eneric0
using System.ComponentModel0
using System.*ata0
using System.*iagnostics0
using System.6inE0
using System.Service8rocess0
using System.)e+t0
using System.ServiceModel0
using System.ServiceModel.*escription0
namespace 4C,&osted4indo%sService
<
partial class 4C,&osted4indo%sService : ServiceBase
<
Service&ost mB&ost0

public 4C,&osted4indo%sService./
<
$nitialiFeComponent./0
=
protected override void 5nStart.string:; args/
<
if .mB&ost C= null/
<
mB&ost.Close./0
=
Create a -7$ to serve as the base address
-ri http-rl = ne%
-ri."http:localhost:!"#"MyServiceSimpleCalculator"/0
Create Service&ost
mB&ost = ne% Service&ost
.typeof.4indo%sService&ostedService.SimpleCalculator/2 http-rl/0
3dd a service endpoint
mB&ost.3ddService(ndpoint
.typeof.4indo%sService&ostedService.$SimpleCalculator/2 ne%
4S&ttpBinding./2 ""/0
(nable metadata e+change
ServiceMetadataBehavior smb = ne% ServiceMetadataBehavior./0
smb.&ttp'et(nabled = true0
mB&ost.*escription.Behaviors.3dd.smb/0
Start the Service
mB&ost.5pen./0
=
protected override void 5nStop./
<
if .mB&ost C= null/
<
mB&ost.Close./0
mB&ost = null0
=
=
static void Main./
<
ServiceBase:; Services)o7un0
Services)o7un = ne% ServiceBase:;
<
ne% 4C,&osted4indo%sService./
=0
ServiceBase.7un.Services)o7un/0
=
=
=
!tep 8* In order to install te service we need to ave te Installer class for te Windows service. %o
add new Installer class to te proGect, wic is inerited from te 0nstaller class. 7lease find te
below code for mentioning te %ervice name, %tart=p type etc of te service.
!erviceInstaller.cs
using System0
using System.Collections.'eneric0
using System.)e+t0
using System.Service8rocess0
using System.Configuration.$nstall0
using System.ComponentModel0
using System.Configuration0
namespace 4C,&osted4indo%sService
<
:7un$nstaller.true/;
public class 4inService$nstaller : $nstaller
<
private Service8rocess$nstaller process0
private Service$nstaller service0
public 4inService$nstaller./
<
process = ne% Service8rocess$nstaller./0
process.3ccount = Service3ccount.Let%orMService0
service = ne% Service$nstaller./0
service.ServiceLame = "4C,&osted4indo%sService"0
service.*isplayLame = "4C,&osted4indo%sService"0
service.*escription = "4C, Service &osted"0
service.Start)ype = ServiceStartMode.3utomatic0
$nstallers.3dd.process/0
$nstallers.3dd.service/0
=
=
=
!tep 1#* -uild te proGect, we will get te 'C1Hosted'indowsService.exe. "e5t we need to install
te service using 4isual %tudio Command 7rompt. %o open te command prompt by clicking %tart-
L0ll 7rograms-L 'icrosoft 4isual %tudio /$$@-L 4isual %tudio ,ools-L 4isual %tudio Command
7rompt =sing installutil utility application, you can install te service as sown below.
!tep 11* "ow service is 6osted sucessfully and we can create te pro5y class for te service and
start using in te client applcaiton.
)inding
-inding will describes ow client will communicate wit service. ,ere are different protocols
available for te WCF to communicate to te Client. Bou can mention te protocol type based on
your re2uirements.
-inding as several caracteristics, including te following>
Transport
:efines te base protocol to be used like 6,,7, "amed 7ipes, ,C7, and '%'( are some
type of protocols.
'ncoding A;ptionalB
,ree types of encoding are available-,e5t, -inary, or 'essage ,ransmission )ptimi<ation
'ecanism (',)'). ',)' is an interoperable message format tat allows te effective
transmission of attacments or large messages (greater tan C3D).
(rotocolA;ptionalB
:efines information to be used in te binding suc as %ecurity, transaction or reliable
messaging capability
)indings and Channel !tac/s
In WCF all te communication details are andled by cannel, it is a stack of cannel components
tat all messages pass troug during runtime processing. ,e bottom-most component is te
transport cannel. ,is implements te given transport protocol and reads incoming messages off
te wire. ,e transport cannel uses a message encoder to read te incoming bytes into a logical
'essage obGect for furter processing.
Figure .> -indings and Cannel %tacks (draw new diagram)
0fter tat, te message bubbles up troug te rest of te cannel stack, giving eac protocol
cannel an opportunity to do its processing, until it eventually reaces te top and WCF dispatces
te final message to your service implementation. 'essages undergo significant transformation
along te way.
It is very difficult for te developer to work directly wit cannel stack arcitecture. -ecause you
ave to be very careful wile ordering te cannel stack components, and weter or not tey are
compatible wit one oter.
%o WCF provides easy way of acieving tis using end point. In end point we will specify address,
binding and contract. ,o know more about end point. Windows Communication Foundation follows
te instructions outlined by te binding description to create eac cannel stack. ,e binding binds
your service implementation to te wire troug te cannel stack in te middle.
,ypes of -inding
;et us see more detailed on predefined binding
)asic,ttp)inding
It is suitable for communicating wit 0%7."+, Web services (0%'1)-based services tat
comfort wit W%--asic 7rofile conformant Web services.
,is binding uses 6,,7 as te transport and te5t?1'; as te default message encoding.
%ecurity is disabled by default
,is binding does not support W%-E functionalities like W%- 0ddressing, W%-%ecurity, W%-
&eliable'essaging
It is fairly weak on interoperability.
W!,ttp)inding
:efines a secure, reliable, interoperable binding suitable for non-duple5 service contracts.
It offers lot more functionality in te area of interoperability.
It supports W%-E functionality and distributed transactions wit reliable and secure sessions
using %)07 security.
It uses 6,,7 and 6,,7% transport for communication.
&eliable sessions are disabled by default.
W!Dual,ttp)inding
,is binding is same as tat of W%6ttp-inding, e5cept it supports duple5 service. :uple5 service is
a service wic uses duple5 message pattern, wic allows service to communicate wit client via
callback.
In W%:ual6ttp-inding reliable sessions are enabled by default. It also supports communication via
%)07 intermediaries.
W!Federation,ttp)inding
,is binding support federated security. It elps implementing federation wic is te ability to
flow and sare identities across multiple enterprises or trust domains for autentication and
autori<ation. It supports W%-Federation protocol.
+etTcp)inding
,is binding provides secure and reliable binding environment for ."et to ."et cross macine
communication. -y default it creates communication stack using W%-&eliable'essaging protocol
for reliability, ,C7 for message delivery and windows security for message and autentication at
run time. It uses ,C7 protocol and provides support for security, transaction and reliability.
+et+amed(ipe)inding
,is binding provides secure and reliable binding environment for on-macine cross process
communication. It uses "amed7ipe protocol and provides full support for %)07 security,
transaction and reliability. -y default it creates communication stack wit W%-&eliable'essaging
for reliability, transport security for transfer security, named pipes for message delivery and binary
encoding.
+et-smC)inding
,is binding provides secure and reliable 2ueued communication for cross-macine
environment.
(ueuing is provided by using '%'( as transport.
It enables for disconnected operations, failure isolation and load leveling
+et(eerTcp)inding
,is binding provides secure binding for peer-to-peer environment and network
applications.
It uses ,C7 protocol for communication
It provides full support for %)07 security, transaction and reliability.
)inding configuration
-inding can be configured eiter troug configuration file or 7rogramming. ;et us see te binding
representation in eac metod.
Administrative AConfiguration fileB*
In te configuration file of te osting application, you can add te PbindingsL element inside te
Psystem.service'odelL element and add te properties to particular binding type. 7roperties
corresponding to te particular binding type can be mentioned below. "ame of te binding
properties tat you are going to use as to be mention in te end point.
<system.serviceModel>
<services>
<service name="MyService">
<endpoint address="http:localhost$$S&ostedServiceMyService.svc"
binding="%s&ttpBinding" bindingLame="%shttpbind" contract="$MyService">
<identity>
<dns value="localhost">
<identity>
<endpoint>
<endpoint address="me+" binding="me+&ttpBinding"
contract="$Metadata(+change">
<service>
<services>
<bindings>
<%s&ttpBinding>
<binding name="%shttpbind" allo%CooMies="true" close)imeout=""":"G:"""
receive)imeout=""":"G:""" >
<%s&ttpBinding>
<bindings>
<system.serviceModel>
(rogramming -odel*
In te following code, I ave created te 'SHttp%inding obGect and assign te properties wic to
be configured. ,is binding obGect is added to te %ervice endpoint for client communication.
%imilarly you can also create any type of binding and add to endpoint.
Create a -7$ to serve as the base address
-ri http-rl = ne%
-ri."http:localhost:!"#"MyServiceSimpleCalculator"/0
Create Service&ost
Service&ost host =
ne% Service&ost.typeof.MyCalculatorService.SimpleCalculator/2
http-rl/0
Create Binding to add to end point
4S&ttpBinding %shttpbind = ne% 4S&ttpBinding./0
%shttpbind.3llo%CooMies = true0
%shttpbind.Close)imeout = ne% )imeSpan."2 G2 "/0
%shttpbind.7eceive)imeout = ne% )imeSpan."2 G2 "/0
3dd a service endpoint
host.3ddService(ndpoint
.typeof.MyCalculatorService.$SimpleCalculator/2 %shttpbind2 ""/0
(nable metadata e+change
ServiceMetadataBehavior smb = ne% ServiceMetadataBehavior./0
smb.&ttp'et(nabled = true0
host.*escription.Behaviors.3dd.smb/0
Start the Service
host.5pen./0
Console.4rite6ine."Service is host at " 9 *ate)ime.Lo%.)oString.//0
Console.4rite6ine."&ost is running... 8ress Mey to stop"/0
Console.7ead6ine./0
+ote* It is always good if you configure te binding properties using configuration file, because
wile moving to te production you no need to cange in te code and recompile it. It is always
good practice to represent in te configuration file.
-etadata '%change
WCF provides ric infrastructure for +5porting, 7ublising, retrieving and Importing te metadata.
WCF uses te 'etadata to describe ow to interact wit te service endpoint. =sing te metadata,
client will create te pro5y class for te service using SvcUtil.exe
'%porting !ervice -etadata
It is te process of describing te service endpoint so tat client can understand ow to use te
service.
(ublishing !ervice -etadata
It is te process publising metadata. It involves converting C;& type and binding information into
W%:; or some oter low level representation.
.etrieving !ervice -etadata
It is te process of retrieving te metadata. It uses W%-'etadata+5cage or 6,,7 protocol for
retrieving te metadata. Importing %ervice 'etadata - It is te process of generating te abstract
representation of te service using metadata.
"ow we are going to focus mainly on publising metadata. ,ere are two way to publis metadata,
eiter we can use 6,,7-H+, or troug message e5cange endpoint. -y default service metadata
is turn-off due to security reason. WCF metadata infrastructure resides in
System.ServiceModel.,escription namespace. %ervice metadata can be used for following purpose
0utomatically generating te client for consuming service
Implementing te service description
=pdating te binding for a client
"ow let us understand te publising te metadata using 6,,7-H+, metod.
,TT(DE'T 'nabled -etadata
We will use %ervice-eaviour to publis te metadata using 6,,7-H+,. ,is can be configures
eiter administratively or 7rogrammatically. 6ttp and 6ttps can e5pose by appending MFwsdlM to te
end of te service address. For e5ample service address is
http://localhost:"!"!/MyCalulatorService , 6,,7-Het metadata address is given by
http://localhost:"!"!/MyCalulatorService#wsdl.
Administrative AConfiguration fileB*
In te below mention configuration information, you can find te beavior section in te
%ervice-eavior. Bou can e5pose te metadata using %ervice'etadata node wit
ttpHet+nableIJ,rueJ.
<system.serviceModel>
<services>
<service behaviorConfiguration="ServiceBehavior" name="MyService">
<endpoint address="http:localhost$$S&ostedServiceMyService.svc"
binding="%s&ttpBinding" contract="$MyService">
<identity>
<dns value="localhost">
<identity>
<endpoint>
<service>
<services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<CDSetting http'et(nabled you can publish the metadata DD>
<serviceMetadata http'et(nabled="true">
<behavior>
<serviceBehaviors>
<behaviors>
<system.serviceModel>
(rogarmming -odel*
=sing %ervice'etadata-eavior you can enable te metadata e5cange. In te following code, I
ave created te %ervice'etadata-eavior obGect and assigned 6ttpHet+nabled property to true.
,en you ave to add te beavior to ost description as sown. ,is set of code will publis te
metadata using 6,,7-H+,.
Create a -7$ to serve as the base address
-ri http-rl = ne%
-ri."http:localhost:!"#"MyServiceSimpleCalculator"/0
Create Service&ost
Service&ost host = ne%
Service&ost.typeof.MyCalculatorService.SimpleCalculator/2 http-rl/0
3dd a service endpoint
host.3ddService(ndpoint
.typeof.MyCalculatorService.$SimpleCalculator/2 ne% 4S&ttpBinding./2
""/0
(nable metadata e+change
ServiceMetadataBehavior smb = ne% ServiceMetadataBehavior./0
(nable metadata e+change using &))8D'()
smb.&ttp'et(nabled = true0
host.*escription.Behaviors.3dd.smb/0
Start the Service
host.5pen./0
Console.4rite6ine."Service is host at " 9 *ate)ime.Lo%.)oString.//0
Console.4rite6ine."&ost is running... 8ress Mey to stop"/0
Console.7ead6ine./0
-etadata '%change 'ndpoint
+5posing te metadata using 6,,7-H+, as a disadvantage, suc tat tere is no guarantee tat
oter platforms you interact will support it. ,ere is oter way of e5posing te using special
endpoint is called as 'etadata +5cange +ndpoint. Bou can ave as many metadata e5cange
endpoints as you want.
Address
It is basically =ri to identify te metadata. Bou can specify as address in te endpoint but append
wit Mme5M keyword. For e5ample Mttp>??localost>A$A$?'yCalulator%ervice?me5M
)inding
,ere are four types of bindings supported for metadata e5cange. ,ey are me56ttp-inding,
me56ttps-inding, me5"amed7ipes-inding, me5,cp-inding.
Contract
I'etadata+5cange is te contract used for '+1 endpoint. WCF service ost automatically
provides te implementation for tis I'etadata+5cange wile osting te service.
Bou can create te 'etadata +5cange +ndpoint eiter 0dministrative (configuration file) or
programmatically.
Administrative AConfiguration fileB*
In te configuration file of te osting application, you can add metadata e5cange endpoint as
sown below.
<system.serviceModel>
<services>
<service name="MyService">
<endpoint address="http:localhost$$S&ostedServiceMyService.svc"
binding="%s&ttpBinding" contract="$MyService">
<identity>
<dns value="localhost">
<identity>
<endpoint>
<endpoint address="me+" binding="me+&ttpBinding"
contract="$Metadata(+change">
<service>
<services>
<system.serviceModel>
(rogramming -odel*
In te following code I ave mention about creating te 'etadata +5cange +ndpoint troug
coding. %teps to create te metadata endpoint are
Create te ServiceMetadata%ehavior obGect and add to %ervice ost description.
ServiceMetadataBehavior smb = ne% ServiceMetadataBehavior./0
host.*escription.Behaviors.3dd.smb/0
Create te metadata binding obGect using Metadata2xchange%inding
Binding me+Binding = Metadata(+changeBindings.CreateMe+&ttpBinding ./0
#. 0dd te endpoint to te service ost wit address, binding and contract.
host.3ddService(ndpoint.typeof.$Metadata(+change/2 me+Binding2 "me+"/0
Complete code for osting te service wit metadata e5cange endpoint is sown below.
Create a -7$ to serve as the base address
-ri http-rl = ne%
-ri."http:localhost:!"#"MyServiceSimpleCalculator"/0
Create Service&ost
Service&ost host = ne%
Service&ost.typeof.MyCalculatorService.SimpleCalculator/2 http-rl/0
3dd a service endpoint
host.3ddService(ndpoint
.typeof.MyCalculatorService.$SimpleCalculator/2 ne% 4S&ttpBinding./2
""/0
(nable metadata e+change
ServiceMetadataBehavior smb = ne% ServiceMetadataBehavior./0
host.*escription.Behaviors.3dd.smb/0
Binding me+Binding = Metadata(+changeBindings.CreateMe+&ttpBinding
./0
3dding metadata e+change endpoint
host.3ddService(ndpoint.typeof.$Metadata(+change/2 me+Binding2
"me+"/0
Start the Service
host.5pen./0
Console.4rite6ine."Service is host at " 9 *ate)ime.Lo%.)oString.//0
Console.4rite6ine."&ost is running... 8ress Mey to stop"/0
Console.7ead6ine./0
Contracts
Windows Communication Foundation (WCF, formerly known as Indigo) is built upon te
foundation of web services messaging and related standards, wile at te same time makes it
possible to seriali<e messages in a more compact binary format, or in a more proprietary way. %till,
te core message can always be represented in 1';, terefore be considered compatible wit any
platform tat understands 1';, and agrees on te contract tat defines said messaging between
systems.
,e contract is a platform-neutral and standard way of describing wat te service does. WCF
defines four types of contracts>
%ervice Contract
:ata Contract
'essage Contract
Fault Contract
!ervice Contract
%ervice contract describes te operation tat service provide. 0 %ervice can ave more tan one
service contract but it sould ave at least one %ervice contract.
%ervice Contract can be define using 8%erviceContract9 and 8)perationContract9 attribute.
8%erviceContract9 attribute is similar to te 8Web%ervcie9 attribute in te Web%ervice and
8)peartionContract9 is similar to te 8Web'etod9 in Web%ervice.
It describes te client-callable operations (functions) e5posed by te service
It maps te interface and metods of your service to a platform-independent description
It describes message e5cange patterns tat te service can ave wit anoter party. %ome
service operations migt be one-way! oters migt re2uire a re2uest-reply pattern
It is analogous to te element in W%:;
,o create a service contract you define an interface wit related metods representative of a
collection of service operations, and ten decorate te interface wit te ServiceContract 0ttribute
to indicate it is a service contract. 'etods in te interface tat sould be included in te service
contract are decorated wit te 3perationContract 0ttribute.
:ServiceContract./;
public interface $SimpleCalculator
<
:5perationContract./;
int 3dd.int numG2 int numH/0
=
)nce we define %ervice contract in te interface, we can create implement class for tis interface.
public class SimpleCalculator : $SimpleCalculator
<

public int 3dd.int numG2 int numH/
<
return numG 9 numH0
=
=
Wit out creating te interface, we can also directly created te service by placing Contract in te
implemented class. -ut it is not good practice of creating te service
:ServiceContract./;
public class SimpleCalculator
<
:5perationContract./;
public int 3dd.int numG2 int numH/
<
return numG 9 numH0
=
=
"ow you ave some fundamental idea on %ervice contract. "e5t we will look into :ata Contract.
Data Contract
0 data contract is a formal agreement between a service and a client tat abstractly describes te
data to be e5canged.
:ata contract can be e5plicit or implicit. %imple type suc as int, string etc as an implicit data
contract. =ser defined obGect are e5plicit or Comple5 type, for wic you ave to define a :ata
contract using 8:ataContract9 and 8:ata'ember9 attribute.
0 data contract can be defined as follows>
It describes te e5ternal format of data passed to and from service operations
It defines te structure and types of data e5canged in service messages
It maps a C;& type to an 1'; %cema
t defines ow data types are seriali<ed and deseriali<ed. ,roug seriali<ation, you convert
an obGect into a se2uence of bytes tat can be transmitted over a network. ,roug
deseriali<ation, you reassemble an obGect from a se2uence of bytes tat you receive from a
calling application.
It is a versioning system tat allows you to manage canges to structured data
We need to include System.4untime.Seriali5ation reference to te proGect. ,is assembly olds te
,ataContract and ,ataMember attribute.
Create user defined data type called +mployee. ,is data type sould be identified for seriali<ation
and deseriali<ation by mentioning wit 8:ataContract9 and 8:ata'ember9 attribute.
:ServiceContract;
public interface $(mployeeService
<
:5perationContract;
(mployee 'et(mployee*etails.int (mp$d/0
=
:*ataContract;
public class (mployee
<
private string mBLame0
private int mB3ge0
private int mBSalary0
private string mB*esignation0
private string mBManager0
:*ataMember;
public string Lame
<
get < return mBLame0 =
set < mBLame = value0 =
=
:*ataMember;
public int 3ge
<
get < return mB3ge0 =
set < mB3ge = value0 =
=
:*ataMember;
public int Salary
<
get < return mBSalary0 =
set < mBSalary = value0 =
=
:*ataMember;
public string *esignation
<
get < return mB*esignation0 =
set < mB*esignation = value0 =
=
:*ataMember;
public string Manager
<
get < return mBManager0 =
set < mBManager = value0 =
=
=
Implementation of te service class is sown below. In Het+mployee metod we ave created te
+mployee instance and return to te client. %ince we ave created te data contract for te
+mployee class, client will aware of tis instance wenever e creates pro5y for te service.
public class (mployeeService : $(mployeeService
<
public (mployee 'et(mployee*etails.int emp$d/
<

(mployee emp*etail = ne% (mployee./0
*o something to get employee details and assign to Nemp*etailN
properties
return emp*etail0
=
=
Client side
)n client side we can create te pro5y for te service and make use of it. ,e client side code is
sown below.
protected void btn'et*etailsBClicM.ob1ect sender2 (vent3rgs e/
<
(mployeeServiceClient ob1(mployeeClient = ne%
(mployeeServiceClient./0
(mployee emp*etails0
emp*etails = ob1(mployeeClient.'et(mployee*etails.emp$d/0
*o something on employee details
=
-essage Contract
-essage
'essage is te packet of data wic contains important information. WCF uses tese messages to
transfer information from %ource to destination.
WCF uses %)07(%imple )bGect 0ccess 7rotocol) 'essage format for communication. %)07
message contain +nvelope, 6eader and -ody.%)07 envelope contails name, namespace,eader and
body element. %)07 6ear contain important information wic are not directly related to message.
%)07 body contains information wic is used by te target.
:iagram %oap envelope
-essage (attern
It describes ow te programs will e5cange message eac oter. ,ere are tree way of
communication between source and destination
.. !imple% - It is one way communication. %ource will send message to target, but target will
not respond to te message.
/. .eCuest3.epla& - It is two way communications, wen source send message to te target, it
will resend response message to te source. -ut at a time only one can send a message
#. Duple% - It is two way communication, bot source and target can send and receive message
simultaniouly.
What is -essage contractF
0s I said earlier, WCF uses %)07 message for communication. 'ost of te time developer will
concentrate more on developing te :ataContract, %eriali<ing te data, etc. WCF will automatically
take care of message. )n %ome critical issue, developer will also re2uire control over te %)07
message format. In tat case WCF provides 'essage Contract to customi<e te message as per
re2uirement.
WCF supports eiter &7C(&emote 7rocedure Call) or 'essage style operation model. In te &7C
model, you can develop operation wit &ef and out parameter. WCF will automatically create te
message for operation at run time. In 'essage style operation WCF allows to customi<e te
message eader and define te security for eader and body of te message.
Defining -essage Contract
'essage contract can be applied to type using 'essageContract attribute. Custom 6eader and -ody
can be included to message using J'essage6eaderJ and JMessage%odyMemberJatttribute. ;et us see
te sample message contract definition.
:MessageContract;
public class (mployee*etails
<
:Message&eader;
public string (mp$*0
:MessageBodyMember;
public string Lame0
:MessageBodyMember;
public string *esignation0
:MessageBodyMember;
public int Salary0
:MessageBodyMember;
public string 6ocation0
=
Wen I use tis +mployee:eatils type in te service operation as parameter. WCF will add e5tra
eader call J+mpI:J to te %)07 envelope. It also add "ame, :esignation, %alary, ;ocation as e5tra
member to te %)07 -ody.
.ules *
Bou ave to follow certain rules wile working wit 'essage contract
.. Wen using 'essage contract type as parameter, )nly one parameter can be used in servicie
)peration
:5perationContract;
void Save(mployee*etails.(mployee*etails emp/0
/. %ervice operation eiter sould return 'essagecontract type or it sould not return any value
:5perationContract;
(mployee*etails 'et(mployee*etails./0
#. %ervice operation will accept and return only message contract type. )ter data types are not
allowed.
:5perationContract;
(mployee*etails Modify(mployee*etails.(mployee*etails emp/0

+ote* If a type as bot 'essage and :ata contract, service operation will accept only message
contract.
-essage,eaderArra& Attribute
Consider te 'essage contract type definition as sown below.

:MessageContract;
public class *epartment
<
:Message&eader;
public string *epartment$*0
:Message&eader;
public string *epartmentLame0
:Message&eader;
public (mployees (mployee./0
=
In tis we are aving array of +mployee type as message eader. Wen tis converted to %)07
6eader it looks as sown below.
<*epartment>
<*epartment$*>875GHOP<*epartment$*>
<*epartmentLame>8roduction<*epartmentLame>
<(mployees>
<(mployee>Sam<(mployee>
<(mployee>7am<(mployee>
<(mployee>7a1a<(mployee>
<(mployees>
<*epartment>
%uppose you want to sow te all employee detail in same level. We can use 'essage6eader0rray
attribute wic will seriali<e te array element independently. If you use te 'essage6eader0rray
attribute of +mployees, %)07 message will look as sown below.
<*epartment>
<*epartment$*>875GHOP<*epartment$*>
<*epartmentLame>8roduction<*epartmentLame>
<(mployee>Sam<(mployee>
<(mployee>7am<(mployee>
<(mployee>7a1a<(mployee>
<*epartment>
+ote* 'essage6eader0rray 0ttribute is applicable only for 0rray, not for collection.
-essage Contract (roperties
(rotection=evel
Bou can mention te MessageHeader or Message%odyMember to be signed or +ncrypted using
.rotection6evel property.
'%ample

using System.Let.Security0
:MessageContract;
public class (mployee*etails
<
:Message&eader.8rotection6evel=8rotection6evel.Lone/;
public string (mp$*0
:MessageBodyMember.8rotection6evel = 8rotection6evel.Sign /;
public string Lame0
:MessageBodyMember.8rotection6evel = 8rotection6evel.Sign /;
public string *esignation0
:MessageBodyMember.8rotection6evel=8rotection6evel.(ncrypt3ndSign/;
public int Salary0
=
In te above type definition, we ave made te different protection level for body. -ut te
protection level of te body is determind by te igest .rotection6evel property. -y default if you
are not specifying te protection level it takes J+ncrypt0nd%ignJ. %o it good if you specify minimum
7rotection;evel re2uired.
+ame and +amespace*
%)07 representation of te message element can be cange by mentioning "ame and "amespace
property of te 6eader and -ody member. -y default namespace is te same as te namespace of
te service contract tat te message is participating. In te below e5ample, I ave mention te
"ame property to te +mpI: and "ame.

:MessageContract;
public class (mployee*etails
<
:Message&eader.Lame="$*"/;
public string (mp$*0
:MessageBodyMember.Lame="(mployeeLame"/;
public string Lame0
:MessageBodyMember./;
public string *esignation0
:MessageBodyMember./;
public int Salary0
=
Wen %)07 message representation, its name is canged to I: and +mployee"ame.

<(mployee*etails>
<$*>OIJPO<$*>
<(mployeeLame>Sam<(mployeeLame>
<*esignation>Soft%are (ngineer<*esignation>
<Salary>HI"""<Salary>
<(mployee*etails>
;rder
,e order of te body elements are alpeabetical by default. -ut you can control te order, usiing
3rder property in te Message%ody attribute.

:MessageContract;
public class (mployee*etails
<
:Message&eader./;
public string (mp$*0
:MessageBodyMember.5rder=H/;
public string Lame0
:MessageBodyMember.5rder=P/;
public string *esignation0
:MessageBodyMember.5rder=G/;
public int Salary0
=
Fault Contract
%ervice tat we develop migt get error in come case. ,is error sould be reported to te client in
proper manner. -asically wen we develop managed application or service, we will andle te
e5ception using try- catc block. -ut tese e5ceptions andlings are tecnology specific.
In order to support interoperability and client will also be interested only, wat wents wrongF not on
ow and were cause te error.
-y default wen we trow any e5ception from service, it will not reac te client side. WCF
provides te option to andle and convey te error message to client from service using %)07 Fault
contract.
%uppose te service I consumed is not working in te client application. I want to know te real
cause of te problem. 6ow I can know te errorF For tis we are aving Fault Contract. Fault
Contract provides documented view for error accorded in te service to client. ,is elp as to easy
identity te wat error as accord. ;et us try to understand te concept using sample e5ample.
!tep 1* I ave created simple calculator service wit 0dd operation wic will trow general
e5ception as sown below
Service interface
:ServiceContract./;
public interface $SimpleCalculator
<
:5perationContract./;
int 3dd.int numG2 int numH/0
=
Service implementation
public class SimpleCalculator : $SimpleCalculator
<

public int 3dd.int numG2 int numH/
<
*o something
thro% ne% (+ception."(rror %hile adding number"/0

=
=
!tep "* )n client side code. +5ceptions are andled using try-Catc block. +ven toug I ave
capture te e5ception wen I run te application. I got te message tat e5ceptions are not andled
properly.
try
<
MyCalculatorService8ro+y.MyCalculatorService8ro+y pro+y
= ne% MyCalculatorService8ro+y.MyCalculatorService8ro+y./0
Console.4rite6ine."Client is running at " 9 *ate)ime.Lo%.)oString.//0
Console.4rite6ine."Sum of t%o numbers... I9I =" 9 pro+y.3dd.I2 I//0
Console.7ead6ine./0
=
catch .(+ception e+/
<
Console.4rite6ine.e+.Message/0
Console.7ead6ine./0
=
!tep 5* "ow if you want to send e5ception information form service to client, you ave to use
Fault+5ception as sown below.
public int 3dd.int numG2 int numH/
<
*o something
thro% ne% ,ault(+ception."(rror %hile adding number"/0

=
!tep 6* )utput window on te client side is sow below.
!tep 2* Bou can also create your own Custom type and send te error information to te client using
1aultContract. ,ese are te steps to be followed to create te fault contract.
:efine a type using te data contract and specify te fields you want to return.
:ecorate te service operation wit te FaultContract attribute and specify te type name.
&aise te e5ception from te service by creating an instance and assigning properties of te
custom e5ception.
!tep 4* :efining te type using :ata Contract
:*ataContract./;
public class Custom(+ception
<
:*ataMember./;
public string )itle0
:*ataMember./;
public string (+ceptionMessage0
:*ataMember./;
public string $nner(+ception0
:*ataMember./;
public string StacM)race0
=
!tep 7* :ecorate te service operation wit te 1aultContract
:ServiceContract./;
public interface $SimpleCalculator
<
:5perationContract./;
:,aultContract.typeof.Custom(+ception//;
int 3dd.int numG2 int numH/0
=
!tep $* &aise te e5ception from te service
public int 3dd.int numG2 int numH/
<
*o something
Custom(+ception e+ = ne% Custom(+ception./0
e+.)itle = "(rror ,untion:3dd./"0
e+.(+ceptionMessage = "(rror occur %hile doing add function."0
e+.$nner(+ception = "$nner e+ception message from serice"0
e+.StacM)race = "StacM )race message from service."0
thro% ne% ,ault(+ception.e+2"7eason: )esting the ,ault contract"/ 0

=
!tep 8* )n client side, you can capture te service e5ception and process te information, as sown
below.
try
<
MyCalculatorService8ro+y.MyCalculatorService8ro+y pro+y
= ne% MyCalculatorService8ro+y.MyCalculatorService8ro+y./0
Console.4rite6ine."Client is running at " 9 *ate)ime.Lo%.)oString.//0
Console.4rite6ine."Sum of t%o numbers... I9I =" 9 pro+y.3dd.I2 I//0
Console.7ead6ine./0
=
catch .,ault(+ception<MyCalculatorService.Custom(+ception> e+/
<
8rocess the (+ception
=
Instance -anagement
Instance management refers to te way a service andles a re2uest from a client. Instance
management is set of tecni2ues WCF uses to bind client re2uest to service instance, governing
wic service instance andles wic client re2uest. It is necessary because application will differ
in teir need for scalability, performance, durability, transaction and 2ueued calls.
-asically tere are tree instance modes in WCF>
7er-Call instance mode
7er-%ession instance mode
%ingleton Instance 'ode

Configuration*
Instance mode can be configured using Service%ehavior attribute. ,is can be specified at
implementing te service contract as sown below.
:ServiceContract./;
public interface $MyService
<
:5perationContract;
int MyMethod./0
=

:ServiceBehavior.$nstanceConte+tMode=$nstanceConte+tMode.Single/;
public class MyService:$MyService
<
public int MyMethod./
<
*o something
=
=
(er-Call !ervice
Wen WCF service is configured for 7er-Call instance mode, %ervice instance will be created for
eac client re2uest. ,is %ervice instance will be disposed after response is sent back to client.

Following diagram represent te process of andling te re2uest from client using 7er-Call instance
mode.
;et as understand te per-call instance mode using e5ample.
!tep 1* Create te service contract called I'y%ervice and implement te interface. 0dd service
beavior attribute to te service class and set te 0nstanceContextMode property to .erCall as sow
below.
:ServiceContract./;
public interface $MyService
<
:5perationContract;
int MyMethod./0
=
!tep "* In tis implementation of 'y'etod operation, increment te static variable(mQCounter).
+ac time wile making call to te service, mQCounter variable is incremented and return te value
to te client.
:ServiceBehavior.$nstanceConte+tMode=$nstanceConte+tMode.8erCall/;
public class MyService:$MyService
<
static int mBCounter = "0
public int MyMethod./
<
mBCounter990
return mBCounter0
=
=

!tep 5* Client side, create te pro5y for te service and call Mmy'etodM operation multiple time.
static void Main.string:; args/
<
Console.4rite6ine."Service $nstance mode: 8erDCall"/0
Console.4rite6ine."Client maMing call to service..."/0
Creating the pro+y on client side
MyCalculatorService8ro+y.MyService8ro+y pro+y =
ne% MyCalculatorService8ro+y.MyService8ro+y./0
Console.4rite6ine."Counter: " 9 pro+y.MyMethod.//0
Console.4rite6ine."Counter: " 9 pro+y.MyMethod.//0
Console.4rite6ine."Counter: " 9 pro+y.MyMethod.//0
Console.4rite6ine."Counter: " 9 pro+y.MyMethod.//0
Console.7ead6ine./0
=
%urprisingly, all re2uests to service return J.J, because we configured te Instance mode to 7er-Call.
%ervice instance will created for eac re2uest and value of static variable will be set to one. Wile
return back, service instance will be disposed. )utput is sown below.
Fig> 7ercall)utput.
(er-!ession !ervice
Wen WCF service is configured for 7er-%ession instance mode, logical session between client and
service will be maintained. Wen te client creates new pro5y to particular service instance, a
dedicated service instance will be provided to te client. It is independent of all oter instance.
Following diagram represent te process of andling te re2uest from client using 7er-%ession
instance mode.

;et as understand te 7er-%ession instance mode using e5ample.
!tep 1* Create te service contract called I'y%ervice and implement te interface. 0dd service
beavior attribute to te service class and set te 0nstanceContextMode property to .erSession as
sow below.
:ServiceContract./;
public interface $MyService
<
:5perationContract;
int MyMethod./0
=
!tep "* In tis implementation of 'y'etod operation, increment te static variable (mQCounter).
+ac time wile making call to te service, mQCounter variable will be incremented and return te
value to te client.
:ServiceBehavior.$nstanceConte+tMode=$nstanceConte+tMode.8erSession/;
public class MyService:$MyService
<
static int mBCounter = "0
public int MyMethod./
<
mBCounter990
return mBCounter0
=
=
!tep 5* Client side, create te pro5y for te service and call Mmy'etodM operation multiple time.
static void Main.string:; args/
<
Console.4rite6ine."Service $nstance mode: 8erDSession"/0
Console.4rite6ine."Client maMing call to service..."/0
Creating the pro+y on client side
MyCalculatorService8ro+y.MyService8ro+y pro+y =
ne% MyCalculatorService8ro+y.MyService8ro+y./0
Console.4rite6ine."Counter: " 9 pro+y.MyMethod.//0
Console.4rite6ine."Counter: " 9 pro+y.MyMethod.//0
Console.4rite6ine."Counter: " 9 pro+y.MyMethod.//0
Console.4rite6ine."Counter: " 9 pro+y.MyMethod.//0
Console.7ead6ine./0
=
0ll re2uest to service return incremented value (., /, #, 3), because we configured te instance
mode to 7er-%ession. %ervice instance will be created once te pro5y is created at client side. %o
eac time re2uest is made to te service, static variable is incremented. %o eac call to 'y'etod
return incremented value. )utput is sown below.
Fig> 7ersession)utput.
!ingleton !ervice
Wen WCF service is configured for %ingleton instance mode, all clients are independently
connected to te same single instance. ,is singleton instance will be created wen service is osted
and, it is disposed wen ost suts down.
Following diagram represent te process of andling te re2uest from client using %ingleton
instance mode.

;et as understand te %ingleton Instance mode using e5ample.
!tep 1* Create te service contract called I'y%ervice and implement te interface. 0dd service
beavior attribute to te service class and set te 0nstanceContextMode property to Single as sow
below.
:ServiceContract./;
public interface $MyService
<
:5perationContract;
int MyMethod./0
=
!tep "* In tis implementation of 'y'etod operation, increment te static variable(mQCounter).
+ac time wile making call to te service, mQCounter variable is incremented and return te value
to te client
:ServiceBehavior.$nstanceConte+tMode=$nstanceConte+tMode.Single/;
public class MyService:$MyService
<
static int mBCounter = "0
public int MyMethod./
<
mBCounter990
return mBCounter0
=
=
!tep 5* Client side, create te two pro5ies for te service and made a multiple call to 'y'etod.
static void Main.string:; args/
<
Console.4rite6ine."Service $nstance mode: Singleton"/0
Console.4rite6ine."Client G maMing call to service..."/0
Creating the pro+y on client side
MyCalculatorService8ro+y.MyService8ro+y pro+y =
ne% MyCalculatorService8ro+y.MyService8ro+y./0
Console.4rite6ine."Counter: " 9 pro+y.MyMethod.//0
Console.4rite6ine."Counter: " 9 pro+y.MyMethod.//0
Console.4rite6ine."Counter: " 9 pro+y.MyMethod.//0
Console.4rite6ine."Client H maMing call to service..."/0
Creating ne% pro+y to act as ne% client
MyCalculatorService8ro+y.MyService8ro+y pro+yH =
ne% MyCalculatorService8ro+y.MyService8ro+y./0
Console.4rite6ine."Counter: " 9 pro+yH.MyMethod.//0
Console.4rite6ine."Counter: " 9 pro+yH.MyMethod.//0
Console.7ead6ine./0
=

Wen two pro5y class made a re2uest to service, single instance at service will andle it and it
return incremented value (., /, #, 3), because instance mode is configured to J%ingleJ. %ervice
instance is created wen it is osted. %o tis instance will remain till ost is sutdown. )utput is
sown below.
Fig> %ingleton)utput.
Instance Deactivation
In Instance 'anagement %ystem tutorial, you learn ow to create sessionful service instance.
-asically service instance is osted in a conte5t. %ession actually correlated te client message not
to te instance, but to te conte5t tat ost it. Wen session starts, conte5t is created and wen it
closes, conte5t is terminated. WCF provides te option of separating te two lifetimes and
deactivating te instance separately from its conte5t.
4elease0nstanceMode property of te 3berational%ehavior attribute used to control te instance in
relation to te metod call.
Followings are te list &elease mode available in te 4elease0nstanceMode
.. &ealeaseInstance'ode."one
/. &ealeaseInstance'ode.-eforeCall
#. &ealeaseInstance'ode.0fterCall
3. &ealeaseInstance'ode.-efore0nd0fterCall
-elow code sow, ow to add te J&eleaseInstance'odeJ property to te operational beavior.
:ServiceContract./;
public interface $SimpleCalculator
<
:5perationContract./;
int 3dd.int numG2 int numH/0
=
:5perationBehavior.7elease$nstanceMode=7elease$nstanceMode.BeforeCall;
public int 3dd.int numG2 int numH/
<
return numG 9 numH0
=
.eleaseInstance-ode.+one
,is property means tat it will not affect te instance lifetime. -y default &eleaseInstance'ode
property is set to J"oneJ.
.eleaseInstance-ode.)eforeCall
,is property means tat it will create new instance before a call is made to te operation.
If te instance is already e5ist,WCF deactivates te instance and calls :ispose() before te call is
done. ,is is designed to optimi<e a metod suc as Create()
.eleaseInstance-ode.AfterCall
,is property means tat it will deactivate te instance after call is made to te metod.
,is is designed to optimi<e a metod suc a Cleanup()
.eleaseInstance-ode.)eforeAndAfterCall
,is is means tat it will create new instance of obGect before a call and deactivates te instance
after call. ,is as combined effect of using 4elease0nstanceMode.%eforeCall and
4elease0nstanceMode.-fterCall
'%plicit Deactivate
Bou can also e5plicitly deactivate instance using 0nstanceContext obGect as sown below.
:ServiceContract./;
public interface $MyService
<
:5perationContract;
void MyMethod./0
=

:ServiceBehavior.$nstanceConte+tMode=$nstanceConte+tMode.Single/;
public class MyService:$MyService
<
public void MyMethod./
<
*o something
5perationConte+t.Current.$nstanceConte+t.7eleaseService$nstance./0

=
=

Durable !ervice
:urable services are WCF services tat persist service state information even after service ost is
restarted or Client. It means tat durable services ave te capability to restore teir own state wen
tey are recycled. It can use data store like %(; database for maintain instance state. It is new
feature in ."et #.N
Bou migt tink tat we can also maintain session using WCF sessions, but content in te session
environment is not persisted by default. If te service is sut down or client closes te pro5y, data
will be lost. -ut in case of :urable service it is still maintained.
Wor/ing*
Wen :urable service is created wit database as data store, it will maintain all its state information
in te table.
Wen a client make a re2uest to te service, instance of te service is seriali<ed, a new H=I: is
generated. ,is seriali<ed instance 5ml and key will be saved in te database. We will call tis
H=I: as instanceI:. %ervice will send te instanceI: to te client, so later it can use tis id to get
te instance state back. +ven wen client is sut down, instanceId will be saved at te client side.
%o wen ever client opening te pro5y, it can get back te previous state.
Defining the Durable !ervice
:urable service can be implemented using 8:urable%ervice()9 attribute. It takes JCanCreateInstanceJ
and JCompletesInstanceJ property to mention on wic operation instance state as to be saved and
destroyed.
CanCreateInstance G true* Calling tis operation results in creating te seriali<ation and
inserting it into te datastore.
CompletesInstance G true* Calling tis operation results in deleting te persisted instance
from te datastore.
:SerialiFable;
:*urableService./;
public class MyService :$Myservice
<
:*urable5peration.CanCreate$nstance = true/;
public int Start8ersistance./
<
*o Something
=
:*urable5peration.Completes$nstance = true/;
public void (nd8ersistence./
<
*o Something
=
=

,ow to Create Durable !ervice
;et us understand more about te durable service by creating %imple Calculator service wic
persist te instance state in %(; server database.
!tep 1* %tart te 4isual %tudio /$$@ and click File-L"ew-LWeb %ite. %elect te JWCF %erviceJ as
sown below.

!tep "* Create interface and decorate wit %ervice and )peration contract.
:ServiceContract./;
public interface $SimpleCalculator
<
:5perationContract;
int 3dd.int num/0
:5perationContract;
int Subtract.int num/0
:5perationContract;
int Multiply.int num/0
:5perationContract;
void (nd8ersistence./0
=

!tep 5* Bou need to add 8%eriali<able9 0nd 8:urable%ervice()9 attribute to te service
implementation. %et CanCreateInstance I true property to te operation in wic instance state as
to be persisted and set CompletesInstance I true wen state as to be destroyed. In tis
implementation, we are going to persist te Jcurrent4alueJ variable value to te database.
using System.7untime.SerialiFation0
using System.ServiceModel0
using System.)e+t0
using System.ServiceModel.*escription0
:SerialiFable;
:*urableService./;
public class SimpleCalculator :$SimpleCalculator
<
int currentQalue = default.int/0
:*urable5peration.CanCreate$nstance = true/;
public int 3dd.int num/
<
return .currentQalue 9= num/0
=
:*urable5peration./;
public int Subtract.int num/
<
return .currentQalue D= num/0
=
:*urable5peration./;
public int Multiply.int num/
<
return .currentQalue K= num/0
=
:*urable5peration.Completes$nstance = true/;
public void (nd8ersistence./
<
=
!tep 6* -efore configuring te database information in te durable service, you need to set up
:ata%tore environment. 'icrosoft provides inbuilt s2l7ersistance provider. ,o set up te database
environment, run te tese s2l 2uery located at following location
JC>OWindowsO'icrosoft."+,OFrameworkOv#.NO%(;O+"J
%2l7ersistence7rovider%cema.s2l
%2l7ersistence7rovider;ogic.s2l
!tep 2* In order to support durable service, you need to use Conte5t binding type.
Ppersistence7roviderL tag is used to configure te persistence provider.
<system.serviceModel>
<services>
<service name="SimpleCalculator"
behaviorConfiguration="ServiceBehavior">
<CDD Service (ndpoints DD>
<endpoint address="" binding="%s&ttpConte+tBinding"
bindingConfiguration="bro%Config" contract="$SimpleCalculator">
<identity>
<dns value="localhost">
<identity>
<endpoint>
<endpoint address="me+" binding="me+&ttpBinding"
contract="$Metadata(+change">
<service>
<services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata http'et(nabled="true">
<service*ebug include(+ception*etail$n,aults="true">
<persistence8rovider
type="System.ServiceModel.8ersistence.SEl8ersistence8rovider,actory2
System.4orMflo%Services2 Qersion=P.I."."2 Culture=neutral2
8ublicRey)oMen=PGbfP!IJadPJOePI"
connectionStringLame="*urableServiceStore"
persistence5peration)imeout=""":"":G""
locM)imeout=""":"G:"""
serialiFe3s)e+t="true">
<behavior>
<serviceBehaviors>
<behaviors>
<bindings>
<%s&ttpConte+tBinding >
<binding name="bro%Config" >
<security mode="Lone"><security>
<binding>
<%s&ttpConte+tBinding>
<bindings>
<system.serviceModel>
<connectionStrings>
<add name="*urableServiceStore"
connectionString="*ata Source=saravanaMumar0$nitial Catalog
=*urableServiceStore0$ntegrated Security=)rue">
<connectionStrings>
!tep 4* Create te console client application and name it as :urable%erviceClient

!tep 7* 0dd following reference to client application
%ystem.%ervice'odel
%ystem.Workflow%ervice

!tep $* 0dd WCF service as %ervice &eference to te proGect and name it as
%impleCalculator%ervice

!tep 8* Create te 6elper class called it as 6elper.cs. ,is elper class is used to %tore, &etrieve
and set te conte5t at te client side. Conte5t information will be saved in JtokenQconte5t.binJ file.
Copy and paste te below code to your elper file.
,elper.cs
using System.ServiceModel.Channels0
using System.ServiceModel0
using System.Let0
using System.$50
using System.7untime.SerialiFation.,ormatters.Binary0
public class &elper
<
static readonly String )oMenConte+t,ileLame = "toMenBconte+t.bin"0
public static $*ictionary<String2 String> 6oadConte+t./
<
$*ictionary<String2 String> ct+ = null0
try
<
using .,ileStream fs = ne%
,ileStream.)oMenConte+t,ileLame2 ,ileMode.5pen2
,ile3ccess.7ead//
<
Binary,ormatter bf = ne% Binary,ormatter./0
ct+ = bf.*eserialiFe.fs/ as $*ictionary<String2 String>0
fs.Close./0
=
=
catch .(+ception e+/
<
=
return ct+0
=
public static void SaveConte+t.$ClientChannel channel/
<
$*ictionary<String2 String> ct+ = null0
$Conte+tManager cm = channel.'et8roperty<$Conte+tManager>./0
if .cm C= null/
<
ct+ = cm.'etConte+t./ as $*ictionary<String2 String>0
try
<
using .,ileStream fs
= ne% ,ileStream.)oMenConte+t,ileLame2 ,ileMode.CreateLe%//
<
Binary,ormatter bf = ne% Binary,ormatter./0
bf.SerialiFe.fs2 ct+/0
fs.Close./0
=
=
catch .(+ception e+/
<
=
=
=
public static void *eleteConte+t./
<
try
<
,ile.*elete.)oMenConte+t,ileLame/0
=
catch .(+ception e+/
<
=
=
public static void SetConte+t.$ClientChannel channel2
$*ictionary<String2 String> ct+/
<
$Conte+tManager cm = channel.'et8roperty<$Conte+tManager>./0
if .cm C= null/
<
cm.SetConte+t.ct+/0
=
=
=
!tep 1#* In te main metod, I was creating te pro5y for te service and calling te 0dd operation.
Call to tis metod will add instance state to te database. "ow I ave closed te pro5y and creating
new pro5y instance. Wen I call te %ubtract and 'ultiply operation, it will operate on te
previously saved value (instance state).
static void Main.string:; args/
<

Create the pro+y for the service
SimpleCalculatorService.SimpleCalculatorClient client
= ne% SimpleCalculatorService.SimpleCalculatorClient
"4S&ttpConte+tBindingB$SimpleCalculator"/0
int currentQalue = "0
Call the 3dd method from the service
currentQalue = client.3dd.G""""/0
Console.4rite6ine.")he current value is <"="2 currentQalue/0
Save the Conte+t from the service to the client
&elper.SaveConte+t.client.$nnerChannel/0
Close the pro+y
client.Close./0

Create ne% $nstance of the pro+y for the service
client = ne% SimpleCalculatorService.SimpleCalculatorClient
."4S&ttpConte+tBindingB$SimpleCalculator"/0
6oad the conte+t from the client to start from saved state
$*ictionary<string2string> cnt+=&elper.6oadConte+t./0
Set Conte+t to conte+t manager
&elper.SetConte+t.client.$nnerChannel2 cnt+/0
Call the Subtract and Multiply method from service
currentQalue = client.Subtract.H/0
Console.4rite6ine.")he current value is <"="2 currentQalue/0
currentQalue = client.Multiply.I/0
Console.4rite6ine.")he current value is <"="2 currentQalue/0
*elete the conte+t from the client
&elper.*eleteConte+t./0
7emove persistance state from the server
client.(nd8ersistence./0
Console.4rite6ine."8ress <(L)(7> to shut do%n the client."/0
Console.7ead6ine./0
client.Close./0
=
+nd of te pro5y ., service instance saved in te database as sown below.

%eriali<ed 1'; instance state save in te database is sown below.

)utput of te client application.

Throttling
WCF trottling provides some properties tat you can use to limit ow many instances or sessions
are created at te application level. 7erformance of te WCF service can be improved by creating
proper instance.
Attribute Description
ma5ConcurrentCalls
;imits te total number of calls tat can currently be in progress across
all service instances. ,e default is .C.
ma5ConcurrentInstances
,e number of InstanceConte5t obGects tat e5ecute at one time across a
%ervice6ost. ,e default is Int#/.'a54alue.
ma5Concurrent%essions
0 positive integer tat limits te number of sessions a %ervice6ost obGect
can accept. ,e default is .$.
%ervice ,rottling can be configured eiter 0dminstractive or 7rogramatically
AdministrativeAconfiguration fileB
=sing Pservice,rottlingL tag of te %ervice -eavior, you can configure te maxConcurrentCalls,
maxConcurrent0nstances , maxConcurrentSessions property as sown below.
<system.serviceModel>
<services >
<service behaviorConfiguration="ServiceBehavior" name="MyService">
<endpoint address="" binding="%s&ttpBinding" contract="$MyService">
<identity>
<dns value="localhost">
<identity>
<endpoint>
<endpoint address="me+" binding="me+&ttpBinding"
contract="$Metadata(+change">
<service>
<services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata http'et(nabled="true">
<service*ebug include(+ception*etail$n,aults="true ">
<service)hrottling ma+ConcurrentCalls="I"""
ma+Concurrent$nstances ="G"""
ma+ConcurrentSessions ="H""">
<behavior>
<serviceBehaviors>
<behaviors>
<system.serviceModel>
(rogramming -odel
=se %ervice,rottling-eavior obGect to set concurrent calls, session and instance property.
Service&ost host = ne% Service&ost.typeof.MyService//0
Service)hrottlingBehavior throttle
= host.*escription.Behaviors.,ind./0
if .throttle == null/
<
throttle = ne% Service)hrottlingBehavior./0
throttle.Ma+ConcurrentCalls = I""0
throttle.Ma+ConcurrentSessions = H""0
throttle.Ma+Concurrent$nstances = G""0
host.*escription.Behaviors.3dd.throttle/0
=
host.5pen./0

;perations
In classic obGect or component- oriented programming model offered only single way for client to
call a metod. Client will issue a call, block wile te call was in progress, and continue e5ecuting
once te metod returned.
WCF will support classical &e2uest-&eplay model, along wit tat it also supports )ne-Way
call(call and forget operation) and callback(service to call back te client)
,ree modes of communication between client and service are
.. &e2uest- &eplay
/. )ne-Way
#. Callback
.eCuest-.epl&
-y default all WCF will operated in te &e2uest-&eplay mode. It means tat, wen client make a
re2uest to te WCF service and client will wait to get response from service (till receive7imeout).
0fter getting te response it will start e5ecuting te rest of te statement. If service doesnJt respond
to te service witin receive,imeout, client will receive 7ime3ut2xception.
0part from 8et.eer7cp%inding and te 8etMsm9%inding all oter bindings will support re2uest-
reply operations.
;ne-Wa&
In )ne-Way operation mode, client will send a re2uest to te server and does not care weter it is
success or failure of service e5ecution. ,ere is no return from te server side, it is one-way
communication.
Client will be blocked only for a moment till it dispatces its call to service. If any e5ception
trown by service will not reac te server.
Client can continue to e5ecute its statement, after making one-way call to server. ,ere is no need
to wait, till server e5ecute. %ometime wen one-way calls reac te service, tey may not be
dispatced all at once but may instead be 2ueued up on te service side to be dispatced one at a
time, according to te serviceJs configured concurrency mode beavior. If te number of 2ueued
messages as e5ceeded te 2ueueJs capacity, te client will be blocked even if itJs issued a one-way
call. 6owever, once te call is 2ueued, te client will be unblocked and can continue e5ecuting,
wile te service processes te operation in te background.
Definition *
)ne-way operation can be enabled by setting Is)neWay property to true in )peration contract
attribute.
:ServiceContract;
public interface $MyService
<
:5perationContract.$s5ne4ay=true/;
void MyMethod.(mployee*etails emp/0
=
;ne-Wa& ;perations and !essionful !ervices
;et us see te e5ample, wat will appen wen you use te one-way communication wit
%essionful service.
:ServiceContract.SessionMode = SessionMode.7eEuired/;
interface $MyContract
<
:5perationContract.$s5ne4ay = true/;
void MyMethod./0
=
0s per above configuration, wen client makes one-way call using 'y'etod() operation and if it
close te pro5y. Client will be blocked until operation completes. It will be good practice, tat one-
way operation sould be applied on per-call and singleton service.
%uppose If you want to make use of )ne-way operation in %essionful service, use in te last
operation of te service wic will terminate te session. ,is operation sould not return any
value.
:ServiceContract.SessionMode = SessionMode.7eEuired/;
interface $MyContract
<
:5perationContract;
void MyMethodG./0
:5perationContract;
string MyMethodH./0
:5perationContract.$s5ne4ay = true2 $s$nitiating = false2
$s)erminating = true/;
string CloseSessionService.int id/0

=
;ne-Wa& ;perations and '%ceptions
%uppose wen we are using %asicHttp%inding or 'SHttp%inding, i.e. no transport session is used, if
any e5ception trow by service will not affect te client. Client can make a call to te service using
same pro5y
:ServiceContract;
interface $MyContract
<
:5perationContract.$s5ne4ay = true/;
void Method4ith(rror. /0
:5perationContract;
void Method4ithout(rror. /0
=
Client side %ithout transport session
MyContractClient pro+y = ne% MyContractClient. /0
pro+y.Method4ith(rror. /0 Lo e+ception is thro%n from serivce
pro+y.Method4ithout(rror. /0 5peration %ill e+ecute properly
pro+y.Close. /0
In te presence of transport session, any e5ception trown by service will fault te client cannel.
Client will not be able to make new call using same pro5y instance.
Client side transport session
MyContractClient pro+y = ne% MyContractClient. /0
pro+y.Method4ith(rror. /0
pro+y.Method4ithout(rror. /0 Can not e+ecutre because channel is faulted
pro+y.Close. /0
Callbac/ !ervice
,ill now we ave seen tat te all clients will call te service to get te tings done. -ut WCF also
provides te service to call te client. In wic, service will act as client and client will act as
service.
6,,7 protocols are connectionless nature, so it is not supported for callback operation. %o
-asic6ttp-inding and W%6ttp-inding cannot be used for tis operation.
WCF support W%:ual6ttp-inding for call back operation.
0ll ,C7 and I7C protocols support :uple5 communication. %o all tese binding will be used
for callback operation.
Defining and configuring a callbac/ contract
Callback service can be enabled by using Callbac:Contract property in te ServiceContract
attribute. In te below e5ample you can find te decalration of te callback contract and it is
configured in te ServiceContract attribute.
public interface $MyContractCallbacM
<
:5perationContract;
void 5nCallbacM./0
=
:ServiceContract.CallbacMContract = typeof.$MyContractCallbacM//;
public interface $MyContract
<
:5perationContract./;
void MyMethod./0
=

Client Callbac/ !etup
0s I said earlier, in callback operation client will act as service and service will act as client. %o
client as to e5pose a callback endpoint to te service to call. In te earlier part of te tutorial I ave
mention tat InstanceConte5t is te e5ecution scope of inner most service instance. It provides a
constructor tat takes te service instance to te ost.
$MyContractCallbacM callbacM=ne% MyCallbacM./0
$nstanceConte+t cnt+=ne% $nstanceConte+t.callbacM/0
MyServiceClient pro+y = ne% MyServiceClient.cnt+/0
pro+y.MyMethod./0
,e client must use a pro5y tat will set up te bidirectional communication and pass te callback
endpoint reference to te service. ,is can be acieved by creating te pro5y using
,uplexClient%ase
class MyServiceClient:*uple+ClientBase2$MyContract
<
public MyServiceClient.$nstanceConte+t callbacMCnt+/
: base.callbacMCnt+/
<
=
public void MyMethod./
<
base.Channel.MyMethod./0
=
=
!ervice-!ide Callbac/ Invocation
,e client-side callback endpoint reference is passed along wit every call te client makes to te
service, and it is part of te incoming message. ,e )perationConte5t class provides te service
wit easy access to te callback reference via te generic metod ;etCallbac:ChannelP,L( ).
%ervice can call te client side callback metod using reference e to te client side callback
instance. ,e following code sows te callback metod invocation.
$MyContractCallbacM
callbacM$nstance=5perationConte+t.Current.'etCallbacMChannel./0
callbacM$nstance.5nCallbacM./0
,ow to Create Callbac/ !ervice in WCF
,is tutorial gives ands-on to create a sample Callback service.
!tep 1* Create te sample Classlibrary proGect using 4isual %tudio /$$@ and name it as
Callback%ervice
!tep " * 0dd System.ServiceModel reference to te proGect
!tep 5* Create te Callback and %ervice contract as sown below. Bou need to mention
Callbac:Contract property in te ServiceContract attribute. Implementation of te Callback
contract will be done on te client side.
I-&Contract.cs
using System0
using System.Collections.'eneric0
using System.6inE0
using System.)e+t0
using System.ServiceModel0
namespace CallbacMService
<

public interface $MyContractCallbacM
<
:5perationContract;
void 5nCallbacM./0
=
:ServiceContract.CallbacMContract = typeof.$MyContractCallbacM//;
public interface $MyContract
<
:5perationContract./;
void MyMethod./0
=
=
!tep 6* Implement te %ervice contract as sown below. In te below code you will find using
3perationContext is used to receive te reference to Callback instance. =sing tat instance we are
calling te 3nCallbac:<= metod from client side.
-&!ervice.cs
using System0
using System.Collections.'eneric0
using System.6inE0
using System.)e+t0
using System.ServiceModel0
namespace CallbacMService
<
:ServiceBehavior.ConcurrencyMode=ConcurrencyMode.Multiple /;
public class MyService:$MyContract
<
public void MyMethod./
<
*o something
$MyContractCallbacM callbacM$nstance
=5perationConte+t.Current.'etCallbacMChannel./0
callbacM$nstance.5nCallbacM./0
=
=
=
Bou can also note tat We ave set te ConcurrencyMode to 'ultile. If you are not using
Concurrency'ode to 'ultiple or &eentent, you will be end up wit deadlock e5ception as sown
below. ,is is because wen a client made a call to te service, cannel is created and lock by WCF
service. If you are calling te Callback metod inside te service metod. %ervice will try to access
te lock cannel, tis may leads to deadlock. %o you can set ConcurrencyMode to Multiple or
4eentent so it will release te lock silently.

!tep 2* Create a Console application using 4isual %tudio /$$@ and name it a Callback%ervice6ost.
,is application is used to self-ost te WCF service

!tep 4* 'ain metod
static void Main.string:; args/
<
-ri http-rl = ne% -ri."http:localhost:!"#"MyService"/0
Service&ost host = ne%
Service&ost.typeof.CallbacMService.MyService/2 http-rl/0
host.5pen./0
Console.4rite6ine."Service is &osted at <"="2
*ate)ime.Lo%.)oString.//0
Console.4rite6ine."&ost is running...8ress Mey to stop the
service."/0
Console.7ead6ine./0
host.Close./0
=

!tep 7* =se :uple5 binding to support Callback operation.
Web.Config
<system.serviceModel>
<services >
<service behaviorConfiguration="ServiceBehavior"
name="CallbacMService.MyService">
<endpoint address="http:localhost:!"#"MyService"
binding="%s*ual&ttpBinding" contract="CallbacMService.$MyContract">
<identity>
<dns value="localhost">
<identity>
<endpoint>
<endpoint address="me+"
binding="me+&ttpBinding" contract="$Metadata(+change">
<service>
<services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata http'et(nabled="true">
<service*ebug include(+ception*etail$n,aults="true ">
<behavior>
<serviceBehaviors>
<behaviors>
<system.serviceModel>
!tep $* &un te ost application

!tep 8* Create Console 0pplication using 4isual %tudio /$$@ and name it as CallbackClient. ,is is
te client application wic contain Callback implementation.

!tep1#* 0dd System.ServiceModel and Callbac:Service as reference to te proGect
!tep 11* Create te pro5y class as sown below. =se ,uplexClient%ase to create te pro5y, because
it will support bidirectional communication. Create te contractor wic will accept
0nstanceContext as parameter.
using System0
using System.Collections.'eneric0
using System.6inE0
using System.)e+t0
using System.ServiceModel0
using CallbacMService0
namespace CallbacMClient
<
class MyServiceClient:*uple+ClientBase<$MyContract>2$MyContract
<
public MyServiceClient.$nstanceConte+t callbacMCnt+/
: base.callbacMCnt+/
<
=
public void MyMethod./
<
base.Channel.MyMethod./0
=
=

=
!tep1"* Create te implementation for Callback Contract
class MyCallbacM : $MyContractCallbacM
<
public void 5nCallbacM./
<
Console.4rite6ine."CallbacM method is called from client side."/0

=
=
!tep 15* Implementation of main metod
static void Main.string:; args/
<
$MyContractCallbacM callbacM=ne% MyCallbacM./0
$nstanceConte+t cnt+=ne% $nstanceConte+t.callbacM/0
MyServiceClient pro+y = ne% MyServiceClient.cnt+/0
Console.4rite6ine."Client call the MyMethod 5peration from
Service."/0
pro+y.MyMethod./0
Console.7ead6ine./0
=
!tep16* &un te client application. In te output, you can see te )nCallback metod called by te
service

'vents
+vents allow te client or clients to be notified about someting tat as occurred on te service
side. 0n event may result from a direct client call, or it may be te result of someting te service
monitors. ,e service firing te event is called te publiser, and te client receiving te event is
called te subscriber.

7ubliser will not care about order of invocation of subscriber. %ubscriber can be e5ecuted
in any manner.
Implementation of subscriber side sould be sort duration. ;et us consider te scenario in
wic you wat to publis large volume of event. 7ubliser will be blocked, wen
subscriber is 2ueued on previous subscription of te event. ,ese make publisers to put in
wait state. It may lead 7ubliser event not to reac oter subscriber.
;arge number of subscribers to te event makes te accumulated processing time of eac
subscriber could e5ceed te publiserJs timeout
'anaging te list of subscribers and teir preferences is a completely service-side
implementation. It will not affect te client! publiser can even use ."et delegates to manage
te list of subscribers.
+vent sould always one-Way operation and it sould not return any value
Definition
public interface $My(vents
<
:5perationContract.$s5ne4ay = true/;
void (ventG./0
=
;et us understand more on +vent operation by creating sample service
!tep 1 * Create Class;ibrary proGect in te 4isual %tudio /$$@ and name it as WCF+vent%ervice as
sown below.

%tep />
0dd reference System.ServiceModel to te proGect
Create te +vent operation at te service and set 0s3nw'ay property to true. ,is operation sould
not return any value. %ince service as to communicate to te client, we need to use
Callbac:Contract for duple5 communication. 6ere we are using one operation to subscribe te
event and anoter for firing te event.
public interface $My(vents
<
:5perationContract.$s5ne4ay = true/;
void (ventG./0
=
:ServiceContract.CallbacMContract = typeof.$My(vents//;
public interface $MyContract
<
:5perationContract;
void *oSomething3nd,ire(vent./0
:5perationContract;
void Subscribe(vent./0
=
!tep 5* Implementation of te %ervice Contract is sown below.
In te %ubscription operation, I am using )perationconte5t to get te reference to te client instance
and %ubscription metod is added as event andler to te service event. :o%ometing0ndFire+vent
operation will fire te event as sown.
-&(ublisher.cs
:ServiceBehavior.$nstanceConte+tMode = $nstanceConte+tMode.8erCall/;
public class My8ublisher : $MyContract
<
static 3ction mB(ventG = delegate < =0
public void Subscribe(vent./
<
$My(vents subscriber =
5perationConte+t.Current.'etCallbacMChannel./0
mB(ventG 9= subscriber.(ventG0
=
public static void ,ire(vent./
<
mB(ventG./0
=
public void *oSomething3nd,ire(vent./
<
My8ublisher.,ire(vent./0
=
=
!tep 6* Create te Console application using 4isual %tudio /$$@ and name it as
Wcf+vent%ervice6ost. ,is application will be used to self-ost te service.

!tep 2* 0dd System.ServiceModel and 'cf2ventService as reference to te proGect.
static void Main.string:; args/
<
-ri http-rl = ne% -ri."http:localhost:!"#"My8ublisher"/0
Service&ost host = ne%
Service&ost.typeof.4cf(ventService.My8ublisher/2 http-rl/0
host.5pen./0
Console.4rite6ine."Service is &osted at <"="2
*ate)ime.Lo%.)oString.//0
Console.4rite6ine."&ost is running...8ress Mey to stop the
service."/0
Console.7ead6ine./0
host.Close./0
=

!tep 4* =se :uple5 binding to support Callback operation.
Web.Config
<system.serviceModel>
<services >
<service behaviorConfiguration="ServiceBehavior"
name="4cf(ventService.My8ublisher">
<endpoint address="http:localhost:!"#"My8ublisher"
binding="%s*ual&ttpBinding" contract="4cf(ventService.$MyContract">
<identity>
<dns value="localhost">
<identity>
<endpoint>
<endpoint address="me+" binding="me+&ttpBinding"
contract="$Metadata(+change">
<service>
<services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata http'et(nabled="true">
<service*ebug include(+ception*etail$n,aults="true ">
<behavior>
<serviceBehaviors>
<behaviors>
<system.serviceModel>
!tep7* &un te ost application as sown below.

!tep $* Create te console application using visual studio and name it as 'cf2ventServiceClient as
sown below. ,is application will act a client wic is used to subscribe te event from service.

!tep 8* Create te pro5y class as sown below. =se ,uplexClient%ase to create te pro5y, because
it will support bidirectional communication. Create te contractor wic will accept
InstanceConte5t as parameter.
'vent!erviceClient.cs
class (ventServiceClient:*uple+ClientBase<$MyContract>2$MyContract
<
public (ventServiceClient.$nstanceConte+t eventCnt+/
: base.eventCnt+/
<

=
public void *oSomething3nd,ire(vent./
<
base.Channel.*oSomething3nd,ire(vent./0
=
public void Subscribe(vent./
<
base.Channel.Subscribe(vent./0
=

=
!tep 1#* Implementation of I'y+vents at client side is sown below. ,is metod will be called
wen service publis te event.
class MySubscriber : $My(vents
<
public void (ventG./
<
Console.4rite6ine."(vent is subscribed from the
service at <"="2*ate)ime.Lo%.)oString./ /0
=

=
!tep 11* 'ain metod of te client side you can find te creating %ubscription instance and it
passed to service using 0nstanceContext
static void Main.string:; args/
<
$My(vents evnt = ne% MySubscriber./0
$nstanceConte+t evntCnt+ = ne% $nstanceConte+t.evnt/0
(ventServiceClient pro+y = ne% (ventServiceClient.evntCnt+/0
Console.4rite6ine."Client subscribe the event
from the service at <"="2*ate)ime.Lo%.)oString.//0
pro+y.Subscribe(vent./0
Console.4rite6ine."Client call operation %hich %ill fire the
event"/0
pro+y.*oSomething3nd,ire(vent./0
Console.7ead6ine./0
=
!tep 1"* &un te client application and you see te wen event is fired from te service. %ubscriber
got notification.

Transfer mode
In our normal day today life, we need to transfer data from one location to oter location. If data
transfer is taking place troug WCF service, message si<e will play maGor role in performance of
te data transfer. -ased on te si<e and oter condition of te data transfer, WCF supports two
modes for transferring messages
)uffer transfer
Wen te client and te service e5cange messages, tese messages are buffered on te receiving
end and delivered only once te entire message as been received. ,is is true weter it is te
client sending a message to te service or te service returning a message to te client. 0s a result,
wen te client calls te service, te service is invoked only after te clientJs message as been
received in its entirety! likewise, te client is unblocked only once te returned message wit te
results of te invocation as been received in its entirety.
!tream transfer
Wen client and %ervice e5cange message using %treaming transfer mode, receiver can start
processing te message before it is completely delivered. %treamed transfers can improve te
scalability of a service by eliminating te re2uirement for large memory buffers. If you want to
transfer large message, streaming is te best metod.
!tream.eCuest
In tis mode of configuration, message send from client to service will be streamed
!tream.espone
In tis mode of configuration, message send from service to client will be streamed.
Configuration
<system.serviceModel>
<services >
<service behaviorConfiguration="ServiceBehavior" name="MyService">
<endpoint address="" binding="net)cpBinding"
bindingConfiguration="MyService.net)cpBinding" contract="$MyService">
<identity>
<dns value="localhost">
<identity>
<endpoint>
<endpoint address="me+" binding="me+&ttpBinding"
contract="$Metadata(+change">
<service>
<services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata http'et(nabled="true">
<service*ebug include(+ception*etail$n,aults="true ">
<behavior>
<serviceBehaviors>
<behaviors>
<bindings >
<net)cpBinding>
<binding name="MyService.net)cpBinding"
transferMode="Buffered" close)imeout ="":"G:"""
open)imeout="":"G:"""><binding>
<net)cpBinding>
<bindings>
<system.serviceModel>
Differences between )uffered and !treamed Transfers
)uffered !treamed
,arget can process te message once it is
completely received.
,arget can start processing te data wen it is
partially received
7erformance will be good wen message si<e is
small
7erformance will be good wen message si<e is
larger(more tan C3D)
"ative cannel sape is
I:uple5%essionCannel
"ative cannels are I&e2uestCannel and
I&eplyCannel
!treaming
Client and %ervice e5cange message using %treaming transfer mode, receiver can start processing
te message before it is completely delivered. %treamed transfers can improve te scalability of a
service by eliminating te re2uirement for large memory buffers. If you want to transfer large
message, streaming is te best metod.
!upported )indings
-asic6ttp-inding
"et,cp-inding
"et"amed7ipe-inding
.estrictions
,ere are some restriction, wen streaming is enabled in WCF
:igital signatures for te message body cannot be performed
+ncryption depends on digital signatures to verify tat te data as been reconstructed
correctly.
&eliable sessions must buffer sent messages on te client for redelivery if a message gets
lost in transfer and must old messages on te service before anding tem to te service
implementation to preserve message order in case messages are received out-of-se2uence.
%treaming is not available wit te 'essage (ueuing ('%'() transport
%treaming is also not available wen using te 7eer Cannel transport
I3; !treams
WCF uses ."et stream class for %treaming te message. %tream in base class for streaming, all
subclasses like File%tream,'emory%tream, "etwork%tream are derived from it. %tream te data,
you need to do is, to return or receive a %tream as an operation parameter.
:ServiceContract;
public interface $MyService
<
:5perationContract;
void SaveStream*ata.Stream emp/0
:5perationContract;
Stream 'etStream*ata./0
=
+ote*
.. %tream and itJs subclass can be used for streaming, but it sould be seriali<able
/. %tream and 'emory%tream are seriali<able and it will support streaming
#. File%tream is non seriali<able, and it will not support streaming
!treaming and )inding
)nly te ,C7, I7C, and basic 6,,7 bindings support streaming. Wit all of tese bindings
streaming is disabled by default. 7ransferMode property sould be set according to te desired
streaming mode in te bindings.
public enum )ransferMode
<
Buffered2 *efault
Streamed2
Streamed7eEuest2
Streamed7esponse
=
public class Basic&ttpBinding : Binding2...
<
public )ransferMode )ransferMode
<get0set0=
More members
=
!treamed.eCuest - %end and accept re2uests in streaming mode, and accept and return
responses in buffered mode
!tream.esponse - %end and accept re2uests in buffered mode, and accept and return
responses in streamed mode
!treamed - %end and receive re2uests and responses in streamed mode in bot directions
)uffered -%end and receive re2uests and responses in -uffered mode in bot directions
!treaming and Transport
,e main aim of te %treaming transfer mode is to transfer large si<e data, but default message si<e
is C3D. %o you can increase te message si<e using max4eceivedMessageSi5e attribute in te
binding element as sown below.
<system.serviceModel>
<bindings >
<net)cpBinding>
<binding name="MyService.net)cpBinding"
transferMode="Buffered" ma+7eceivedMessageSiFe="G"HO"""">
<binding>
<net)cpBinding>
<bindings>
<system.serviceModel>
Transaction
0 transaction is a collection or group of one or more units of operation e5ecuted as a wole. It
provides way to logically group single piece of work and e5ecute tem as a single unit. In addition,
WCF allows client applications to create transactions and to propagate transactions across service
boundaries.
.ecover& Challenge
;et us discuss more on callenge we will pased and ow to recover from it.
.. Consider a system maintained in consistent state, wen application fail to perform particular
operation, you sould recover from it and place te system in te consistent state.
/. Wile doing singe operation, tere will be multiple atomic sub operation will appen. ,ese
operations migt success or fail. We are not considering about sub operation wic are
failed. We mainly consider about te success operation. -ecause we ave to recover all
tese state to its previous consistence state.
#. 7roductivity penalty as to be payee for all effort re2uired for andcrafting te recovery
logic
3. 7erformance will be decreased because you need to e5ecute uge amount of code.
!olution
-est way to maintain system consistence and andling error-recovery callenge is to use
transactions. -elow figure gives idea about transaction.

Committed transaction* ,ransaction tat e5ecute successfully and transfer te system from
consistence state 0 to -.
Aborted transaction* ,ransaction encounters an error and rollback to Consistence %tate 0
from intermediate state.
In-doubt transaction* ,ransactions fail to eiter in commit or abort.
Transaction .esources
,ransactional programming re2uires working wit a resource tat is capable of participating in a
transaction, and being able to commit or roll back te canges made during te transaction. %uc
resources ave been around in one form or anoter for decades. ,raditionally, you ad to inform a
resource tat you would like to perform transactional work against it. ,is act is called enlisting.
%ome resources support auto-enlisting.
Transaction (roperties
,ransaction can be said as pure and successful only if meets four caracteristics.
0tomic - Wen transaction completes, all te individual canges made to te resource wile
process must be made as to tey were all one atomic, indivisible operation.
Consistent - transaction must leave te system in consistent state.
Isolated - &esources participating in te transaction sould be locked and it sould not be
access by oter tird party.
:urable - :urable transactions must survive failures.
Two-phase committed protocol
Consider te scenario were I am aving single client wic use single service for communication
and interacting wit single database. In wic service starts and manage te transaction, now it will
be easy for te service to manage te transaction.
Consider for e5ample client calling multiple service or service itself calling anoter service, tis
type of system are called as :istributed %ervice-oriented application. "ow te 2uestions arise tat
wic service will begin te transactionF Wic service will take responsibility of committing te
transactionF 6ow would one service know wat te rest of te service feels about te transactionF
%ervice could also be deployed in different macine and site. 0ny network failure or macine cras
also increases te comple5ity for managing te transaction.
In order to overcome tese situations, WCF come up wit distributed transaction using two way
committed protocol and dedicated transaction manager.
,ransaction 'anager is te tird party for te service tat will manage te transaction using two
pase committed protocol.
;et us see ow ,ransaction manager will manage te transaction using two-pase committed
protocols.
Transaction (ropagation
In WCF, transaction can be propagated across service boundary. ,is enables service to participate
in a client transaction and it includes multiple services in same transaction, Client itself will act as
service or client.
We can specify weter or not client transaction is propagated to service by canging -inding and
operational contract configuration
<bindings>
<net)cpBinding>
<binding transaction,lo%="true"><binding>
<net)cpBinding>
<bindings>
+ven after enabling transaction flow does not mean tat te service wants to use te clientRs
transaction in every operation. We need to specify te S,ransactionFlow0ttributeT in operational
contract to enable transaction flow.
:ServiceContract;
public interface $Service
<
:5perationContract;
:)ransaction,lo%.)ransaction,lo%5ption.3llo%ed/;
int 3dd.int a2 int b/0
:5perationContract;
int Subtract.int a2 int b/0
=
+ote* ,ransactionFlow can be enabled only at te operation level not at te service level.
TransactionFlow;ption
)inding
configuration
"ot0llowed
transactionFlowIMtr
ueM
or
transactionFlowIMf
alseM
Client cannot propagate its transaction to service
even client as transaction
0llowed
transactionFlowIMtr
ueM
%ervice will allow to flow client transaction.
It is not necessary tat service to use client
transaction.
0llowed
transactionFlowIMf
alseM
If service disallows at binding level, client also
sould disable at binding level else error will be
occurred.
'andatory
transactionFlowIMtr
ueM
-ot %ervice and client must use transaction aware
binding
'andatory
transactionFlowIMf
alseM
Invalid)peration+5ception will be trow wen
serice binding disables at binding level.
Fault+5ception will be trown wen client disable
at its binding level.
Transaction (rotocols
0s a developer we no need to concern about transaction protocols and transaction manager used by
WCF. WCF itself will take care of wat kind of transaction protocols sould be used for different
situation. -asically tere are tree different kinds of transaction protocols used by WCF.
,andling '%ception in !ilverlight application
from WCF
Attachment*
%ilverligtQWCFQ+5ception.<ip
,is article e5plains about andling te e5ception in %ilverligt application from WCF. I ave
created te sample %ilverligt application, wic uses te WCF service for process te data. Wile
testing te application I came to know tat e5ception message trown from WCF cannot be
received at te client side(%ilverligt application) even after using te Fault+5ception. I was always
getting !&stem.!ervice-odel.Communication'%ception* ,e remote server returned an error>
"otFound.
;ater I came to know tat WCF trows te 6,,7 N$$ series Fault message but %ilverligt can
andle only /$$ series. %o we need to convert te N$$ series to /$$ error message for %ilverligt.
6ere is te sample application for e5ception andling between WCF and %ilverligt.
!tep 1* We can customi<e te +ndpoint beavior of te WCF service by ineriting te %eha and
implementing the 02ndpoint%ehavior. -ctual code for converting the >!! error serice to )!! serivce
in %eforeSend4eply method.
Create a Class6ibrary pro?ect and name it as @Silverlight_WCF_FaultBehaviorA and name the
class as @Silverlight1ault%ehaviorA. Copy and paste the follwing code inside the
Silverlight1ault%ehavior class.
Imports System.ServiceModel.ConfigurationrviceModel.Configuration
Imports System.ServiceModel.Description
Imports System.ServiceModel.Dispatcher
Imports System.ServiceModel.Channels
Imports System.ServiceModel
Public Class Silverlightault!ehavior
Inherits !ehavior"#tension"lement
Implements I"ndpoint!ehavior
Public $verrides %ead$nly Property !ehavior&ype'( )s System.&ype
*et
%eturn *et&ype'Silverlightault!ehavior(
"nd *et
"nd Property
Protected $verrides unction Create!ehavior'( )s $b+ect
%eturn ,e- Silverlightault!ehavior
"nd unction
Public Sub )dd!indingParameters'!y.al endpoint )s Service"ndpoint/
!y.al bindingParameters )s
!indingParameterCollection(
Implements
I"ndpoint!ehavior.)dd!indingParameters
"nd Sub
Public Sub )pplyClient!ehavior'!y.al endpoint )s Service"ndpoint/
!y.al client%untime )s Client%untime(
Implements
I"ndpoint!ehavior.)pplyClient!ehavior
"nd Sub
Public Sub )pplyDispatch!ehavior'!y.al endpoint )s Service"ndpoint/
!y.al endpointDispatcher )s "ndpointDispatcher(
Implements I"ndpoint!ehavior.)pplyDispatch!ehavior
Dim inspector )s ,e- SilverlightaultMessageInspector'(
endpointDispatcher.Dispatch%untime.MessageInspectors.)dd'inspector(
"nd Sub
Public Sub .alidate'!y.al endpoint )s Service"ndpoint(
Implements I"ndpoint!ehavior..alidate
"nd Sub
Public Class SilverlightaultMessageInspector
Implements IDispatchMessageInspector
Public unction )fter%eceive%e0uest'!y%ef re0uest )s Message/
!y.al channel )s IClientChannel/
!y.al instanceConte#t )s InstanceConte#t(
)s $b+ect
Implements
IDispatchMessageInspector.)fter%eceive%e0uest
1 Do nothing to the incoming message.
%eturn ,othing
"nd unction
Public Sub !eforeSend%eply'!y%ef reply )s
System.ServiceModel.Channels.Message/
!y.al correlationState )s $b+ect(
Implements
IDispatchMessageInspector.!eforeSend%eply
If reply.Isault &hen
Dim 2property3 )s ,e- Http%esponseMessageProperty'(
1 Here the response code is changed to 455.
2property3.StatusCode 6 System.,et.HttpStatusCode.$7
reply.Properties'Http%esponseMessageProperty.,ame( 6
2property3
"nd If
"nd Sub
"nd Class
"nd Class
Note: Highlighted code shows the conversion for >!! serices to )!! series error code.
Step !: %uild the pro?ect
Step ": Create a new 'C1 service with 0nterface and implementation class as follows
#nter$ace
8ServiceContract'(9 :
Public Interface IService
8$perationContract'(9 :
unction )dd'!y.al num; )s Integer/ !y.al num4 )s Integer( )s Integer
8$perationContract'(9 :
unction Subtract'!y.al num; )s Integer/ !y.al num4 )s Integer( )s Integer

"nd Interface
#%ple%entation
Public Class Service
Implements IService
Public Sub ,e-'(
"nd Sub
Public unction )dd'!y.al num; )s Integer/ !y.al num4 )s Integer(
)s Integer Implements IService.)dd
&hro- ,e- ault"#ception'<"rror thro-n by user for )dd operation<(
1%eturn num; = num4
"nd unction
Public unction Subtract'!y.al num; )s Integer/
!y.al num4 )s Integer( )s Integer Implements
IService.Subtract
%eturn num; > num4
"nd unction
"nd Class
B -dd the Silverlight_WCF_FaultBehavior pro?ect dll as reference to 'C1 Service
Step &:
Step &: #n WCF 'e can e(tend the )inding and )ehavior )* using +e(tention, tag. #n our case
also 'e are e(tending the custo% endpoint )ehavior as sho'n )elo'. #n the
+)ehaviorE(tensions, tag 'e need speci$* the $ull* -uali$ied na%e o$ the cuto% )ehaviour
asse%)l*.
.odi$* the We).con$ig $ile as sho'n )ello'
<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="ServiceBehavior">
<!-- Service nd!oints -->
<end!oint address="" binding="basic"tt!Binding" contract="#Service"
behaviorConfiguration="Silverlight$aultBehavior">
<!--
%!on de!loyment& the follo'ing identity element should be removed
or re!laced
to reflect the identity under 'hich the de!loyed service runs. #f
removed&
(C$ 'ill infer an a!!ro!riate identity automatically.-->
<identity>
<dns value="localhost")>
<)identity>
<)end!oint>
<end!oint address="me*" binding="me*"tt!Binding"
contract="#Metadata*change")>
<)service>
<)services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- +o avoid disclosing metadata information& set the value belo' to
false and
remove the metadata end!oint above before de!loyment -->
<serviceMetadata htt!,etnabled="true")>
<!-- +o receive e*ce!tion details in faults for debugging !ur!oses&
set the value
belo' to true. Set to false before de!loyment to avoid disclosing
e*ce!tion
information -->
<service-ebug include*ce!tion-etail#n$aults="false")>
<)behavior>
<)serviceBehaviors>
<end!ointBehaviors>
<behavior name="Silverlight$aultBehavior">
<silverlight$aults)>
<)behavior>
<)end!ointBehaviors>
<)behaviorss=.BlueCode/>>
<e*tensions>
<behavior*tensions>
<add name="silverlight$aults"
ty!e="Silverlight0(C$0$aultBehavior.Silverlight$aultBehavior&
Silverlight0(C$0$aultBehavior& 1ersion=2.3.3.3& Culture=neutral&
4ublic5ey+o6en=null")>
<)behavior*tensions>
<)e*tensionss=.BlueCode/>>
<)system.serviceModel>
Step /: Create the an* sa%ple silverlight application as 0Silverlight_WCF_E(ception1 and add
this WCF service as Service 2e$erence.
url: http:33localhost3.athService3Service.svc
Step 4: Add a )utton to the .ain5age.(a%l and call the WCF %ethod as sho'n )elo'
4rivate Sub Button0Clic67By1al sender 8s System.9b:ect&
By1al e 8s System.(indo's.;outedvent8rgs<
-im !ro*y 8s =e' Service4ro*y.ServiceClient
8dd"andler !ro*y.8ddCom!leted& 8ddress9f 8dd9!erationCom!leted
!ro*y.8dd8sync7>& ?<
nd Sub
4rivate Sub 8dd9!erationCom!leted7By1al sender 8s 9b:ect&
By1al e 8s
Service4ro*y.8ddCom!letedvent8rgs<
#f e.rror #s=ot =othing +hen
MessageBo*.Sho'7e.rror.Message<
lse
MessageBo*.Sho'7e.;esult<
nd #f
nd Sub
Step 6: Output 'ill loo7 li7e this
Conclution: 8his article e(plains a)out handling the e(ception in Silverlight application $ro%
WCF
Custom message header
Attachment*
Custom'essage6eader.<ip
,is article e5plains about customi<ing te wcf message flowing between service and client.
,ere are certain scenario in wic you to pass some information from client to service, but not as
parameter in operation contracts. +5ample, logging system at te service we need to log user or
macine information, wic made re2uest to te service. In tis kind of scenario we sould not pass
user or macine information as parameter in operation contract. Instead we can pass te information
troug message flowing between client and service vice versa. ,e information we need to send
can be appended wit message eader and it can be received at te server side.
;et as create sample service and client application, in wic client will send S=ser nameT
information troug re2uest message and service will respond wit confirmation message.
I ave created 'at service wit 0dd and %ubtract functionality. Client consuming tis service will
send is user name information as string wit re2uested message. )nce re2uest reaced te service,
it will read te information from te message eader and display using console window. Wen
service responding to te client, along wit operation result, it will also send confirmation message
to client troug message eader.
!tep 1* Create 0MathService interface decorated wit %ervice and )perational contract attribute
I'at%ervice.vb
<ServiceContract./> B
8ublic $nterface $MathService
<5perationContract./> B
,unction 3dd.ByQal a 3s $nteger2 ByQal b 3s $nteger/ 3s $nteger
<5perationContract./> B
,unction Subtract.ByQal a 3s $nteger2 ByQal b 3s $nteger/ 3s $nteger
(nd $nterface
!tep "*In tis class, we ave implemented 0dd and %ubtract functionality.
(rint.eCuested>serIDAB metod will read te S=serI:T message eader from incoming message
using )perationConte5t. ,is =ser information is displayed in console window.
!end.esponseWith-essageAB metod will send a confirmation message to te client as 'essage
eader troug )peration conte5t.
'at%ervice.vb
8ublic Class MathService
$mplements $MathService
8ublic ,unction 3dd.ByQal a 3s $nteger2 ByQal b 3s $nteger/ 3s $nteger
$mplements $MathService.3dd
N)his method call %ill retrive message send from client using
Message&eader
8rint7eEuested-ser$*./
N)his method call %ill send message to client using Message&eader
Send7esponse4ithMessage./
7eturn a 9 b
(nd ,unction
8ublic ,unction Subtract.ByQal a 3s $nteger2 ByQal b 3s $nteger/ 3s $nteger
$mplements $MathService.Subtract
N)his method call %ill retrive message send from client using
Message&eader
8rint7eEuested-ser$*./
N)his method call %ill send message to client using Message&eader
Send7esponse4ithMessage./
7eturn a D b
(nd ,unction
8rivate Sub 8rint7eEuested-ser$*./
*im user$* 3s String = String.(mpty
N7ead the message header using "Lame" and "LameSpace"
user$* = 5perationConte+t.Current.$ncomingMessage&eaders
.'et&eader.5f String/."-ser$*"2 "ns"/
Console.4rite6ine."7eEuested user: " 9 user$*/
(nd Sub
8rivate Sub Send7esponse4ithMessage./
NCreating ne% message header %ith "Content" value assigned in
constructor
*im mess 3s Le% Message&eader.5f String/.")his is sample message from
service"/
N3ssigning Lame and LameSpace to the message header value at server side
*im header 3s System.ServiceModel.
Channels.Message&eader =
mess.'et-ntyped&eader."ServiceMessage"2 "ns"/
N3dding message header %ith 5perationConte+t
N%hich %ill be received at the client side
5perationConte+t.Current.5utgoingMessage&eaders.3dd.header/
(nd Sub
(nd Class
!tep 5* 6osting te 'at%ervice using console application
'y%ervice6ost.vb
Module MyService&ost
Sub Main./
N&osting the Math service using console application
*im host 3s Le% Service&ost.'et)ype.MyService.MathService//
host.5pen./
Console.4rite6ine."Service is running... 8ress to e+it."/
Console.7ead6ine./
(nd Sub
(nd Module
Web.Config
<system.serviceModel>
<services><service name="MyService.MathService"
behaviorConfiguration="MyServiceBehavior">
<endpoint address ="MathService" binding="basic&ttpBinding"
contract="MyService.$MathService">
<endpoint address="me+" binding="me+&ttpBinding"
contract="$Metadata(+change">
<host>
<base3ddresses>
<add base3ddress="http:localhost:!"#"MyService">
<base3ddresses>
<host>
<service>
<services>
<behaviors>
<serviceBehaviors >
<behavior name ="MyServiceBehavior">
<serviceMetadata http'et(nabled ="true">
<service*ebug include(+ception*etail$n,aults =")rue">
<behavior>
<serviceBehaviors>
<behaviors>
<system.serviceModel>
!tep 6* Created console client application wic add S=serI:T as message eader to service using
)peration conte5t before calling 0dd() functionality. )nce te response is received from te
service, it is trying to read te confirmation message from service using )peration conte5t.
Sub Main./
NCreating pro+y class for service
*im pro+y 3s $MathService = Lothing
pro+y = Channel,actory.5f $MathService/.CreateChannel.Le%
Basic&ttpBinding./2
Le%
(ndpoint3ddress."http:localhost:!"#"MyServiceMathService"//
N6ifetime of 5perationConte+tScope defines the scope for
5perationConte+t.
*im scope 3s 5perationConte+tScope = Lothing
scope = Le% 5perationConte+tScope.pro+y/

NCreating ne% message header %ith "Content" value assigned in
constructor
*im mess 3s Le% Message&eader.5f String/
.System.Security.8rincipal.4indo%s$dentity.'etCurrent./
.Lame/
N3ssigning Lame and LameSpace to the message header value at client side
*im header 3s System.ServiceModel.Channels.Message&eader
= mess.'et-ntyped&eader."-ser$*"2 "ns"/
N3dding message header %ith 5perationConte+t
N%hich %ill be received at the server side
5perationConte+t.Current.5utgoingMessage&eaders.3dd.header/
NMaMing service call
Console.4rite6ine."Sum of <"=2<G==<H="2 G2 H2 pro+y.3dd.G2 H//
N*isplaying confrimation message from service
Console.4rite6ine."7esponse Message: " 9 5perationConte+t.Current.
$ncomingMessage&eaders.'et&eader.5f String/
."ServiceMessage"2 "ns"//
Console.7ead6ine./
(nd Sub
(nd Module
<ServiceContract./> B
8ublic $nterface $MathService
$nherits $ClientChannel
<5perationContract./> B
,unction 3dd.ByQal a 3s $nteger2 ByQal b 3s $nteger/ 3s $nteger
<5perationContract./> B
,unction Subtract.ByQal a 3s $nteger2 ByQal b 3s $nteger/ 3s $nteger
(nd $nterface
!tep 2* &un te 'y%ervice6ost
!tep 4* &un te 'yClient0pplication
-elow figure sows te message flowing between service and client
Client application output
Console hosted service output screen
Conclusion*
,is article e5plain about customi<ing te wcf message eader
Introdution to WCF 6.#
,is article e5plains about te new features introduced in WCF 3.$.
."et framework comes wit new features and improved areas of WCF. It was mainly focused on
simplifying te developer e5perience, enabling more communication scenario and providing ric
integration wit WWF.
,e following items specifies te new features of WCF 3.$
!implified configuration
,is new feature sows simplification of WCF configuration section by providing default endpoint,
binding and beavior configuration. It is not mandatory to provide endpoint wile osting service.
%ervice will automatically create new endpoint if it does find any endpoint wile osting service.
,ese canges make it possible to ost configuration-free services.
Discover& service
,ere are certain scenario in wic endpoint address of te service will be keep on canging. In tat
kind of scenario, client wo consume tis service also need to cange te endpoint address
dynamically to identify te service. ,is can be acieved using W%-:iscovery protocol.
.outing service
,is new feature introduces routing service between client and actual business service. ,is
intermediated service 0ct as broker or gateways to te actual business services and provides
features for content based routing, protocol bridging and error andling
.'!T !ervice
,ere are few features elps wile developing &+%,ful service.
0utomatic elp page tat describes &+%, services to consumer
%upport for declarative 6,,7 catcing
Wor/flow service
Improves development e5perience
+ntire service definition can be define in 10';
6osting workflow service can be done from .5aml5 file, witout using .svc file
Introduce new SConte5tT bindings like -asic6ttpConte5t-inding, W%6ttpConte5t-inding,
or "et,cpConte5t-inding
In ."et3.$, 'or:flowServiceHost class for osting workflow services was redesigned and it
is available in System.ServiceModel.-ctivities assembly. In ."et#.N, 'or:flowServiceHost
class is available in System.'or:flowServices assembly
"ew messaging activities %end&eply and &eceive&eply are added in ."et3.$
Conclusion*
,is article e5plain new featues introduced in WCF 3.$

Das könnte Ihnen auch gefallen