Professional Documents
Culture Documents
WCF Complete Material
WCF Complete Material
Chapter1: Introduction
Evolution of WCF
Evolution of Service Oriented Architecture (SOA)
Four Tenets of SOA
What is WCF
Where does WCF Services fit in?
Evolution of WCF:
1. Monolithic Applications
a. Fox Pro and MS Access Applications which have both database and code at one
place
b. SQL Server / Oracle database were used on network but the application was still a
monolithic one.
c. Problem: Takes lots of time and No Code Reusability
2. Object Orientation 1980s
a. Polymorphism
b. Encapsulation
c. Sub-classing
d. Problem: It by itself didnt facilitate the dynamic evolution of software at runtime.
Once an application was built, it was static. There wasnt an easy way to infuse new
code into an application.
3. COM Components
a. Write code once and reuse in multiple applications.
b. Location Transparent
c. Tight Coupling
d. Runtime Metadata (self describing systems)
e. Problem: Worked well on single machine(using method invocation on an object
reference), we hit scaling problems when we tried to stretch it out and apply it as
the substrate for distributed software integration (across machines)
4. DCOM
a. Network Version of COM Sharing COM objects over network
b. Biggest failure of Microsoft as not at all reliable and scalable.
5. COM+
a. DCOM + MTS (Transaction Services)
b. Object Pooling and Just In Time Activation.
6. .NET Remoting
a. Option for .Net developers for Distributed application development.
b. Best option only when both client and server are on same network.
7. Web Services
a. Provides Objects functionality over HTTP
b. Data is exchanged over the network in XML format.
c. SOAP is the protocol used for communication.
8. WCF is the next generation of Web Service with following enhancements
a. Supports sending messages not only using HTTP but also using TCP and NamedPipe and MSMQ
b. Support for sending messages using formats other than SOAP which includes
Representational State Transfer (REST) and Plain Old XML (POX)
c. Service can be hosting in different types of application unlike web services which
needs Web server only.
d. Built in support for Transaction and reliable sessions
Service Oriented Architecture:
A service is a program that perform a task and that you can interact with through well defined
messages.
o XML is the format in which Web Service and its client communicate with each other.
Service Oriented applications consists of loosely coupled services that communicates through
Messages and Contracts
o Client does not instantiate the service
o Messages are Requests and Responses exchanged between client and server.
o Contracts specify what requests you can make on the service and how it will respond.
Four Tenets of Service Orientation
[OperationContract]
int GetCounter();
Configuration File
1. Everything will be under <system.serviceModel>
2. <services> contains service type definitions
3. <endpoints> contains ABC for a service
4. <binding> contains one or more binding sections to configure individual bindings
5. <behavior> provides configuration for service.
Service Endpoints:
1. A Service endpoint is used by Service Host to receive the request from the client and forward it
to the service.
2. A service can have one or more endpoints.
3. Every endpoint will have unique combination of ABC
4. Can be defined in Code or in Configuration File
a. If configuration file is used it gives facility to change the endpoints when needed. We
can either manually write the configuration file or use Service Configuration Editor.
b. If defined in code: No one can change the endpoints once the code is build and
deployed.
Endpoint in config file:
<endpoint address=""
binding="wsHttpBinding"
contract="WCFLibrary.IMathService">
What is ABC?
Address Where do you send the message?
Binding How do you send the message?
Contract What should the message look like?
Metadata Exchange Endpoint:
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
this is used by clients to add service reference i.e to generate the proxy class.
Base Address:
<baseAddresses>
<add baseAddress="http://localhost:8731/WCFLibrary/MathService" />
<add baseAddress="net.pipe://localhost/WCFService"/>
<add baseAddress="net.tcp://localhost:8000/WCFService"/>
</baseAddresses>
Creating Endpoint Programmatically:
Following can be written in Main:
ServiceHost sh = new ServiceHost(typeof(MathService));
System.ServiceModel.Description.ServiceEndpoint sep;
sep = sh.AddServiceEndpoint(typeof(IService1),
new WSHttpBinding(),
"http://localhost:8731/WCFLibrary/MathService/");
sh.Open();
...
sh.Close();
Chapter 4: Channel Stacks & Bindings in WCF
Understanding Channel Stack
Introduction to Binding
Types of Bindings.
Binding Comparison
Thumb rules in choosing endpoint binding
Configuring a Service and Client for Multiple Bindings
Binding Class Properties.
1. Clients and services communicate by passing messages and the mechanism they use to
communicate is a channel stack.
2. Channel Stack is made up of multiple channels as shown above.
3. Protocol channels are responsible for preparing the message to be sent. These are optional.
The order is important
4. Transport channels are responsible for sending/receiving the message as per the protocol i.e.
Http, TCP etc.
5. Message Encoder converts the Message from XML to bytes for transport and Transport actually
sends the message over the socket.
Introduction to Binding:
The Binding is an attribute of an endpoint and it lets you configure the channels like transport
protocol, encoding and security requirements as shown below
One of the design goals of WCF is to unify the way distributed systems are developed prior to
release of .Net Framework 3.0.
WCF offers a single development framework for all scenarios where distributed solutions were
implemented using different technologies such as ASMX web services, .Net Remoting, COM+,
etc.
WCF achieves this by configuring binding attributes of an endpoint. WCF lets you choose HTTP
or TCP transport protocol, encoding, etc. just by tweaking the value of binding attribute for an
endpoint.
Types
of Bindings (All are class names which are inherited from Binding class).
BasicHttpBinding
WSHttpBinding
WSDualHttpBinding
WSFederatinHttpBinding
NetNamedPipeBinding
NetTcpBinding
NetPeerTcpBinding
NetMsmqBinding
MsmqIntegrationBinding
Security Tx
Mode
Flow*
None
Message WS-AT
Message WS-AT
WSFederationHttpBin HTTP
ding
NetTcpBinding
TCP
Message WS-AT
NetPeerTcpBinding
Binary
SOAP 1.2
Transport X
SOAP 1.2
Transport OleTx
SOAP 1.2
Message X
P2P
Transport OleTx
If you require your service to be consumed by clients compatible with SOAP 1.1, use
basicHttpBinding for interoperability
If you require your service to be consumed within the corporate network, use
netTCPBinding for performance
If you require your service to be consumed over the internet and the client is a WCF
compatible, use wsHttpBinding to reap full benefits of WS* specifications
If you require your service to be accessible only in the same machine, use
netNamedPipeBinding
If you require your service to be queue messages, use netMsmqBinding
If you require your service to act as server as well as client in a peer to peer environment,
utilize netPeerTcpBinding setting
10
11
Known Types
Normally, when passing parameters and return values between a client and a service, both
endpoints share all of the data contracts of the data to be transmitted.
However, this is not the case in the following circumstances:
The sent data contract is derived from the expected data contract. In that case, the
transmitted data does not have the same data contract as expected by the receiving endpoint.
The declared type for the information to be transmitted is an interface.
The declared type for the information to be transmitted is Object.
Some types, which include .NET Framework types, have members that are in one of the
preceding three categories. For example, Hashtable uses Object to store the actual objects in
the hash table. When serializing these types, the receiving side cannot determine in advance
the data contract for these members
Known Types can be declared at 3 places
Step1: Add the following classes to the Library Project.
[DataContract]
public class TrainingEmployee : Employee
{
[DataMember]
public string Subject
{ get; set; }
}
[DataContract]
public class DevelopmentEmployee : Employee
{
[DataMember]
12
13
Overview
Producing Faults
SOAP fault with FaultCode and FaultReason
Culture specific SOAP fault
Strongly Typed SOAP fault
Consuming Faults
Proxy State for Managed Exceptions Vs SOAP Fault
Overview
WCF does not communicate CLR Exceptions.
WCF Exceptions are passed as SOAP Messages. The underlying principle of service-oriented
error handling consists of SOAP fault messages, which convey the failure semantics and
additional information associated with the failure (such as the reason).
For security purpose, an exception message doesnt contain any information about the actual
exception.
During development we can configure the service to return more detailed exception
information.
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
or
[ServiceBehavior(IncludeExceptionDetailInFaults=true)]
public class DemoService : IDemoService
{...}
Managed Exceptions Vs SOAP Fault
If a managed exception is thrown from a service operation, client is immediately reported with
a FaultException and the communication channel of the client is faulted and the proxy object
cannot be used for calling any more methods. If it is used then
CommunicationObjectFaultedException is thrown in the client application.
If a managed exception is thrown from a one way service operation, client is not immediately
reported about the exception in the service. If the client application after this calls any other
method then MessageSecurityException will be reported to client and the communication
channel will be in faulted state.
If a FaultException is thrown from the service operation on server then the client application
can handle this FaultException and the communication channel of client and server will not be
in faulted state.
Producing Faults
Use FaultException Class to customize the Error Message the service returns.
o Clients cant distinguish types of faults
o Use FaultCode to specify a SOAP fault code
o Use FaultReason to specify the description of the fault. It supports locale based
translation of message
14
15
16
17
Transaction: Logical units of work comprising of multiple activities that should all succeed or all
fail
Transaction needs to meet ACID principles:
Atomic: Transaction executes at once and all of the work occurs or none does.
Consistency: Needs to preserve data consistency i.e. commit or rollback
Isolation: Needs to be independent of other transactions and one transaction should not
be allowed to see the uncommitted state of another transaction.
Durable: transactions are recoverable i.e. needs to log its state so that it should know
what do undo if the transaction fails.
.NET framework provides System.Transactions Namespace and TransactionScope class.
To Enable Transaction in WCF Service
1. Create New Binding. Please note the Bindings that supports transaction: NetTcpBinding,
NetNamedPipeBinding, WSHttpBinding, WSDualHttpBinding, WSFederationBinding
<bindings>
<wsHttpBinding>
<binding transactionFlow="true"
name="WSHttpTransactionBindingConfig"/>
</wsHttpBinding>
</bindings>
2. Assign the binding to the endpoint.
<endpoint . . . bindingConfiguration="WSHttpTransactionBindingConfig">
3. Add the following attribute to the participating methods in the Service Contract interface
[TransactionFlow(TransactionFlowOption.Mandatory)]
NotAllowed: A transaction should not be flowed. This is the default value.
Allowed: Transaction may be flowed
Mandatory: Transaction must be flowed
4. For the method implemented by the Service class add the following
[OperationBehavior(TransactionScopeRequired=true,TransactionAutoComplete=true
)]
Default value of TransactionScoreRequired is false.
Default value of TransactionAutoComplete is true
TransactionScopeR
Binding
Caller
Result
equired
permits
flows
transaction transact
flow
ion
False
False
No
Method executes without a transaction.
True
False
No
Method creates and executes within a new
transaction.
True or False
False
Yes
A SOAP fault is returned for the transaction
header.
False
True
Yes
Method executes without a transaction.
True
True
Yes
Method executes under the flowed
transaction.
TransactionIsolationLevel:
Optionally you may configure transaction isolation in ServiceBehaviorAttribute
[ServiceBehavior(TransactionIsolationLevel=System.Transactions.IsolationLevel.Serializable
)]
Different transaction isolation levels in WCF
Read Uncommitted: So, you can read an uncommitted transaction that might get
rolled back later. This isolation level is also called dirty read. This is the lowest isolation
level.
18
Read Committed: It ensures that physically corrupt data will not be read and will
never read data that another application has changed and not yet committed, but it
does not ensure that the data will not be changed before the end of the transaction.
Repeatable Read: It means that locks will be placed on all data that is used in a
query, and other transactions cannot update the data.
Serializable: It does not allow any modification and addition of new data till the
transaction is completed. This is considered to be a very restrictive level.
Snapshot: It raises error on modifying a data that has already been changed by any
transaction.
19
Introduction
Microsoft Message Queuing, or MSMQ, is technology for asynchronous messaging.
MSMQ can be used whenever there's need for two or more applications to send messages to
each other without having to immediately know results.
MSMQ can communicate between remote machines, even over internet. It's free and comes
with Windows, but is not installed by default.
The MSMQ server is similar to an e-mail server, but it's designed to let applications "talk" to
each other, whereas a mail server is designed to let humans talk to each other
Introduction
Advantages of using MSMQ
Transactional Queues
Setup and View MSMQ Server
Steps to follow to Build a MSMQ application
Transactional Queues
When transactions are used to send and receive messages, there are actually two separate
transactions. When the client sends messages within the scope of a transaction, the
transaction is local to the client and the client queue manager. When the service receives
messages within the scope of the transaction, the transaction is local to the service and the
receiving queue manager.
It is very important to remember that the client and the service are not participating in the
same transaction; rather, they are using different transactions when performing their
operations (such as send and receive) with the queue.
Steps to Install and Verify MSMQ Server
1. Go to Control Panel Program and Features Turn Windows Features on or off
2. Check Microsoft Message Queue (MSMQ) Server OK
20
21
Concepts.
Security Mechanisms.
Default Security Settings.
Demonstrate how Messages are encrypted.
Authentication
a. Windows Authentication
b. HTTPS / SSL Authentication.
c. ASP.NET Membership Authentication
d. Custom Authentication
6. Authorization
a. Windows Group/Role based Authorization
b. Custom Role based Authorization
c. ASP.NET Role Provider
d.
Security Concepts
Authentication: Client and service have clear Identity. Client has to provide login Credentials
Authorization: Client has permissions or not to call operations of the service.
Confidentiality: Only client can read data passed between client and service. Data is encrypted
on network
Integrity: Messages have not been tampered with when they are on the network
Security Mechanisms
1. Transport Level Security
Security applied at OS level at Network or transport level and before the message is sent
Encryption based on binding
o HTTPS uses SSL
o TCP uses Transport Layer security (TLS)
o Can require clients to pass credentials for authentication
2. Message Level Security
Messages are encrypted based on WS-Security standard and signed before they are sent.
Can require to client pass credentials for authentication
Pros and Cons of Message Level and Transport Level Security
1. Transport Level Security:
o Pros: Faster and can benefit from hardware acceleration.
o Cons: Provides only point to point encryption. So if the client uses transport level
security and send the message to service, which then forwards the message to another
service for processing. The intermediary service will decrypt the message and could
potentially alter it.
2. Message level Security
o Cons: Slower
o Cons: Requires both client and service must support WS-Security specification. This will
make interoperability more difficult
o Pros: Provides end to end encryption since message is encrypted. Intermediary service
cannot read or decrypt the message.
o Pros: More options for credentials.
Note: In situation where the client sends the message directly to service that performs the
operation, we can safely use either of the mechanism to secure the message.
Default Security Settings
1. BasicHttpBinding
No Security because interoperable with ASMX
2. WsHttpBinding
Message Level Security
Messages are encrypted
3. NetTcpBinding
Transport level security
Messages are not encrypted, but packets are.
22
23
24
25
26
27