Introduction of WCF

hushedsnailInternet and Web Development

Nov 13, 2013 (4 years and 7 months ago)

282 views

Introduction of WCF

Windows Communication Foundation (WCF) is an SDK for developing and deploying services
on Windows.and it (Code named Indigo) is a programming platform


and


runtime system
for building, configuring and deploying network
-
distributed services.WCF provides a runtime
environment for your services, enabling you to expose CLR types as services, and to
consume other services as CLR types. It is the latest service o
riented technology;
Interoperability is the fundamental characteristics of WCF. Windows Communication
Foundation (WCF) is unified programming model provided in .Net Framework 3.0. WCF is a
combined features of Web Service, Remoting, MSMQ and COM+. WCF prov
ides a common
platform for all .NET communication.

different technology combined to form WCF.




WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on operation systems that
support it. Presently this list consists
of Windows Vista (client and server), Windows XP SP2,
and Windows Server 2003 SP1 or their later versions

Advantage



Its made of a lot of different components, so you can create new components for
security, transport, authentication



In WCF, there is no need

to make much change in code for implementing the
security model and changing the binding. Small changes in the configuration will
make your requirements.



Its faster than ASMX



Supports Scaling/Load Balancing



WCF has integrated logging mechanism, changing t
he configuration file settings will
provide this functionality. In other technology developer has to write the code.



Its Interoperability, for java, and more.



WCF is interoperable with other services when compared to .Net Remoting,where the
client and
service have to be .Net



WCF services provide better reliability and security in compared to ASMX web
services.

Disadvantages

A drawback would be that, WCF is Microsoft's implementation of SOA and hence its APIs are
solely controlled by MS which makes inter
operability a bit difficult. Also, to deploy WCF
apps, you will need more underlying hardware resources on the platform on which the WCF
applications will be running, since there is an additional layer of abstraction to deal with.

Features of WCF

Workflow Services

Workflow Service explains


how to create and configure workflow services.


Endpoints: Addresses, Bindings, and Contracts

Explainhow to control multiple aspects of your service.


Data Transfer and Serialization

Explain how serialization

of data can be tailored for interoperation or future compatibility.


Sessions, Instancing, and Concurrency

Explain the instancing and session modes of WCF and how to select the right mode for your
application.


Transports in Windows Communication Foundat
io
n

Explain how to configure the transport layer, the lowest level of the channel stack.


Queues and Reliable Sessions

Explain queues, which store messages from a sending application on behalf of a receiving
application and later forward these messages t
o the receiving application.


Transactions

Explains how to created transacted operations that can be rolled back if needed.


Windows Communication Foundation Security

Explain how WCF security helps you to create applications that have confidentiality and

integrity. Authentication and authorization are also available, as are auditing features.


Peer
-
to
-
Peer Networking

Details how to create peer services and clients.


Metadata

Explainmetadata architecture and formats.


Clients

Explain how to create a var
iety of clients that access services.


Hosting

Explain hosting. A service can be hosted by another application, or it can be self
-
hosted.


Interoperability and Integration

Explain how to use WCF to extend your existing logic rather than having to rewrite

it if you
have a substantial investment in component
-
based application logic hosted in COM+.


WCF Web HTTP Programming Model

Explainthe WCF Web Programming Model that allows developers to expose WCF service
operations to non
-
SOAP endpoints.


WCF Syndicat
ion

Explainsupport to easily expose syndication feeds from a WCF service.


AJAX Integration and JSON Support

Explainsupport for ASP.NET Asynchronous JavaScript and XML (AJAX) and the Javascript
Object Notation (JSON) data format to allow WCF services to
expose operations to AJAX
clients.


WCF Discovery

Explainsupport to enable services to be discoverable at runtime in an interoperable way
using the WS
-
Discovery protocol.


Routing

Explainthe routing service.

WCF Architecture


There are five layers:
-

1)A
pplication

2)Contracts

3)Service Runtime

4)Messaging

5)Activation and hosting

Contracts

Contracts layer are second layer of the wcf architecture. Developer will directly use this
contract to develop the service. We are also going to do the same now.

i)
Service contract

-
It explains


about the operation that service can provide.

ii) Data contract

-

It explains


the custom data type which is exposed to the client and defines the data
types, are passed to and from service. Data types like int, string are i
dentified by the client
because it is already mention in XML schema definition language document, but custom
created class or datatype cannot be identified by the client e.g. Employee data type. By
using DataContract we can make client aware that we are us
ing Employee data type for
returning or passing parameter to the method.

iii) Message Contract

-

Default SOAP message format is provided by the WCF runtime for communication between
Client and service. If it is not meeting your requirements then we can cre
ate our own
message format. This can be achieved by using Message Contract attribute.

iv) Policies and Binding

-

It


specify

conditions required to communicate with a service e.g security requirement to
communicate with service, protocol and encoding used for binding.

Service Runtime

-

It contains the behaviors that occur during runtime of service.



Error Behavior
-

Specifies wh
at occurs, when internal error occurs on the service.



Dispatch Behavior
-

Controls how a message is processed by the WCF Infrastructure.



Throttling Behavior
-

Controls how many messages are processed.



Metadata Behavior
-

Tells how and whether metadata is av
ailable to outside world.



Instance Behavior
-

Specifies how many instance of the service has to be created
while running.



Transaction Behavior
-

Enables the rollback of transacted operations if a failure
occurs.

Messaging

It is composed of channels and


ch
annel is a component that processes a message in some
way, for example, by authenticating a message. Channels are the core abstraction for
sending message to and receiving message from an Endpoin and


set of channels is also
known as a channel stack.t. Bro
adly we can categories channels as



Transport Channels:
Handles sending and receiving message from network.
Protocols like HTTP, TCP, name pipes and MSMQ.



Protocol Channels:
Implements SOAP based protocol by processing and possibly
modifying message. E.g.
WS
-
Security and WS
-
Reliability.

Activation and Hosting

Services can be hosted or executed, so that it will be available to everyone accessing from
the client. WCF serv ice can be hosted by following mechanism



IIS

Internet information Service provides
number of advantages if a Service uses Http as
protocol. It does not require Host code to activate the service, it automatically
activates service code.



Windows Activation Service

(WAS) is the new process activation mechanism that ships with IIS 7.0. In a
ddition
to HTTP based communication, WCF can also use WAS to provide message
-
based
activation over other protocols, such as TCP and named pipes.



Self
-
Hosting

WCF service can be self hosted as console application, Win Forms or WPF application
with graphica
l UI.



Windows Service

WCF can also be hosted as a Windows Service, so that it is under control of the
Service Control Manager (SCM)

Difference between WCF and Web service

Web service is a part of WCF. WCF provides


much more flexibility and portability to

develop
a service when comparing to web service.

Features

Web Service

WCF

Hosting

It can be hosted in IIS

It can be hosted in IIS, windows
activation service, Self
-
hosting, Windows
service

Programming

[WebService] attribute has to be
added to the class

[ServiceContraact] attribute has to be
added to the class

Model

[WebMethod] attribute represents
the method exposed to client

[OperationContract] attribute represents
the method exposed to client

Operation

One
-
way, Request
-

Response are
the different ope
rations supported
in web service

One
-
Way, Request
-
Response, Duplex
are different type of operations
supported in WCF

XML

System.Xml.serialization name
space is used for serialization

System.Runtime.Serialization
namespace is used for serialization

Encoding

XML 1.0, MTOM(Message
Transmission Optimization
Mechanism), DIME, Custom

XML 1.0, MTOM, Binary, Custom

Transports

Can be accessed through HTTP,
TCP, Custom

Can be accessed through HTTP, TCP,
Named pipes, MSMQ,P2P, Custom

Protocols

Security

Secur
ity, Reliable messaging,
Transactions




WCF Contracts

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

There are four Contracts:



Service contracts:
Define


which operations the client can perform on the service.
Service contracts are the subject of the next chapter, but are used extensively in
every chapter in this book.



Data contracts:

Define which data types are passed to and from the service. WCF
defines implicit contracts for built
-
in types such as
int

and
string
, but you can easily
define explicit opt
-
in data contracts for custom types



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



Message contracts:
Allow the service to interact directly with messages. Message
contracts can be typed or untyped, and are useful in interoperability cases and when
there is

an existing message format you have to comply with.



WCF Service



A service
-
oriented application (SOA) aggregates services into a single logical
application similar to the way a component
-
oriented application aggregates
components or an object
-
oriented
application aggregates objects and ervice
-
orientation (SO) is an abstract set of principles and best practices for building SO
applications .The services can be local or remote, developed by multiple parties using
any technology, versioned independently, a
nd even execute on different timelines.
Inside a service, you will find concepts such as languages, technologies, platforms,
versions, and frameworks, yet between services, only prescribed communication
patterns are allowed.The client of a service is merel
y the party consuming its
functionality. The client can be literally anythinga Windows Forms class, an ASP.NET
page, or another service



Clients and services interact by sending and receiving messages. Messages may
transfer directly from client to service o
r via an intermediary. With WCF, all
messages are SOAP messages.the messages are independent of transport
protocolsunlike Web services, WCF services may communicate over a variety of
transports, not just HTTP. WCF clients may interoperate with non
-
WCF serv
ices, and
WCF services can interact with non
-
WCF clients



Services' Execution Boundaries



With WCF, the client never interacts with the service directly, even when dealing with
a local, in
-
memory service. The client always uses a proxy to forward the call to

the
service. The proxy exposes the same operations as the service, plus some proxy
-
management methods. WCF allows the client to communicate with the service across
all execution boundaries.






Service contracts

The
ServiceContractAttribute

is defined as:

[AttributeUsage(AttributeTargets.Interface|AttributeTargets.Class,


Inherited = false)]

public sealed class ServiceContractAttribute : Attribute

{


public string Name


{get;set;}


public string Namespace


{get;set;}


//More member
s

}

Defining and implementing a service contract


[ServiceContract]

interface
IMyContract

{


[OperationContract]


string
show(
string
text);



//Will not be part of the contract


string
show(
string
text);

}

class
MyService : IMyContract

{


public string
show
(
string
text)


{


return
"Hello "
+ text;


}


public string
show(
string
text)


{


return
"Cannot call this method over
WCF"
;


}

}







WCF


Addresses

WCF address provides two important elements:

1)
The location of the service
:
-
The location portion of the address indicates the name of
the target machine, site, or network; a communication port, pipe, or queue; and an optional
specific path or URI. A URI is a Universal Resource Identifier, and can be a
ny unique string,
such as the service name or a GUID.

2)
The transport protocol

or transport schema used to communicate with the service.

WCF transport schemas

WCF 1.0 supports the following transport schemas

1)HTTP

2)TCP

3)Peer network

4)IPC

(Inter
-
Process Communication over named pipes)

5)MSMQ

Addresses always have the following format:

[base address]/[optional URI]

The base address is always in this format:

[transport]://[machine or domain][:optional port]

EXAMPLE
-

http://localhost:8001

htt
p://localhost:8001/MyService

net.tcp://localhost:8002/MyService

net.pipe://localhost/MyPipe

net.msmq://localhost/private/MyService

The way to read an address such as

http://localhost:8001


is like this: "Using HTTP, go

to the machine called localhost,
where on port 8001 someone is waiting for my calls."

If there is also a URI such as:

http://localhost:8001/MyService

http://localhost:8001/MyService

then the address would re
ad as follows: "Using HTTP, go to the machine called localhost,
where on port 8001 someone called

MyService is waiting for my calls."

1) HTTP Addresses:

HTTP addresses use http for transport, and can also use https for secure transport. You
typically use

HTTP addresses with outward
-
facing

Internet
-
based services, and can specify a port such as:

http://localhost:8001

When the port number is unspecified, it defaults to 80. Similar to TCP addresses, two HTTP
addresses from the same host can share a port, ev
en on the same machine.

2)TCP

TCP addresses use
net.tcp

for the transport, and typically include a port number such as:

net.tcp://localhost
:8002
/MyService

When a port number is not specified, the TCP address defaults to port 808:

net.tcp://localhost/MyService

It is possible for two TCP addresses (from the same host, which will be discussed more later
on in this chapter) to share a port:

net.tcp://localhost
:8002
/MyService

net.tcp://localhost
:8002
/MyOtherService

3) IPC Addresses
(Inter
-
Process Communication over named pipes)

IPC addresses use
net.pipe

for transport, to indicate the use of the Windows named pipe
mechanism. In WCF, services that use named pipes can only accept calls from the same
machine. Consequently, you must spec
ify either the explicit local machine name or
localhost

for the machine name, followed by a unique string for the pipe name:

net.pipe://localhost/MyPipe

4) MSMQ Addresses

MSMQ addresses use
net.msmq

for transport, to indicate the use of the Microsoft Messa
ge
Queue (MSMQ). You must specify the queue name. When you're dealing with private
queues, you must specify the queue type, but that can be omitted for public queues:

net.msmq://localhost/private/MyService

net.msmq://localhost/MyService

5) Peer Network Add
ress

Peer network addresses use
net.p2p

for transport, to indicate the use of the Windows peer
network transport. You must specify the peer network name as well as a unique path and
port. Using and configuring peer networks is beyond the scope of this book
, and you will see
very little mention of peer networks in subsequent chapters.

WCF Bindings

A binding explains


the transport (such as HTTP or TCP) and the encoding being used (such
as text or binary). A binding can contain binding elements that specify d
etails like the
security mechanisms used to secure messages, or the message pattern used by an
endpoint.

WCF defines nine standard bindings
:

Basic binding:

Defined by the BasicHttpBinding class, this is designed to expose a WCF
service as a legacy ASMX web

service, so that old clients can work with new services. When
used by the client, this binding enables new WCF clients to work with old ASMX services.

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

Peer network binding:
Defined by the NetPeerTc
pBinding class, this uses peer networking
as a transport. The peer network
-
enabled client and services all subscribe to the same grid
and broadcast messages to it. Peer networking is beyond the scope of this book since it
requires an understanding of grid
topology and mesh computing strategies.

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

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

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

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

MSMQ binding:
Defined by the NetMsmqBinding class, this uses MSMQ for transport and is
designed to offer support for disconnected queued calls. MSMQ integration bin
ding

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

Format and Encoding Binding

Each of the standard bindings uses different transport and encodin
g

Name

Transport

Encoding

Interoperable

BasicHttpBinding

HTTP/HTTPS

Text, MTOM

Yes

NetTcpBinding

TCP

Binary

No

NetPeerTcpBinding

P2P

Binary

No

NetNamedPipeBinding

IPC

Binary

No

WSHttpBinding

HTTP/HTTPS

Text, MTOM

Yes

WSFederationHttpBinding

HTTP/HTTPS

Text, MTOM

Yes

Name

Transport

Encoding

Interoperable

WSDualHttpBinding

HTTP

Text, MTOM

Yes

NetMsmqBinding

MSMQ

Binary

No

MsmqIntegrationBinding

MSMQ

Binary

Yes

Choosing a Binding

Choosing a binding for your service should follow the decision
-
activity diagram




WCF Hosting

WCF

service


has to be hosted in windows process called as host process. Single host
process can host multiple servers and same service type can be hosted in multiple host
process

There are mainly four different way of hosting the WCF service.

1)IIS hosting

2
)Self hosting

3)Windows Activation Service

4)Windows Service

The WCF host architecture


The WCF context is conceptually similar to the Enterprise Services context or the .NET
context
-
bound object context Multiple hosting and protocols supported by WCF. Mi
crosoft
has introduced the WCF concept in order to make distributed application development and
deployment simple.

Hosting Environment

Supported protocol

Windows console and form application

HTTP,net.tcp,net.pipe,net.msmq

Windows service application
(formerly known as NT services)

HTTP,net.tcp,net.pipe,net.msmq

Web server IIS6

http, wshttp

Web server IIS7
-

Windows Process Activation Service (WAS)

HTTP,net.tcp,net.pipe,net.msmq

A summary of hosting options and supported features.

Feature

Self
-
Host
ing

IIS Hosting

WAS Hosting

Executable Process/ App
Domain

Yes

Yes

Yes

Configuration

App.config

Web.config

Web.config

Activation

Manual at startup

Message
-
based

Message
-
based

Idle
-
Time Management

No

Yes

Yes

Health Monitoring

No

Yes

Yes

Process
Recycling

No

Yes

Yes

Management Tools

No

Yes

Yes



Binding and Reliability in WCF

WCF make a distinction between transport reliability and message reliability.
Transport
reliability

describes


point
-
to
-
point guaranteed delivery at the network packet
level, as well
as guarantees the order of the packets. Transport reliability is not resilient to dropping
network connections and a variety of other communication problems.

Message reliability deals with managing the connection itself via connection verifi
cation and
cleanup when no longer needed also deals with reliability at the message level independent
of how many packets are required to deliver the message and


provides for end
-
to
-
end
guaranteed delivery and order of messages, regardless of how many int
ermediaries are
involved, and how many network hops are required to deliver the message from the client
to the service.

Message reliability is based on an industry standard for reliable message
-
based
communication that maintains a session at the transport

level.Message reliability offers
retries in case of transport failures such as dropping a wireless connection; it automatically
deals with congestion, message buffering, and flow control; and it can adjust the number of
messages accordingly.

Reliability
and binding

Name

Supports
reliability

Default
reliability

Supports
ordered

Default
ordered

BasicHttpBinding

No

N/A

No

N/A

NetTcpBinding

Yes

Off

Yes

On

NetPeerTcpBinding

No

N/A

No

N/A

NetNamedPipeBinding

No

N/A (On)

Yes

N/A (On)

WSHttpBinding

Yes

Off

Yes

On

WSFederationHttpBinding

Yes

Off

Yes

On

WSDualHttpBinding

Yes

On

Yes

On

NetMsmqBinding

No

N/A

No

N/A

MsmqIntegrationBinding

No

N/A

No

N/A

Ordered Messages

Message reliability


provides

ordered delivery assurance, which allow messages to be
executed in the order they were sent, not in the order in which they were delivered. It
guarantees that messages are delivered exactly once.

WCF


enable reliability but not ordered delivery, in which

case messages are delivered in
the order in which they were received. The default for all bindings that support reliability is
that when reliability is enabled, ordered delivery is enabled as well.

Enabling reliability with the TCP binding


<
system
.
serviceModel
>


<
services
>


<
service
name
=
"MyService"
>


<
endpoint


address
=
"net.tcp://localhost:8000/MyService"


binding
=
"netTcpBinding"


bindingConfiguration
=
"ReliableTCP"


contract
=
"IMyContract"


/>


</
service
>


</
services
>


<
bindings
>


<
netTcpBinding
>


<
binding
name
=
"ReliableTCP"
>


<
reliableSession
enabled
=
"true"
/>


</
binding
>


</
netTcpBinding
>


</
bindings
>

</
system
.
serviceModel
>







WCF


Channels


Working

We

can


use channels directly to invoke operations on the service without ever resorting to
using a proxy class.

TheChannelFactory<T> class:

The
ChannelFactory<T>

class enables we to create a
proxy on the fly.


public class
contractexample

{


public
Type
ContractType


{get;set;}


//More members

}


public class
ServiceEndpoint

{


public
ServiceEndpoint
(contractexample contract,
Binding
binding,
EndpointAddress
address);


public
EndpointAddress
Address


{
get;set;}


public
Binding Binding


{get;set;}


public
contractexample Contract


{get;}


//More members

}


public abstract class
ChannelFactory
: ...

{


public
ServiceEndpoint
Endpoint


{get;}


//More members

}

public class
ChannelFactory
<T>

:
ChannelFactory
,...

{


public
ChannelFactory
(
ServiceEndpoint
endpoint);


public
ChannelFactory
(
string
configurationName);


public
ChannelFactory
(
Binding
binding,
EndpointAddress
endpointAddress);


public static
T CreateChannel(
Binding
binding,
EndpointAddress
endpointAddress);


public
T CreateChannel( );


//More Members

}





we


pass


the constructor of
ChannelFactory<T>

with the endpointeither the endpoint name
from the client config file, or the binding and address objects, or a
ServiceEndpoint

object.Use the
CreateChannel( )

method to obtain a reference to the proxy and use its
methods. At the end


close the proxy by either casting it to
IDisposable

and calling the
Dispose( )

method or to
ICommunicationObject

and calling the
Clos
e( )

method:

ChannelFactory<IMyContract> factory = new ChannelFactory<IMyContract>( );


IMyContract proxy1 = factory.CreateChannel( );

using(proxy1 as IDisposable)

{


proxy1.MyMethod( );

}


IMyContract proxy2 = factory.CreateChannel( );

proxy2.MyMethod(
);

ICommunicationObject channel = proxy2 as ICommunicationObject;

Debug.Assert(channel != null);

channel.Close( );

The InProcFactory Class

Class
InProcFactory
, defined as:

public static class InProcFactory

{


public static I CreateInstance<S,I>
( ) where I : class


where S : I;


public static void CloseProxy<I>(I instance) where I : class;


//More members

}

Implementing InProcFactory<T>


public static class
InProcFactoryexample

{


struct
HostRecordst
rustru


{


public
HostRecordstrustru(
ServiceHost
host,
string
address)


{


Host = host;


Address = address;


}


public readonly
ServiceHost
Host;


public readonly string
Address;


}


static readonly
Uri
BaseAddress =
new
Uri
(
"net.pipe://localhost/"
);


static readonly
Binding
NamedPipeBinding;


static
Dictionary
<
Type
,HostRecordstrustru> m_Hosts =
new
Dictionary
<
Type
,HostRecordstrustru>( );



static
InProcFactoryexample( )


{


NetNamedPipeBindi
ng
binding =
new
NetNamedPipeBinding
( );


binding.TransactionFlow =
true
;


NamedPipeBinding = binding;


AppDomain
.CurrentDomain.ProcessExit +=
delegate


{


foreach
(KeyValuePair<
Type
,HostRecordstrustru> pair
in
m_Hosts)


{


pair.Value.Host.Close( );


}



};


}


public static
I CreateInstance<S,I>( ) where I :
class


where S : I


{


HostRecordstrustru HostRecordstrustru = GetHostRecordstrustru<S,I>( );


return
ChannelFactory
<I
>.CreateChannel(NamedPipeBinding,


new
EndpointAddress
(HostRecordstrustru.Address));


}


static
HostRecordstrustru GetHostRecordstru <S,I>( ) where I :
class


where S :
I


{


HostRecordstru HostRecordstru;


if
(m_Hosts.ContainsKey(
typeof
(S)))


{


HostRecordstru = m_Hosts[
typeof
(S)];


}


else


{


ServiceHost
host =
new
ServiceHost
(
typeof
(S), BaseAddress);


string
address = BaseAddress.ToString() + Guid.NewGuid().ToString( );


HostRecordstru =
new
HostRecordstru(host,address);


m_Hosts.Add(
typeof
(S),HostRecordstru);


host.AddServiceEndpoint(
typeof
(I),NamedPipeBinding,address);


host.O
pen( );


}


return
HostRecordstru;


}


public static void
CloseProxy<I>(I instance) where I :
class


{


ICommunicationObject proxy = instance
as
ICommunicationObject;


Debug
.Assert(proxy !=
null
);


proxy.Close( );


}

}






WCF Endpoints

In WCF the relationship between Address, Contract and Binding is called Endpoint. The
Endpoint is the fusion of Address, Contract and Binding. WCF formalizes this relationship in
the form of an endpoint.Every service must have Address that
defines where the service
resides, Contract that defines what the service does and a Binding that defines how to
communicate with the service

Administrative Endpoint Configuration

Configuring an endpoint administratively requires placing the endpoints in t
he hosting
process' config file. For example, given this service definition:

namespace endname

{


[ServiceContract]


interface IMyContract


{...}


class MyService : IMyContract


{...}

}



Example






<
system
.
serviceModel
>


<
services
>


<
service
name
=
"MyNamespace.MyService"
>


<
endpoint


address
=
"http://localhost:8000/MyService/"


binding
=
"wsHttpBinding"


contract
=
"MyNamespace.IMyContract"


/>


</
service
>


</
services
>

</
system
.
serviceModel
>




Multiple endpoints on the same service


<
service
name
=
"MyService"
>


<
endpoint


address
=
"http://localhost:8000/MyService/"


binding
=
"wsHttpBinding"


contract
=
"IMyContract"


/>


<
endpoint


address
=
"net.tcp://localhost:8001/MyService/"


binding
=
"netTcpBinding"


contract
=
"IMyContract"


/>


<
endpoint


address
=
"net.tcp://localhost:8002/MyService/"


binding
=
"netTcpBinding"


contract
=
"IMyOtherContract"


/>

</
service
>








Service
-
side binding configuration


<
system
.
serviceModel
>


<
services
>


<
service
name
=
"MyService"
>


<
endpoint


address
=
"net.tcp://localhost:8000/MyService/"


bindingConfiguration
=
"TransactionalTCP"


binding
=
"netTcpBinding"


contract
=
"IMyContract"


/>


<
endpoint


address
=
"net.tcp://localhost:8001/MyService/"


bindingConfiguration
=
"TransactionalTCP"


binding
=
"netTcpBinding"


contract
=
"IMyOtherContract"


/>


</
service
>


</
services
>


<
bindings
>


<
netTcpBinding
>


<
binding
name
=
"TransactionalTCP"


transactionFlow
=
"true"


/>


</
netTcpBinding
>


</
bindings
>

</
system
.
serviceModel
>






Service
-
side programmatic endpoint configuration


ServiceHost
host =
new
ServiceHost
(
typeof
(MyService));


Binding
wsBinding =
new
WSHttpBinding
( );

Binding
tcpBinding =
new
NetTcpBinding
( );


host.AddServiceEndpoint(
typeof
(IMyContract),wsBinding,


"http://localhost:8000/MyService"
);

host.AddServiceEndpoint(
typeof
(IMyContract),tcpBinding,


"net.tcp://localhost:8001/MyService"
);

host.AddServiceEndpoint(
typeof
(IMyOtherContract),tcpBinding,


"net.tcp://localhost:8002/MyService"
);


host.Open( );



</system.serviceModel>






AddServiceEndpoint( )
-
It
adds a service endpoint to the hosted service with a
specified contract, binding,
and endpoint address.


First WCF Service

WCF programming model support 3 styles of programming :

1.

Declarative programming, in which we can


define attributes

2.

Imperative programming, in which we work with the WCF object model in

code

3.

Configuration
-
based programming, in which we


define


behavior in application
configuration files

Service programs

:

In it defines four element

1.

Contract definitions:
A service


have at least one service contract, and it might
contain multiple service

contracts, data contracts, or message contracts.

2.

Implementation code:

The service contracts in a service need code to implement
their service operations.

3.

Hosting code:

Some code is needed to create and start the service.

4.

Endpoint definitions:

One or
more address "binding" contract endpoints must be
declared.

Before Starting :

This example require the following packages to be installed on your system:

1.

.net framework 3.0 RC1

2.

Windows SDK RC1

Application divided into 3 parts :

A.





Developing the Serv
er application



Step 1
:
Create the application



Step 2 : Create the Service Contracts



Step 3 : Create the Service Implementation Code



Step 4 : Create the Service Host



Step 5 : Create the Service Configurations

B.





Publish the Service MetaData

C.





Create .net Based Client Application



First WCF Service
-
2nd part

A) Developing the Server application

Step 1 : Create the application

1.

Open


your development environment and create a new C# console
application project named server.

2.

Add reference to t
he System.ServiceModel.dll , then add reference to the
System.ServiceModel namespace

3.

Change the name space to EgyAntiques.Store


as the

using

System;

using

System.Collections.Generic;

using

System.Text;

using

System.ServiceModel;




namespace

EgyAntiques.Store

{




}

Step 2 : Create the Service Contracts

1.

Define the interface that will serve as a contract for our application , decorate your
interface with ServiceContract Attribute

2.

Define 2 methods signature as in the following code , those me
thods will serve as
the contract operations , decorate your methods with the OperationContract attribute



[
ServiceContract
]





public

interface

IAntiques





{









[
OperationContract
]









string

DisplayAntiquesList();












[
OperationContract
]









double

GetAntiquePrice(
int

antiqueID);





}



Step 3 : Create the Service Implementation Code

1.

Define AntiquesService Class which will implement the IAntiques interface

2.

Provide Implementation for the 2 methods as in the
following code





public

class

AntiquesService

:
IAntiques





{









public

string

DisplayAntiquesList()









{













string

str =
" 1.A
\
n 2.B
\
n 3.c
\
n 4.D"
;













return

str;









}












public

double

GetAntiquePrice(
int

antiqueID)









{













switch

(antiqueID)













{

















case

1:





















return

100.05;





















break
;

















case

2:





















return

150.00;





















break
;

















c
ase

3:





















return

340.23;





















break
;

















case

4:





















return

1000;





















break
;

















default
:





















return

00.00;





















break
;













}









}





}

Step 4 : Create the Service Host

Add


main method to the class ,which will create a new ServiceHost object and open this
host , the host will not run untill we specify the endpoints


that will allow the other services
to communicate with our A
ntiquesService , this part we will do using configuration files.





static

void

Main(
string
[] args)



{



ServiceHost

sh =
new

ServiceHost
(
typeof
(
AntiquesService
));






try



{



sh.Open(
);



Console
.WriteLine(
"EgyAntiques Store Service opened successfully"
);



Console
.WriteLine(
"Press Enter to terminate EgyAntiques Store Service"
);



Console
.ReadLine();



}



finally




{



sh.Close();

}



Step 5 : Create the Service Configurations

1.

Build your project and make sure that it successfully built

2.

Open the Service Configuration Editor (Tool come with Windows SDK ) and load the
application file , from File Open à
Executable
-

Browse for Server.exe

Click create new service , and specify the service type as
“EgyAntiques.Store.AntiquesService”



4






Specify the Service Contract for the service as “EgyAntiques.Store.IAntiques





5.






Set the communication
mode for HTTP


6.






Set the method of interoperability to Advanced Web service Interoperability , and
set the communication Simplex Communicatio


7.






Left the address field for your endpoint empty in this case the WCF will search for
base addres
s for the service and will consider this address as address for the
endpoint

8.






Click finish , you should see the following result by now







9.






Now click from the left pane the Host Icon ,

then click New to add new base
address for your service , then set the address for your service to


http://r4r
-
03/service




10.


Expand the Endpoints from the left pane and select your end point , then in the
name field write “ep1” this is the name for

your endpoint in will be used to reference
this endpoint configuration from inside code


B . Publish the Service MetaData

1.






Expand from the left pane the Advanced node , then click Service Behaviors node

and click New Service Behavior Configurati
on from the right pane


2.






Set the BehaviorConfiguration name to “MetaDataBehavior” , and click add to add
Behavior element , then select ServiceMetaData


3.






Select the serviceMetaData from the left pane , on the right pane set the HttpGetEn
abled to true and
the HttpGetUrl to
http://r4r
-
03/service


4.






Now Select the EgyAntiques.Store.AntiqueService node from the left pane then
set the Behavior Configuration in the right pane to your Behavior name
“MetaDataBehavior”


6.






Now you can run your service , it should run ok without any errors ,

if everything
is alright you’ll see this screen


:


C . Create .net Based Client Application

1.


Open command shell and navigate to the required folder you need the tool to
generate the files in , then write the following command and hit enter:

Svcutil.
exe
http://localhost:8000/AntiqueService/?wsdl

You should see the following result , and if you got to the folder you had specified for the
tool you will find 2 files (1) AntiquesService.cs (2) out
put.config


2.


Now create new console project name it “client”, set the name space to
“EgyAntiques.Store” , then add reference to the “System.ServiceModel.dll” , finally
add the generated files to your project “AntiquesService.cs” and rename the
configuration file t
o “app.config” then add it to the project ,the result should look like
that

3.


You only need to create proxy object from your generated proxy , then call your
service methods from the proxy , here is the code you need to add to the main
method of your c
lient :













Console
.WriteLine(
"Please press enter to get the list of our antiques :"
);













Console
.ReadLine();













AntiquesClient

client =
new

AntiquesClient
(
"ep1"
);













Console
.Write(client.DisplayAntiquesList());













Console
.WriteLine(
"
\
n
\
n
\
nPlease select your Antique # to know it's price :"
);













Console
.WriteLine(
"Your Antique Price is :
"
+client.GetAntiquePrice(
int
.Parse(
Console
.ReadLine())));













Console
.WriteLine(
"
\
npress enter to termi
nate the program ... "
);












Console
.ReadLine();

4.


Save and compile your application , check if there is errors , if successfully built
, run the server application , then run your client application , you should get the
following result


CODE

FOR SERVER




using
System
;

using
System
.
Collections
.
Generic
;

using
System
.Linq;

using
System
.
Text
;

using
System
.
ServiceModel
;


namespace
EgyAntiques.Store

{


[ServiceContract]



public interface
IAntiques


{



[OperationContract]



string
DisplayAntiquesList();





[OperationContract]



double
GetAntiquePrice(
int
antiqueID);



}


public class
AntiquesService : IAntiques


{



public string
DisplayAntiquesList()


{



string
str =
" 1.A
\
n 2.B
\
n 3.C
\
n 4.D"
;



return
str;



}





public double
GetAntiquePrice(
int
antiqueID)


{



switch
(antiqueID)


{



case
1
:


return
100
.
05
;


break
;


case
2
:


return
150
.
00
;


break
;


case
3
:


return
340
.
23
;


break
;


case
4
:


return
1000
;


break
;


default
:


return
00
.
00
;


break
;




}



}


static void
Main(
string
[] args)


{



ServiceHost
sh =
new
ServiceHost
(
typeof
(AntiquesService));





try


{



sh.Open();



Console
.WriteLine(
"EgyAntiques Store
Service opened successfully"
);



Console
.WriteLine(
"Press Enter to
terminate EgyAntiques Store Service"
);



Consol
e
.ReadLine();



}



finally


{



sh.Close();



}


}


}

}




CODE FOR CLIENT


using
System
;

using
System
.
Collections
.
Generic
;

using
System
.Linq;

using
System
.
Text
;


using
System
.
ServiceModel
;


namespace
EgyAntiques.Store

{


class
Program


{


static void
Main(
string
[] args)


{


Console
.WriteLine(
"Please press enter to get
the list of our antiques :"
);



Console
.ReadLine();



AntiquesClient client =
new
AntiquesClient(
"ep1"
);



Console
.Write(client.DisplayAntiquesList());



Console
.WriteLine(
"
\
n
\
n
\
nPlease select your
Antique # to know it's price :"
);



Console
.WriteLine(
"Your Antique Price is :
"
+
client.GetAntiquePrice(
int
.Parse(
Console
.ReadLine())));



Console
.WriteLine(
"
\
npress enter to terminate
the program ... "
);



Console
.ReadLine();


}


}

}




Data Contract Hierarchy

Data contract class can


be

the subclass of another data contract class. Since


the
DataContract

attribute is not inheritable so WCF requires that every level in the class
hierarchy explicitly opt in for a given data contract.


[DataContract]

class
Contact

{


[DataMember]


publi
c string
FtName;



[DataMember]


public string
LName;

}

[DataContract]

class
Customer : Contact

{


[DataMember]


public int
CNumber;

}


1.Known Types

The
KnownType

attribute allows you to designate acceptable subclasses for the data
contract:


[DataContract]

[KnownType(
typeof
(Customer))]

class
Contact

{...}


[DataContract]

class
Customer : Contact

{...}





The KnownType attribute includes the subclass in the metadata so that the client will have
its own definition of the subclass and will be
able to pass the subclass instead of the base
class. Using the base class, all contracts and operations are


affected by The KnownType
attribute , across all services and endpoints on the host side and


allowing it to accept
subclasses instead of base clas
ses. If the client also applies the KnownType attribute on its
copy of the base class, it can in turn receive the known subclass back from the service.

2. Service Known Types

WCF also provides the
ServiceKnownTypeAttribute
, defined as:


[AttributeUsage(Att
ributeTargets.Interface|


AttributeTargets.Method |


AttributeTargets.Class,


AllowMultiple =
true
)]

public sealed class
ServiceKnownTypeAttribute
:
Attribute

{


public
ServiceKnownTypeAttribute
(
Type
type);


//More members

}




Instead of using the KnownType attribute on the base data contract we


can

apply the
ServiceKnownType attribute on a specific operation on the service side. Then, only that
operation (across all supporting services) can accept the known subclass:


[DataContract]

class
Contact

{...}


[DataContract]

class
Customer : Contact

{...}


[ServiceContract]

interface
IContactManager

{


[OperationContract]


[ServiceKnownType(
typeof
(Customer))]


void
AddContact(Contact contact);



[OperationContract]


Contact[] GetContacts();

}


3. Multiple Known Types

Tthe
KnownType

and the
ServiceKnownType

attributes both


can be applied


multiple times
to inform WCF about as many known types as required:


[DataContract]

class
Contact

{...}


[DataContract]

class
Customer : Contact

{...}


[DataContract]

class
Person : Contact

{...}


[ServiceContract]

[ServiceKnownType(
typeof
(Customer))]

[ServiceKnownType(
typeof
(Person))]

interface
IContactManager

{...}



4. Configuring Known Types

The main disadvantage


of

the known types attributes is that they require the service or the
client to know in advance about all possible subclasses the other party may want to use.
Adding a new subclass necessitates changing the code, recompiling, and redeploying. To
alleviate th
is, WCF lets you configure the known types in the service's or client's config file.


<system.runtime.serialization>


<dataContractSerializer>


<declaredTypes>


<add type =
"Contact,Host,Version=1.0.0.0,Culture=neutral,



PublicKeyToken=
null
">


<knownType type =
"Customer,MyClassLibrary,Version=1.0.0.0,


Culture=neutral,PublicKeyToken=
null
"/>


</add>


</declaredTypes>


</dataContractSerializer>

<
/system.runtime.serialization>





5. Object and Interfaces

The base type of a data contract class or a struct can be an interface:




Interface IContact

{


string
FirstName


{get;set;}


string
LastName


{get;set;}

}

[DataContract]

class
Contact :

IContact

{...}


You can use such a base interface in your service contract or as a data member in a data
contract if you use the ServiceKnownType attribute to designate the actual data type:


[ServiceContract]

[ServiceKnownType(
typeof
(Contact))]

interface
IContactManager

{


[OperationContract]


void
AddContact(IContact contact);



[OperationContract]


IContact[] GetContacts();

}




Data Contract Equivalence

Two data contracts are considered
equivalent


if

they have the same wire
representation means


if they have the same schema. This can be the case
if they define the same type (but not necessarily the same version of the
type) or if the two data contracts refer to two different types with the
same data c
ontract and data member names. Equivalent data contracts are
interchangeable: WCF will let any service that was defined with one data
contract operate with an equivalent data contract.

these two data contracts are equivalent


[DataContract]

struct
Contact

{


[DataMember]


public string
FirstName;



[DataMember]


public string
LastName;

}

[DataContract(Name =
"Contact"
)]

struct
Person

{


[DataMember(Name =
"FirstName"
)]


public string
Name;



[DataMember(Name =
"LastName"
)]


public string
Surname;

}




Serialization Order

Equivalent data contracts must serialize and deserialize their members in the same order

when serializing a
Customer

instance, defined as:

[DataContract]

class Contact

{


[DataMember]


public string FName;



[DataMember]


public string LName;

}

[DataContract]

class Customer : Contact

{


[DataMember]


public int CNumber;

the members will be serialized in the following order:
FName
,
LName
,
CNumber
.

The problem


is that combining data contract hierarchy
with aliasing contracts and members
might break the serialization order

To resolve this conflict,we


provide WCF with the order of serialization by setting the
Order

property of the
DataMember

attribute. The
Order

property defaults to
-
1, meaning the
defau
lt WCF ordering, but you can assign to it values indicating the required order:

[DataContract(Name = "Customer")]

public class Person

{


[DataMember(Name = "FirstName",
Order = 1
)]


public string Name;



[DataMember(Name = "LastName",
Order = 2
)]


pu
blic string Surname;



[DataMember,
Order = 3
)]


public int CustomerNumber;


Data Contract Versioning

WCF needs to enable both backward and forward compatibility, without even sharing types
or version information.


There are three main versioning
scenarios:



New members



Missing members



Round tripping, where a new version is passed to and from an old version, requiring
both backward and forward compatibility

By default, data contracts are version tolerant and will silently ignore incompatibilities.

1
. New Members

Both the service and the client can accept data with new members that were not part of
original contract when

the new members can


simply be ignored by
DataContractSerializer

when deserializing the
type.


For example, the service may be bui
lt against this data contract:


[DataContract]

struct
Contact

{


[DataMember]


public string
FirstName;



[DataMember]


public string
LastName;

}


and yet the client may send it this data contract instead:


[DataContract]

struct
Contact

{


[DataMember]


public string
FirstName;



[DataMember]


public string
LastName;



[DataMember]


public string
Address;

}





2. Missing Members

Missing members are initialized to their default value


/////////////////////////// Service Side
//////////////////////////////

[DataContract]

struct
Contact

{


[DataMember]


public string
FName;



[DataMember]


public string
LName;



[DataMember]


public string
Address;

}


[ServiceContract]

interface
IContactManager

{


[OperationContract]


void
AddContact(Contact contact);


...

}


class
ContactManager : IContactManager

{


public void
AddContact(Contact contact)


{


Trace
.WriteLine(
"First name = "
+ contact.FirstName);


Trace
.WriteLine(
"Last name = "
+
contact.LastName);


Trace
.WriteLine(
"Address = "
+ (contact.Address ??
"Missing"
));


...


}


...

}

/////////////////////////// Client Side //////////////////////////////

[DataContract]

struct
Contact

{


[DataMember]


public string
FirstNa
me;



[DataMember]


public string
LastName;

}


Contact contact =
new
Contact( );

contact.FirstName =
"Kamal"
;

contact.LastName =
"Ashish"
;


ContactManagerClient proxy =
new
ContactManagerClient( );

proxy.AddContact(contact);


proxy.Close( );


3.
Versioning Round
-
Trip

The versioning tolerance techniques described


so far for ignoring new members and
defaulting missing ones are suboptimal. The versioning tolerance techniques enable a point
-
to
-
point client
-
to
-
service call but have no support for a wi
der
-
scope pass
-
through scenario.





Data Contract Enumerations

Enumerations are always serializable by definition. When you explain


a new enum, there is
no need to apply the
DataContract

attribute on it, and you can freely use it in a data
contract

Using an enum in a data contract

enum
ContactType

{


EName,


EmpPost,


EmpAddress

}

[DataContract]

struct
Contact

{


[DataMember]


public
ContactType ContactType;


[DataMember]


public string
FName;


[DataMember]


public string
LName;

}


Delegates and Data Contracts

All delegate definitions are compiled into serializable classes, and so in theory your data
contract types could contain delegates as member variables:

[DataContract]

class A

{


[DataMember]


public EventHandler ME;

}

or e
ven as events

[DataContract]

class A

{


[
field:
DataMember]


public
event

EventHandler ME;

}



Data Sets and TablesData

The raw
DataSet

and
DataTable

types are serializable, marked with the
Serializable

attribute:

[Serializable]

public

class DataSet : ...

{...}


[Serializable]

public class DataTable : ...

{...}



Type
-
safe data set and data table


[Serializable]

public
partial
class
Exampleofdataset :
DataSet

{


public
ContactsDataTable Contacts


{get;}



[Serializable]


public
partial
class
ContactsDataTable :
DataTable
,IEnumerable


{


public void
AddContactsRow(ContactsRow
row);


public
ContactsRow
AddContactsRow(
string
FirstName,
string
LastName);


//More members


}



public
partial
class
ContactsRow :
DataRow


{


public string
FName


{get;set;}



public string
LName


{get;set;}


//More members


}


//More members

}

public
partial
class
ContactsTableAdapter :
Component

{


public file
Exampleofdataset.ContactsDataTable
GetData( );


//More members

}



Data Contract Generics

Generics are specific to .NET, and using them would avoid


the

service
-
oriented nature of
WCF and


use bounded generic types in your data contracts, as long as you specify the type
parameters in the service contract and as long as the specified type parameters have valid
data contracts.We


cannot define WCF contracts

that rely on generic type parameters.

Using bounded generic types Example

[DataContract]

class MyClass<T>

{


[DataMember]


public T m_MyMember;

}


[ServiceContract]

interface IMyContract

{


[OperationContract]


void MyMethod(MyClass
<int>

obj);

}

Collections

Acollection is any type that supports the
IEnumerable

or
IEnumerable<T>

interfaces. All of
the built
-
in collections in .NET, such as the array, the list, and the stack support these
interfaces.

A data contract can include a collection as a da
ta member, or a service contract can define
operations that interact with a collection directly. Because .NET collections are .NET
-
specific,
WCF cannot expose them in the service metadata, yet because they are so useful, WCF
offers dedicated marshaling rul
es for collections.

Example:


ServiceContract]

interface
IContactManager

{


[OperationContract]


IEnumerable<Contact>
GetContacts( );


...

}

class
ContactManager :
IContactManager

{


List
<Contact> m_Contacts =
new
List
<Contact>( );



public
IEnumerable<Contact>
GetContacts( )


{


return
m_Contacts;


}


...

}




Data Sets and Tables

The raw
DataSet

and
DataTable

types are serializable, marked with the
Serializable

attribute:

[Serializable]

public class DataSet : ...

{...}


[Serializable]

public class DataTable : ...

{...}

We can define valid service contracts that accept or return data tables or data sets:

[DataContract]

struct Contact

{...}


[ServiceContract]

interface IContactManager

{


[OperationContract]


void

AddContact(Contact contact);



[OperationContract]


void AddContacts(
DataTable

contacts);



[OperationContract]


DataTable

GetContacts( );

}

Example of Type
-
safe data set and data table


[Serializable]

public
partial
class
MyDataSet :
DataSet

{


public
ContactsDataTable Contacts


{get;}



[Serializable]


public
partial
class
ContactsDataTable :
DataTable
,IEnumerable


{


public void
AddContactsRow(ContactsRow
row);


public
ContactsRow
AddContactsRow(
string
FirstName,
string
LastName);


//More members


}



public
partial
class
ContactsRow :
DataRow


{


public string
FName


{get;set;}



public string
LName


{get;set;}


//More members


}


//More members

}

public
partial
class
ContactsTableAdapter :
Component

{


public file
MyDataSet.ContactsDataTable
GetData( );


//More members

}




DataTableHelper:
-

It requires is a converter from a data row in the table to the data
contract.
DataTableHelper

also adds some compile
-
time and runtime type
-
safety verification

Exapmle:
Using DataTableHelper


[DataContract]

struct
Contact

{


[DataMember]


public string
FName;



[DataMember]


public string
LNamee;

}

[ServiceContract]

interface
IContactManager

{


[OperationContract]


Contact[] GetContacts( );


...

}

class
ContactManager : IContactManager

{


public
Contact[] GetContacts( )


{


ContactsTableAdapter adapter =
new
ContactsTableAdapter( );


MyDataSet.ContactsDataTable contactsTable =
adapter.GetData( );



Converter<MyDataSet.ContactsRow,Contact>
converter;


Converter =
delegate
(MyDataSet.ContactsRow
row)


{


Contact contact =
new
Contact( );



contact.FName = row.FName;


contact.LNamee = row.LNamee;


return
contact;


};



return
DataTableHelper.ToArray(contactsTable,converter);


}


//Rest of the implementation

}





DataTableHelper.ToArray ( )

DataTableHelper

used for


add some type safety . at compile time,
DataTableHelper

places
constraints on the type parameter
R

to be a data row and


at runtime, the
ToArray( )

method returns an empty array if the table is empty.

ataTableHelper.ToArray( )

use the
myCollection

helper class to invoke the converter on
every row in the table, converting every row to a single
Contact

and returning the resulted
array and It verifies t
hat the type parameter
T

is decorated either with the
DataContract

attribute or the
Serializable

attribute.

Instance Management

Instance management

is the name for a set of techniques used by WCF to bind client
requests to service instances, governing whi
ch service instance handles which client
request.

Behaviors

A
behavior

is a local attribute of a


service that does not affect its communication patterns.
Clients should be unaware of behaviors, and behaviors do not manifest themselves in the
service's bin
ding or published metadata.

Type of Behaviors

Two type of behaviors

1)
ServiceBehaviorAttribute

2)
OperationBehaviorAttribute

1)
ServiceBehaviorAttribute

the
ServiceBehavior

attribute is used to configure the service instance mode.

Example


of

The ServiceBehaviorAttribute used to configure instance context mode


public enum
InstanceContextMode

{


PerCall,


PerSession,


Single

}

[AttributeUsage(AttributeTargets.Class)]

public sealed class
ServiceBehaviorAttribute
:
Attribute
,...

{


public
InstanceContextMode InstanceContextMode


{get;set;}


//More members

}





2)
OperationBehaviorAttribute

The
OperationBehaviorAttribute

is used to configure
operation behaviors
, and it


can

be
applied only on a method that implements a contract operation, never on the operation
definition in the contract itself.

Per
-
Call Services

PerCall service instances are created


with

every method call on the server side and
destroyed also with every method call on the server side and When the service type is
created for
per
-
call activation
, a service instance (the CLR object) exists only while a client
call is in progress .Every clien
t request gets a new dedicated service instance.

Per call activation works as given below
-

1.

The client calls the proxy and the proxy forwards the call to the service.

2.

WCF creates a service instance and calls the method on it.

3.

if the object implements
IDisposable
, WCF calls
IDisposable.Dispose( )

on it then
the method call returns, .

4.


The proxy forwards the call to the service. when The client calls the proxy and

5.

WCF creates an object and calls the method on it.

Configuring Per
-
Call Services

To configu
re a service type as a per
-
call service, We apply the
ServiceBehavior

attribute
with the
InstanceContextMode

property set to
InstanceContextMode.PerCall
:

[ServiceContract]

interface IMyContract

{...}


[ServiceBehavior(InstanceContextMode = InstanceContextM
ode.
PerCall
)]

class MyService : IMyContract

{...}


Per
-
call service and client Example




///////////////////////// Service code
/////////////////////

[ServiceContract]

interface
IMyContract

{


[OperationContract]


void
operation( );

}

[ServiceBehavior(InstanceContextMode =
InstanceContextMode.PerCall)]

class
MyService : IMyContract,IDisposable

{


int
flag =
0
;



MyService( )


{


Trace
.WriteLine(
"MyService.MyService( )"
);


}


public void
operation( )


{


flag++;


Trace
.WriteLine(
"Counter = "
+ flag);


}


public void
Dispose( )


{


Trace
.WriteLine(
"MyService.Dispose( )"
);


}

}

///////////////////////// Client code
/////////////////////

MyContractClient proxy =
new
MyContractClient( );


proxy.opera
tion( );

proxy.operation( );


proxy.Close( );


//Possible Output

MyService.MyService( )