WCF stands for Windows Communication Foundation which is a new Runtime/Library in .Net Framework 3.0 onwards. Its a new revolution in SOA (Service Oriented Architecture) development.
SOA (Service Oriented Architecture): The W3C defines Service Oriented Architecture as "A set of components which can be invoked and whose interface description can be discovered and published."
We can say that a communication between multiple service applications or services in the network in order to share the data/information.
Service Oriented Architecture Principles: Principles behind the service orientation are following:
The thing to keep in mind that there is a cost associated with crossing boundaries. These costs come in a number of forms like as communication, performance and processing overhead costs. Services should be accessed quickly and efficiently.
Autonomous Services: Services are built and deployed independently of other services. Especially distributed systems must be built to handle changes easily. This SOA principle states that each service must be managed and version-ed differently so it does not affect other services in the process.
Policy Based Compatibility: When services call each other, it is not like two friends meeting in the street. exchanging information then talking. Services need to know a little more about each other. Each service may or may not have certain requirements before it will start communicating and handling out information. Each services has its own compatibility level and knows how it will interact with other services.
This is how services interact. Services look at each others' policy, look for similarities so that they can start communicating. Policies allow you to move a service from one environment to another without changing the behavior of the service.
Shared Schemas and Contracts: Think "Schema=data" and "Contracts=behavior" The contract contains information regarding the structure of the message. Services do not pass classes and types. They pass schema and contracts. This allows for a loosely coupled system where the service does not care what type of environment the other service is executing on. The information being passed is 100 percent platform independent.
SOA Wrap-up (benefits):
This layered architecture provides developers a new service oriented programming model is discussed following:
Contracts: WCF contracts are much like that you and I sign in real life. A contract I sign could contain details such as the type of work I will perform and what details I might make available to you. A WCF contract contains very similar information. It contains information that describes what a service does and the type of information it will provide. There are three types of contracts: Data, message and service. Those will be discussed later.
Data Contract: A Data contract describes the data that will be exchanged by the service. The service and client do not need to agree on types, but need to agree on Data Contract. This includes parameters and return types.
Message Contract: A message contract provides additional control over that of a data contract, in that it controls SOAP (Simple Object Access Protocol) messages sent and received by the service. Or we can say a message contract lets you customize the type formatting of parameters in SOAP messages.
Service Contract: A service contract is what informs the clients and the rest of the outside world what the end points has to offer and communicate. Its like a single declaration which describes "here are the data types of my messages, here is where I am located and here are the protocols that I communicate with."
Policy and Binding: It specifies important information such as security, protocols, and other information, and these policies and interrogated looking for the things that need to be satisfied before the two services start communicating.
Service Runtime: This layer specifies and manages the behaviors of the service that occur during service operation or service runtime. Service behaviors control service type behaviors. They have no control over end points or message behavior. like end points and message behaviors have no control over service behavior. There are various behaviors managed by the service runtime which are following:
Throttling Behavior: The throttling behavior determines the number of processed messages.
Error Behavior: It specifies what action will be taken if an error occurs during service runtime.
Metadata Behavior: It controls whether or not metadata exposed to the outside world.
Instance Behavior: It drives how many instances of the service will be available to process messages.
Message Inspection: It gives service the ability to inspect all or parts of the message.
Transaction Behavior: It enables transacted operations. That is, if a process fails during the service runtime it has the ability to rollback the transaction.
Dispatch Behavior: When a message is processed by the WCF infrastructure, the dispatch Behavior services determines how the message is to be handled and processed.
Concurrency Behavior: It determines how each service or instance of the service, handles threading. This behavior helps how many threads can access a given instance of a service.
Parameter Filtering: When a message is acted upon by the service, certain actions can be taken based on what is in the message headers. Parameter Filtering filters the message headers and executes preset actions based on the filter of message headers.
Messaging: It defines what formats and data exchange patterns can be used during service communication. Client applications can be deployed to access this layer and control messaging details and work directly with messages and channels. The following channels and components that the Message Layer is composed of:
WS Security Channel: It implements WS- Security specification, which enables message security.
WS-Reliable Messaging Channel: Guaranteed message delivery is provided by the WS Reliable Messaging channel.
Encoders: It lets you pick from a number of encodings for the message.
HTTP Channel: It tells the service that message delivery will take place via the HTTP Protocol.
TCP Channel: It tells the service that message delivery will take place via the TCP Protocol.
Transaction Flow Channel: It governs transacted message patterns.
NamePipe Channel: It enables inter process communication.
MSMQ Channel: If your service needs to inter-operate with MSMQ, this is the channel that enables that.
Activation and Hosting: The Activation and Hosting layer provides different options in which a service can be started as well as hosted. Services can be hosted within the context of another application, or they can be self hosted.
The following details for hosting of services.
Self Hosting: This hosting is provided to test the service. We can say that it provides less security and features. Once we developed the service, we just need to run it like normal .net applications. it will hosted automatically and will display Service Test Client window in which we can pass the arguments or data to the service and get the result either it is working as per business logic or not.
Windows Service Hosting: This enables WCF applications to be automatically started when running on a computer that is running the Windows Activation Service. Let say if we want our WCF service should run automatically when we start the computer or OS starts and stops automatically when OS or PC shuts down.
WAS Hosting (Windows Activation Service): WAS is a system service available with Windows vista and windows server 2008 & Windows 7. It is available with IIS 7.0 and it is more powerful compared to IIS 6.0 because it supports Http, TCP and named pipes were IIS 6.0 supports only Http. It can be installed and configured separately.
Hosting WCF in Activation service takes many advantages such as process recycling, isolation, idle time management and common configuration system. WAS hosted service can be created using following steps
The XML re-presentation for this SOAP message might look like following:
<env:Envelope xmlns:s=”http://www.w3.org/2003/05/soap-envelope”
xmlns:a=”http://schemas.xmlsoap.org/ws/2004/08/addressing”>
<env:Header>
<o:order xmlns:o=”http://www.bpb.com/order” env:mustUnderstand=”true”>
<o:orderreference>591aef96-0c0d-4534-a1d2-4253b910b0b6</o:orderreference>
<o:orderdate>05/15/2006</o:orderdate>
</o:orderreference>
<p:purchaser xmlns:o=”http://www.bpb.com/purchaser” env:mustUnderstand=”true”>
<p:name>John Spano</p:name>
<p:creditcardnum>1234-5678-9012-3456</p:creditcardnum>
</p:orderreference>
</env:Header>
<env:Body>
<c:price xmlns:c=”http://www.bpb.com/bookcost”>
<c:cost>
<c:retailcost>$49.99</c:retailcost>
<c:salecost>$39.99</c:salecost>
</c:cost>
</c:price>
<q:quantity xmlns:q=”http://www.wrox.com/quantity”>
<q:orderquantity>1</q:orderquantity>
</q:quantity>
<t:title xmlns:t=”http://www.wrox.com/title”>
<t:booktitle>WCF for Dummies</t:booktitle>
</t:title>
</env:Body>
</env:Envelope>
Any child elements of the header element are called "header blocks". These two header blocks provide information that even though not required can be useful in the processing of the body element of the message.
What information goes in the header and what information goes in the body are entirely up to you and
are determined at design time.
Any information required to be exchanged when the messages reaches the intended destination goes in the message body. In the above example, three pieces of information are included in the message body are title, order quantity and book price. The receiving service (SOAP receiver) might use this information to look through its inventory of books for the specific title and, based on the order quantity, decrement its inventory total by the order quantity. These pieces of information are expected to be understood by the receiving service.
Now, depending on how both the client and service were coded, the client might or might not expect a
response, and the service might or might not send a response.
If you are like me and like order confirmations when you order something, it is valid to have the client to expect a response and the service to send a response.The response message sent by service might look like following:
<env:Envelope xmlns:s=”http://www.w3.org/2003/05/soap-envelope”>
<env:Header>
<o:order xmlns:o=”http://www.ogcs.com” env:mustUnderstand=”true”>
<o:orderreference>591aef96-0c0d-4534-a1d2-4253b910b0b6</o:orderreference>
<o:orderdate>05/15/2006</o:orderdate>
</o:orderreference>
<p:purchaser xmlns:o=”http://www.ogcs.com” env:mustUnderstand=”true”>
<p:name>John Spano</p:name>
<p:creditcardnum>1234-5678-9012-3456</p:creditcardnum>
</p:orderreference>
</env:Header>
<env:Body>
<ShippingInfo xmlns==”http://www.ogcs.com”/>
<OrderStatus>Success></OrderStatus>
<ShipDate>5/16/2006</ShipDate>
<ArrivalDate>5/22/2006</ArrivalDate>
</ShippingInfo>
</env:Body>
</env:Envelope>
When the client receives the response, it knows that the order was placed successfully, when the will ship and tentative date of when it will arrive.
Messaging Programs: In WCF, different types of applications can send and receive messages which are following:
Channels: A channel is a medium through which messages are exchanged. The channel is created by client specifying the address of the service and the type of channel to create. once this information is established, the channel is created and opened. The following are the steps to establish connection and exchange messages.
SOA (Service Oriented Architecture): The W3C defines Service Oriented Architecture as "A set of components which can be invoked and whose interface description can be discovered and published."
We can say that a communication between multiple service applications or services in the network in order to share the data/information.
Service Oriented Architecture Principles: Principles behind the service orientation are following:
- Explicit boundaries
- Autonomous services
- Policy-based compatibility
- Shared schemas and contracts
The thing to keep in mind that there is a cost associated with crossing boundaries. These costs come in a number of forms like as communication, performance and processing overhead costs. Services should be accessed quickly and efficiently.
Autonomous Services: Services are built and deployed independently of other services. Especially distributed systems must be built to handle changes easily. This SOA principle states that each service must be managed and version-ed differently so it does not affect other services in the process.
Policy Based Compatibility: When services call each other, it is not like two friends meeting in the street. exchanging information then talking. Services need to know a little more about each other. Each service may or may not have certain requirements before it will start communicating and handling out information. Each services has its own compatibility level and knows how it will interact with other services.
This is how services interact. Services look at each others' policy, look for similarities so that they can start communicating. Policies allow you to move a service from one environment to another without changing the behavior of the service.
Shared Schemas and Contracts: Think "Schema=data" and "Contracts=behavior" The contract contains information regarding the structure of the message. Services do not pass classes and types. They pass schema and contracts. This allows for a loosely coupled system where the service does not care what type of environment the other service is executing on. The information being passed is 100 percent platform independent.
SOA Wrap-up (benefits):
- Services are platform and location independent. A service does not care where the service is located and it does not care about the environment of another service to be able to communicate with it.
- Services are isolated. A change of one service does not necessitate a change in other services
- Services are protocol, format and transport neutral. Service communication information is flexible.
- Services are scalable
- Service behavior is not constrained. If you want to move the location of the services, you can only need to change the policy, not the service itself.
Application
|
Contracts
|
Service Run Time
|
Messaging
|
Activation and
Hosting
|
This layered architecture provides developers a new service oriented programming model is discussed following:
Contracts: WCF contracts are much like that you and I sign in real life. A contract I sign could contain details such as the type of work I will perform and what details I might make available to you. A WCF contract contains very similar information. It contains information that describes what a service does and the type of information it will provide. There are three types of contracts: Data, message and service. Those will be discussed later.
Data Contract: A Data contract describes the data that will be exchanged by the service. The service and client do not need to agree on types, but need to agree on Data Contract. This includes parameters and return types.
Message Contract: A message contract provides additional control over that of a data contract, in that it controls SOAP (Simple Object Access Protocol) messages sent and received by the service. Or we can say a message contract lets you customize the type formatting of parameters in SOAP messages.
Service Contract: A service contract is what informs the clients and the rest of the outside world what the end points has to offer and communicate. Its like a single declaration which describes "here are the data types of my messages, here is where I am located and here are the protocols that I communicate with."
Policy and Binding: It specifies important information such as security, protocols, and other information, and these policies and interrogated looking for the things that need to be satisfied before the two services start communicating.
Service Runtime: This layer specifies and manages the behaviors of the service that occur during service operation or service runtime. Service behaviors control service type behaviors. They have no control over end points or message behavior. like end points and message behaviors have no control over service behavior. There are various behaviors managed by the service runtime which are following:
Throttling Behavior: The throttling behavior determines the number of processed messages.
Error Behavior: It specifies what action will be taken if an error occurs during service runtime.
Metadata Behavior: It controls whether or not metadata exposed to the outside world.
Instance Behavior: It drives how many instances of the service will be available to process messages.
Message Inspection: It gives service the ability to inspect all or parts of the message.
Transaction Behavior: It enables transacted operations. That is, if a process fails during the service runtime it has the ability to rollback the transaction.
Dispatch Behavior: When a message is processed by the WCF infrastructure, the dispatch Behavior services determines how the message is to be handled and processed.
Concurrency Behavior: It determines how each service or instance of the service, handles threading. This behavior helps how many threads can access a given instance of a service.
Parameter Filtering: When a message is acted upon by the service, certain actions can be taken based on what is in the message headers. Parameter Filtering filters the message headers and executes preset actions based on the filter of message headers.
Messaging: It defines what formats and data exchange patterns can be used during service communication. Client applications can be deployed to access this layer and control messaging details and work directly with messages and channels. The following channels and components that the Message Layer is composed of:
WS Security Channel: It implements WS- Security specification, which enables message security.
WS-Reliable Messaging Channel: Guaranteed message delivery is provided by the WS Reliable Messaging channel.
Encoders: It lets you pick from a number of encodings for the message.
HTTP Channel: It tells the service that message delivery will take place via the HTTP Protocol.
TCP Channel: It tells the service that message delivery will take place via the TCP Protocol.
Transaction Flow Channel: It governs transacted message patterns.
NamePipe Channel: It enables inter process communication.
MSMQ Channel: If your service needs to inter-operate with MSMQ, this is the channel that enables that.
Activation and Hosting: The Activation and Hosting layer provides different options in which a service can be started as well as hosted. Services can be hosted within the context of another application, or they can be self hosted.
The following details for hosting of services.
Self Hosting: This hosting is provided to test the service. We can say that it provides less security and features. Once we developed the service, we just need to run it like normal .net applications. it will hosted automatically and will display Service Test Client window in which we can pass the arguments or data to the service and get the result either it is working as per business logic or not.
Windows Service Hosting: This enables WCF applications to be automatically started when running on a computer that is running the Windows Activation Service. Let say if we want our WCF service should run automatically when we start the computer or OS starts and stops automatically when OS or PC shuts down.
WAS Hosting (Windows Activation Service): WAS is a system service available with Windows vista and windows server 2008 & Windows 7. It is available with IIS 7.0 and it is more powerful compared to IIS 6.0 because it supports Http, TCP and named pipes were IIS 6.0 supports only Http. It can be installed and configured separately.
Hosting WCF in Activation service takes many advantages such as process recycling, isolation, idle time management and common configuration system. WAS hosted service can be created using following steps
- Enable WCF for non-HTTP protocols
- Create WAS hosted service
- Enable different binding to the hosted service
Note: If we want a service to support HTTP & TCP and namepipes we can use both the hosting IIS and WAS together.
WCF Offers: The following are the great points that WCF has to offers.
WCF Offers: The following are the great points that WCF has to offers.
- Programming Model
- Scalability
- Interoperability
- Enhance communication
- Enterprise enabled
Scalability:WCF services scale, and they scale in all directions not just up or out in all directions. Services scale up by not tied to a single OS or processor. Services scale up by the pure ability to deploy them on bigger and better servers.
Services scale down by interfacing and communicating with devices such as printers, scanners faxes and so on.
Interoperability: It is able to build high class services using a single programming model and at the same time take advantages of earlier technologies. WCF services also take advantages of the WS architecture utilizing the already established standards as far as communication and protocols and concerned.
Enhance Communication: Services are not dependent on transports (like protocols). As a developer we can choose from handful of transports, different message formats and surplus of message patterns.
In WCF services are neutral as far as transports and protocols are concerned. A service can use TCP, HTTP, Named pipes or any other protocol to communicate. Communication is completely separate from the service. They are completely independence from one another.
Enterprise Enabled: WCF provides the ability to have security and reliability without sacrificing performance and you can throw transactions into the mix as well.
WCF Features: It provides the following feature:
- Transactions
- Hosting
- Security
- Queuing
Transactions: A Transaction is a unit of work. A transaction ensures that everything within that transaction either succeeds as a whole or fails as a whole. WCF incorporates this same transactional processing into its communication. You as a developer can now group communication into transactions. On the enterprise level, this feature lets you execute transactional work across different platforms.
Hosting:WCF hosting allows services to be hosted in a handful of different environment, such as Windows NT services, Windows Forms and console applications as well as IIS (Internet Information Services) and Windows Activation Services (WAS.
Hosting a service in IIS has added benefits in that the service can take full advantage of many of the native IIS features like IIS can control the starting and stopping of the service automatically.
Security: WCF ensures that everything from messages to clients and servers get authenticated and WCF has a feature that ensures messages are not messed during transit. WCF includes message integrity and confidentiality.
WCF also enables you to integrate your application into an existing security infrastructure.
Queuing: WCF supports MSMQ (Microsoft Message Queuing) it allows messages to be safely stored, providing a consistent of communication. Queuing collects and stores sent messages from a sending application and forwards them on to the receiving application. This provides safe and reliable message delivery mechanism.
Messages: A message is a packet of data containing several pieces of important information being routed from a source to destination. Application written using the WCF communicate through messages that are sent a source to a destination.
All messages are SOAP messages, formatted in XML as SOAP envelopes. In case of WCF these SOAP messages are services and endpoints, sending these SOAP messages from one location to another to exchange information.
Message Structure: WCF uses messages to pass data or exchange information from one point to another. These messages are little more than a packet of data and must conform to a specific format in order to exchange of information to take place. Basic structure of SOAP message is following:
SOAP Envelope
|
Basically there are three general components that make up a SOAP message:
- SOAP Envelope
- SOAP Header
- SOAP Body
SOAP Envelope: It is nothing more than a container for the two most important pieces of a SOAP message, the SOAP header and the SOAP body.
A SOAP envelop contains several pieces of key information in the form of elements. They include the following:
- The name of the envelope
- A namespace name
- An optional <header> element
- A required <body> element
The namespace must be “http://www.w3.org/2003/05/soap-envelope”.
The following code snippet shows the basic code necessary to create a SOAP message:
<env:Envelope xmlns:s=”http://www.w3.org/2003/05/soap-envelope”
xmlns:a=”http://schemas.xmlsoap.org/ws/2004/08/addressing”>
...
</env:Envelope>
<env:Envelope xmlns:s=”http://www.w3.org/2003/05/soap-envelope”
xmlns:a=”http://schemas.xmlsoap.org/ws/2004/08/addressing”>
...
</env:Envelope>
SOAP Header:
- The name of the envelope
- A namespace name
- An optional <header> element
- A required <body> element
The namespace must be “http://www.w3.org/2003/05/soap-envelope”.
The following code snippet shows the basic code necessary to create a SOAP message:
<env:Envelope xmlns:s=”http://www.w3.org/2003/05/soap-envelope”
xmlns:a=”http://schemas.xmlsoap.org/ws/2004/08/addressing”>
...
</env:Envelope>
xmlns:a=”http://schemas.xmlsoap.org/ws/2004/08/addressing”>
...
</env:Envelope>
This code fragment that it contains the name of the envelope and a namespace name. the envelope name is given following:
env:Envelope
The rest of the code fragment contains the namespace name. It was mentioned earlier that a SOAP envelope also contains an optional <header> element and a required <body> element will be discussed next.
SOAP Header: It is a collection of zero or more header blocks. It is possible for a SOAP message to contain no headers, It header is included, it must be the first child element of the envelope element.
The SOAP header contains important information regarding things that may not be directly related to the message, and is a good place to put optional information regarding the message.
The following is the basic format for including the message header.
<env:Envelope xmlns:s=”http://www.w3.org/2003/05/soap-envelope”
xmlns:a=”http://schemas.xmlsoap.org/ws/2004/08/addressing”>
<env:Header>
</env:Header>
</env:Envelope>
xmlns:a=”http://schemas.xmlsoap.org/ws/2004/08/addressing”>
<env:Header>
</env:Header>
</env:Envelope>
SOAP Body: SOAP body is a collection of data items to be used at a specific target (SOAP receiver). Like the SOAP header, a message can contain zero or more bodies.
A SOAP body, which is simply a child element of the envelope, contains all the necessary information for communication with the SOAP receiver.
The following is the basic format for including a message body.
<env:Envelope xmlns:s=”http://www.w3.org/2003/05/soap-envelope”
xmlns:a=”http://schemas.xmlsoap.org/ws/2004/08/addressing”>
<env:Header>
</env:Header>
<env:Body>
</env:Body>
</env:Envelope>
xmlns:a=”http://schemas.xmlsoap.org/ws/2004/08/addressing”>
<env:Header>
</env:Header>
<env:Body>
</env:Body>
</env:Envelope>
The following figure describes SOAP message.
SOAP Envelope
|
The XML re-presentation for this SOAP message might look like following:
<env:Envelope xmlns:s=”http://www.w3.org/2003/05/soap-envelope”
xmlns:a=”http://schemas.xmlsoap.org/ws/2004/08/addressing”>
<env:Header>
<o:order xmlns:o=”http://www.bpb.com/order” env:mustUnderstand=”true”>
<o:orderreference>591aef96-0c0d-4534-a1d2-4253b910b0b6</o:orderreference>
<o:orderdate>05/15/2006</o:orderdate>
</o:orderreference>
<p:purchaser xmlns:o=”http://www.bpb.com/purchaser” env:mustUnderstand=”true”>
<p:name>John Spano</p:name>
<p:creditcardnum>1234-5678-9012-3456</p:creditcardnum>
</p:orderreference>
</env:Header>
<env:Body>
<c:price xmlns:c=”http://www.bpb.com/bookcost”>
<c:cost>
<c:retailcost>$49.99</c:retailcost>
<c:salecost>$39.99</c:salecost>
</c:cost>
</c:price>
<q:quantity xmlns:q=”http://www.wrox.com/quantity”>
<q:orderquantity>1</q:orderquantity>
</q:quantity>
<t:title xmlns:t=”http://www.wrox.com/title”>
<t:booktitle>WCF for Dummies</t:booktitle>
</t:title>
</env:Body>
</env:Envelope>
Any child elements of the header element are called "header blocks". These two header blocks provide information that even though not required can be useful in the processing of the body element of the message.
What information goes in the header and what information goes in the body are entirely up to you and
are determined at design time.
Any information required to be exchanged when the messages reaches the intended destination goes in the message body. In the above example, three pieces of information are included in the message body are title, order quantity and book price. The receiving service (SOAP receiver) might use this information to look through its inventory of books for the specific title and, based on the order quantity, decrement its inventory total by the order quantity. These pieces of information are expected to be understood by the receiving service.
Now, depending on how both the client and service were coded, the client might or might not expect a
response, and the service might or might not send a response.
If you are like me and like order confirmations when you order something, it is valid to have the client to expect a response and the service to send a response.The response message sent by service might look like following:
<env:Envelope xmlns:s=”http://www.w3.org/2003/05/soap-envelope”>
<env:Header>
<o:order xmlns:o=”http://www.ogcs.com” env:mustUnderstand=”true”>
<o:orderreference>591aef96-0c0d-4534-a1d2-4253b910b0b6</o:orderreference>
<o:orderdate>05/15/2006</o:orderdate>
</o:orderreference>
<p:purchaser xmlns:o=”http://www.ogcs.com” env:mustUnderstand=”true”>
<p:name>John Spano</p:name>
<p:creditcardnum>1234-5678-9012-3456</p:creditcardnum>
</p:orderreference>
</env:Header>
<env:Body>
<ShippingInfo xmlns==”http://www.ogcs.com”/>
<OrderStatus>Success></OrderStatus>
<ShipDate>5/16/2006</ShipDate>
<ArrivalDate>5/22/2006</ArrivalDate>
</ShippingInfo>
</env:Body>
</env:Envelope>
When the client receives the response, it knows that the order was placed successfully, when the will ship and tentative date of when it will arrive.
Messaging Programs: In WCF, different types of applications can send and receive messages which are following:
- Clients
- Services
- Intermediaries
What is important to understand is the each program is very unique is several ways. A programmer will program the clients and services but not intermediaries. A service will never initiate communication, It will answer a request. it will never start the flow of communication. That is the role of client to open the flow of communication and send the initial message.
Clients: A client is the piece in the whole WCF picture that initiates communication via the sending of message. The client sends a message to service and waits for a response. The service, receives the request and processes the message and sends a response.

Services: A service is a program that receives messages and performs predefined actions based on the contents of a message. service simply respond to incoming messages. The receiving of a message triggers code to be executed, performing an action (or behavior).
These actions or behaviors, could be number of things ranging from reading or writing to/from a database, performing some file I/O operations or even performing more messaging operations such as responding to the client or even sending a message to another service.
One important thing to remember about services serving multiple clients is that a service is completely able to hold each session's state and keep it totally isolated from other session. Two clients can call the same endpoint of the same service at the same time and the service will be able to maintain session state for each client so that operations of one client do not step on the operations of the other client.
Service Chains: Service chains simply means that a service can act like a client and send messages to other service in response to an incoming message. Remember that a service can not initiate communication. It reacts to the incoming message and sends a message to another service. When the service sends a message in response to an incoming message, it is acting as a client.

The above figure describes that the client initiates the communication by sending a message to a service, the first service in the chain. The service processes the incoming messages and based in predefined behavior, sends another message to the second service in the chain. in this case, the first service in the chain behaves both like a client and a service.
Intermediaries: An intermediary is not a service in a chain of services. The client and service have no idea that the intermediary even exists. An intermediary is not required and it does not perform any action against the message. It does not consume the message. Intermediary performs an important role. It can prevent unwanted messages from getting in and it can take various other actions on messages, such as routing messages or acting as a gateway. An intermediary can also monitor message activity.
Messaging Patterns: Message patterns basically describe how programs exchange messages. When a program sends a message, it must conform to one of the several patterns in order for it to successfully communicate with the destination program. The destination program must conform to the same basic pattern. There are three basic messaging patterns that programs can use to exchange messages which are following:
Clients: A client is the piece in the whole WCF picture that initiates communication via the sending of message. The client sends a message to service and waits for a response. The service, receives the request and processes the message and sends a response.
Services: A service is a program that receives messages and performs predefined actions based on the contents of a message. service simply respond to incoming messages. The receiving of a message triggers code to be executed, performing an action (or behavior).
These actions or behaviors, could be number of things ranging from reading or writing to/from a database, performing some file I/O operations or even performing more messaging operations such as responding to the client or even sending a message to another service.
One important thing to remember about services serving multiple clients is that a service is completely able to hold each session's state and keep it totally isolated from other session. Two clients can call the same endpoint of the same service at the same time and the service will be able to maintain session state for each client so that operations of one client do not step on the operations of the other client.
Service Chains: Service chains simply means that a service can act like a client and send messages to other service in response to an incoming message. Remember that a service can not initiate communication. It reacts to the incoming message and sends a message to another service. When the service sends a message in response to an incoming message, it is acting as a client.
The above figure describes that the client initiates the communication by sending a message to a service, the first service in the chain. The service processes the incoming messages and based in predefined behavior, sends another message to the second service in the chain. in this case, the first service in the chain behaves both like a client and a service.
Intermediaries: An intermediary is not a service in a chain of services. The client and service have no idea that the intermediary even exists. An intermediary is not required and it does not perform any action against the message. It does not consume the message. Intermediary performs an important role. It can prevent unwanted messages from getting in and it can take various other actions on messages, such as routing messages or acting as a gateway. An intermediary can also monitor message activity.
Messaging Patterns: Message patterns basically describe how programs exchange messages. When a program sends a message, it must conform to one of the several patterns in order for it to successfully communicate with the destination program. The destination program must conform to the same basic pattern. There are three basic messaging patterns that programs can use to exchange messages which are following:
- Simplex/One way
- Request/Reply
- Duplex
Simplex/One Way: Its a one way communication from program A to program B. No response is generated by program B or we can say that message sent from program A and no response from Program B.
In this scenario, the client initiates communication and sends a message to the service. the service consumes the message and performs some action or behavior but does not communicate back to the client.
Request/Reply: In this pattern a client sends a message to service or sever and waits for reply. once service/server processes or consumes the message then sends reply back to the client, that means for one request there will be only reply from service. Service will work based on request.
Duplex: It allows both programs or client/service to communicate openly and allows message exchanges in both directions. The concept with this messaging pattern is that neither the sending program nor receiving program waits for a response from the other program. We can say client sends one message to service and service can send more than one responses/messages to the client.
Channels: A channel is a medium through which messages are exchanged. The channel is created by client specifying the address of the service and the type of channel to create. once this information is established, the channel is created and opened. The following are the steps to establish connection and exchange messages.
- The client establishes a channel to the service.
- The service accept the client's request to open a channel
- The client sends the message request via the channel
- The service sends a reply to the client via the channel
Also, it is the responsibility of the client to close and dispose of the channel once it is done using the channel.
Channel Stacks: In Service Oriented Architecture, one of the big bonuses of SOA was interoperability, it is through channel stacks that additional features needed by the message are provided, such as binding and security.
Think of a channel as a pipe or tube. When a message is sent from the sender to the receiver, the message is sent through the channel "pipe". Now imagine gluing a number of these pipes together with each pipe or tube performing a specific function needed by the message.You now have a channel stack.
The following is a list of some functionality available that can be utilized to create and string together a channel stack:
- Security
- Interoperability
- Message Patterns
- Transports
Security: Two basic levels of security are available: Transport security and message security. Transport security can be provided by several protocols including as HTTPS. SOAP message security offers quite a list of functionality, including authentication, message integrity and confidentiality and auditing.
You can take advantages of several message security features that already exist such as Windows authentication. One of the key features of WCF is that it is extensible, meaning that you can write custom extensions to add additional security features such as custom credentials, tokens and authorization.
Interoperability: WCF supports MSMQ (Microsoft Message Queuing) ability, .Net interoperability and WS-* interoperability.
MSMQ interoperability allows your WCF application to communicate with your MSMQ installation. .Net interoperability lets you communicate with .Net platforms on both ends of the communication channel, and WS*- interoperability allows you to take advantage of these platforms using the WS-* protocols, such as SOAP, MTOM, WSDL, WS-Security as well as others. Interoperability rocks.
Message Patterns: How we build our message pattern channel depends on what message patterns are available to us. There are three message patterns exist like Simplex/ One Way, Request/Reply and Duplex. When interoperability comes into play we need to keep in mind the types of message patterns of other platforms you want to inter-operate which may not support that message pattern. e.g. MSMQ does not communicate in a request-reply fashion.
Transports: WCF supports four transports: HTTP, TCP, MSMQ and Named Pipes. These transports are the medium in which communication takes place in a channel. Some of these transports have built-in security and others do not e.g. HTTP has HTTPS.
The HTTP transport is useful when connection state does not need to be maintained, such as a web browser client communicating with a web server. Because the HTTP protocol is not connection-based, no connection state is maintained once the response is sent. HTTP protocol is very useful in interoperability with legacy systems.
TCP is useful when connection-based communication is important, In this scenario, a communication session between participants is created prior to the exchange of data. if all communication participants are using WCF, binding using this protocol or the Named Pipes protocol perform better. TCP transport in WCF is specifically designed for the scenario where both participants are using WCF.
Named Pipes is useful for a single machine processing between processes. It can be used for single ( one way) or duplex communication between processes on a single computer. This transport should be used when communication from another machine is to be prevented and communication between WCF applications on the same machine is required.
Services: WCF is made up of services and endpoints that communicate with clients, regardless of the platform. WCF builds on this to offer interoperability with other platforms and allows for the extension of WCF in many areas.
The WCF runtime controls several aspects of the service including message formatting, and the sending and receiving of messages. The runtime also oversees handling the message over to the correct operation for processing and execution.
On top of all this is the ServiceHost. The ServiceHost is responsible for providing a host for the endpoints as well as making available the service behavior.
At any given point a service can be in one of six states:
The WCF runtime controls several aspects of the service including message formatting, and the sending and receiving of messages. The runtime also oversees handling the message over to the correct operation for processing and execution.
On top of all this is the ServiceHost. The ServiceHost is responsible for providing a host for the endpoints as well as making available the service behavior.
At any given point a service can be in one of six states:
- Created
- Opening
- Opened
- Closing
- Closed
- Faulted
Each endpoint has its own address which distinguishes one endpoint from another.
Address: All endpoints will be accessed by their addresses. Several things determine the format of an address, such as transport used and whether or not IIS is hosting the service. It is entirely possible to host a service using TCP or MSMQ. If you were using service using TCP, the prefix would be net.tcp and he address would look something like this:
net.tcp://localhost:9050/PlaceOrder
It you were using Http, the prefix would be http://. Like following:
http://localhost:9051/PlaceOrder
Bindings: Bindings are what defines how an endpoint communicates with the outside world. Each endpoint must have binding. Binding is a set of properties, define things like the transport pattern, the security pattern, and the message pattern. Binding should specify the transport.
WCF comes with nine predefined bindings. These binding are selected based on features you need. Following is the list of bindings:
WCF also allows you to create your own custom bindings.
Contracts: Contracts defines certain aspects of the service such as the format and structure of the message, and equally important, the behavior of the service. Service contracts are well-formed XML documents, typically found in the format of WSDL or XSD.
WCF supports the following three types of contracts:
When developing WCF services we need to understand how to link Object Oriented and Service Oriented together. The term classes and interfaces are extremely familiar to the object oriented developer, and they are still used when developing WCF services. This is the OO part and SO part comes in when you apply the WCF attributes to define entities.
Note: .Net is Component Oriented language. It includes Object Oriented principles and it supports Service Oriented features.
The following class defines and object oriented interface:
public interface CoolService
{
decimal CalculateShipping(string state,int shipType)
{
//do something
}
decimal CalculateTax(string state,decimal bookCost)
{
//do something
}
}
C# now comes the SO part, which is to add necessary attributes used to designate this interface as WCF contract which is following:
[ServiceContract]
public interface CoolService
{
[OperationContract]
decimal CalculatingShipping(string state,int shipType)
{
//do something
}
[OperationContract]
decimal CalculateTax(string state,decimal bookCost)
{
//do something
}
}
We will discuss about [ServiceContract] and [OperationContract] attributes later.
Service Model: WCF service model is very similar to the web service model. Using the service model, you specify, how to communicates and what the service can do. The only difference is the naming of the parts. In WCF, they are not called Service, Binding and PortType. In WCF, they are called Address, Binding and Contract.
A service is an application or piece of software that communicates with other services or applications. The service has one or more endpoints. Each of these endpoints contains an Address, Binding and Contract.
This service model is provided by the System.ServiceModel namespace.
System.ServiceModel: In WCF, the System.ServiceModel namespace is used to model and develop the service application and how it communicates.This namespace provides a large number of classes that allow developers to be flexible with respect of how their service will be developed.
The following are the commonly used classes used to model and build your service.
class TestWCFApp
{
static void Main()
{
Uri baseAddress = new Uri(ConfigurationManager.AppSettings[“address”]);
AddressHeader ah =
AddressHeader.CreateAddressHeader(“service1”,”http://localhost:8080/service”);
EndpointAddress ea = new EndpointAddress(new
Uri(“http://localhost:8081/testservice/service”), ah);
ServiceEndpoint se = new
ServiceEndpoint(ContractDescription.GetContract(typeof(BookOrderService)), new
WSHttpBinding), ea);
ServiceHost sh new ServiceHost(typeof(BookOrderService), baseAddress);
sh.Description.Endpoints.Add(se);
sh.Open();
sh.close();
}
}
The AddressHeader class is used to define an address header for the endpoint. The
endpoint is then defined using the address header. A service endpoint is then defined, followed by the
defining of a service host, which is used to provide a host for the service being created. The endpoint
description is then set, and finally the service host is opened, which creates listeners and starts listening
for messages.
http://mymachine:8080/myservice
or
http://mymachine/myservice
It would be noted that there can be an optional part, the port, over which the service is being addresses. The port will be specified after the machine name.
To understand the addresses, you also need to know the different types of addresses, which are the following:
Address Types: WCF lets you use several types of addresses to associate with each endpoint, and it is through these addresses that the client communicates with the endpoint.
Endpoint Address: An endpoint address specifies the address of a specific service endpoint. Client can access the service via the endpoint address such as following:
http://mymachine:8080/myservice
Once the client has accessed the service via the endpoint address, the client can talk to the service and all communication to and from the service goes through this endpoint at this address.
Base Address: It provides a way to specify a single, primary address for a given service and assign relative addresses to each individual endpoint. Let say you have a service with three exposed endpoints. you can assign a given service the following primary or base address.
http://mymachine:8080/myservice
with the base address assigned to the service, you can then assign the three endpoints the following relative addresses:
http://mymachine:8080/myservice/service1
http://mymachine:8080/myservice/service2
http://mymachine:8080/myservice/service3
The base address is associated to the service, allowing you to assign relative addresses to the individual endpoint.
MEX Address: MEX addresses allow a client to gather information about a particular service. MEX, meaning metadata exchange, is an HTTP endpoint address used to obtain service information. e.g. the following address is an MEX address:
http://mymachine:8080/myservice/mex
MEX address provides the client a way to obtain information about the service. This information is provided through the service metadata, which describes the service.
Address Formats: Endpoint addresses are formatted on the selected transport used in communication. The transport or scheme is the part of the address that specifies and determines the transport that will be used. The developer who can choose the address and how it is deployed. It is important to remember that no matter the format, the client must be able to get to the address to get and consume the service.
There are two things to keep in mind as you develop a service:
Named Pipe Address: The Named Pipe address is formatted as follows:
net.pipe://localhost/myservice
There are two things to notice about this address format:
http://domainname|machinename [:port]/virtualdirectoryname [.svcfilename]
The following list explains the part of an IIS address:
Bindings: Bindings are what defines how an endpoint communicates with the outside world. Each endpoint must have binding. Binding is a set of properties, define things like the transport pattern, the security pattern, and the message pattern. Binding should specify the transport.
WCF comes with nine predefined bindings. These binding are selected based on features you need. Following is the list of bindings:
Binding
|
Interoperability
|
Security
|
Sessions
|
Message Pattern
|
BasicHttpBinding
|
Basic Profile
1.1
|
(None),
Transport
Message
|
None,
(None)
|
n/a
|
WSHttpBinding
|
WS
|
Transport,
(Message),
Mixed
|
(None),
Transport,
Reliable
|
n/a
|
WSDualHttpBinding
|
WS
|
(Message)
|
Reliable
|
Yes
|
WSFederationHttpBinding
|
WS
|
(Message)
|
(None),
Reliable
|
No
|
NetTcpBinding
|
.NET
|
(Transport),
Message
|
Reliable
(Transport)
|
Yes
|
NetNamedPipeBinding
|
.NET
|
(Transport)
|
None,
(Transport)
|
Yes
|
NetMsmqBinding
|
.NET
|
Message,
(Transport),
Both
|
(None)
|
No
|
NetPeerTcpBinding
|
Peer
|
(Transport)
|
(None)
|
Yes
|
MsmgIntegrationBinding
|
MSMQ
|
(Transport)
|
(None)
|
n/a
|
WCF also allows you to create your own custom bindings.
Contracts: Contracts defines certain aspects of the service such as the format and structure of the message, and equally important, the behavior of the service. Service contracts are well-formed XML documents, typically found in the format of WSDL or XSD.
WCF supports the following three types of contracts:
- Service contracts
- Message contracts
- Data contracts
Service Contract: Service contracts defines the operations that a service will perform when executed. They tell the out outside world a lot about the service such as message data types, operation locations, the protocols the client will need in order to communicate with the service and the operation the service provides.
Message Contract: It allows the control of SOAP messages that are produced and consumed by WCF. Basically it boils down to being able to customize the format of contract parameters and placing of elements within a SOAP message.
It is highly recommended that if you do not need this level of control, you should consider using data contracts.
Data Contracts: Data Contracts specifically define the data that is being exchanged between a client and service. The data contract is an agreement that means the client and the service must agree on the data contract in order for the exchange of data to take place. Note that they don't have to agree on the data types, just as contract.
This is made available due to the fact that all data is serialized to XML and deserialized from XML during the processing of the message. This means that a number of different types can be serialized with no extra preparation.
Serialization is provided via a new serialization engine in WCF, called the DataContractSerializer. This engine provides the translation between .Net Framework objects and XML and vice Versa.
Behaviors: A behavior controls the runtime characteristics of a service or endpoint.Behaviors are grouped according to their scope, in that they control aspects relevant to the object to which they are applied.
Behaviors include the following:
Throttling: Determines the number of threads, instances, and messages that can be processed by a service concurrently.
Security: Determines the security characteristics.
Instancing: Determines the number of instances of the service implementation class to be created.
- Per Call: A new service instance will be created and destroyed for every call.
- Per Session: A new service instance will be created per client and maintained throughout the life time of the session. A service instance will not be shared.
- Single: A single service instance will be shared among all clients during the life time of the application.
Error Handling: Lets you determine how errors will be handled when encountered and if they should be returned to the calling application.
Concurrency: Controls the number of threads that are active within an InstanceContext at any given time.
- Multiple: Each instance of the service can have multiple threads that are concurrently processing messages.
- Single: Each InstanceContext can have only one thread that is processing messages at a time.
- Reentrant: Each instance of the service can only process messages one at a time but can accept re-entrant operation calls.
Transactions: Determines if the service can accept and execute a transaction from the client. Transactions are controlled by the client, meaning that the client will tell the service if it can accept and execute a transaction and also controls the lifetime of the transaction.
When developing WCF services we need to understand how to link Object Oriented and Service Oriented together. The term classes and interfaces are extremely familiar to the object oriented developer, and they are still used when developing WCF services. This is the OO part and SO part comes in when you apply the WCF attributes to define entities.
Note: .Net is Component Oriented language. It includes Object Oriented principles and it supports Service Oriented features.
The following class defines and object oriented interface:
public interface CoolService
{
decimal CalculateShipping(string state,int shipType)
{
//do something
}
decimal CalculateTax(string state,decimal bookCost)
{
//do something
}
}
C# now comes the SO part, which is to add necessary attributes used to designate this interface as WCF contract which is following:
[ServiceContract]
public interface CoolService
{
[OperationContract]
decimal CalculatingShipping(string state,int shipType)
{
//do something
}
[OperationContract]
decimal CalculateTax(string state,decimal bookCost)
{
//do something
}
}
We will discuss about [ServiceContract] and [OperationContract] attributes later.
Service Model: WCF service model is very similar to the web service model. Using the service model, you specify, how to communicates and what the service can do. The only difference is the naming of the parts. In WCF, they are not called Service, Binding and PortType. In WCF, they are called Address, Binding and Contract.
A service is an application or piece of software that communicates with other services or applications. The service has one or more endpoints. Each of these endpoints contains an Address, Binding and Contract.
This service model is provided by the System.ServiceModel namespace.
System.ServiceModel: In WCF, the System.ServiceModel namespace is used to model and develop the service application and how it communicates.This namespace provides a large number of classes that allow developers to be flexible with respect of how their service will be developed.
The following are the commonly used classes used to model and build your service.
- BasicHTTPBinding: The binding that service endpoints can use to communicate with clients and web services (ASMX).
- NetMsmqBinding: The binding that service endpoints can use to communicate with MSMQ clients and other services.
- NetNamedPipeBinding: The secure binding that service endpoints can use to communicate with clients/services on the same machine.
- NetTCPBinding: The secure binding that service endpoints can use to communicate with client service across machines.
- WSHTTPBinding: The binding that service endpoints can use to communicate with client/services using distributed transactions and secure and reliable sessions.
- EndPointAddress:The mean by which a unique address is provided and accessible to clients for communication with the endpoint.
- EndpointAddressBinding: The mechanism in which to create new endpoint addresses with specific property values.
- ChannelFactory: The mechanism in which different type of channels are created and managed and made available to clients to send messages to endpoints.
- Identity: The means by which and identity is specified, enabling authentication between endpoints when messages are exchanged.
- Message Header: Represents the contents of a SOAP message header.
- ServiceHost: The mechanism by which a host is provided for services.
- ReliableSession: Provides access to the properties of a reliable session binding element. This is only available when using one of the predefined bindings.
The following is the list of more commonly used classes to define the communication of your service.
- Address Header: A header that contains information used to identify and communicate with an endpoint.
- AddressHeaderCollection: A collection of address headers.
- Binding: A collection of binding elements, each binding defining how an endpoint will communicate with the outside world.
- BindingContext: Provides address and binding information needed to build channel factories and channel listeners.
- BindingElement: Represents a binding element, which is used to build bindings.
- Custom Binding: Used to define and build a custom binding from a set of binding elements.
- Message: A unit of communication between endpoints.
- MessageHeader: The content of a message SOAP header.
- MessageHeaders: A collection of message headers.
class TestWCFApp
{
static void Main()
{
Uri baseAddress = new Uri(ConfigurationManager.AppSettings[“address”]);
AddressHeader ah =
AddressHeader.CreateAddressHeader(“service1”,”http://localhost:8080/service”);
EndpointAddress ea = new EndpointAddress(new
Uri(“http://localhost:8081/testservice/service”), ah);
ServiceEndpoint se = new
ServiceEndpoint(ContractDescription.GetContract(typeof(BookOrderService)), new
WSHttpBinding), ea);
ServiceHost sh new ServiceHost(typeof(BookOrderService), baseAddress);
sh.Description.Endpoints.Add(se);
sh.Open();
sh.close();
}
}
The AddressHeader class is used to define an address header for the endpoint. The
endpoint is then defined using the address header. A service endpoint is then defined, followed by the
defining of a service host, which is used to provide a host for the service being created. The endpoint
description is then set, and finally the service host is opened, which creates listeners and starts listening
for messages.
System.Transactions: Transactions provide a way to gather a set of operations and package them into a single unit of execution. A transaction event must have the following properties.
- Transaction must be atomic, that means all the operations in the transaction must complete successfully and be committed. If any one of the operations fails, all the operations get rolled back to their previous state.
- Transactions must be consistent, in that the operations in the transaction correctly change the state of system.
- Transactions must be isolated, that means one operation within the transaction can not see the result of another operation within the transaction.
- Transaction must be durable, that means anything committed to a managed resource must be survive a failure. Surviving the failure means that no damage has been done to the resource if the operation fails (such as changing data in the database).
SvcUtil.exe: It a handy utility provided by .Net. It does two things:
- Create service model code for your metadata documents.
- Creates metadata documents for your service code.
Once you go to Visual Studio Command Prompt just type SvcUtil/? it will show all the options and their usage.
WCF Programming Methods: WCF supports number of different methods of programming each with pros and cons. There is always more than one way to accomplish something. e.g. you can specify an endpoint in the code or in the configuration file.
There are three common methods of developing WCF service:
WCF Programming Methods: WCF supports number of different methods of programming each with pros and cons. There is always more than one way to accomplish something. e.g. you can specify an endpoint in the code or in the configuration file.
There are three common methods of developing WCF service:
- Declarative
- Explicit
- Configuration
[ServiceContract]
public interface CoolService
{
[OperationContract]
decimal CalculateShipping(string state, int shiptype)
{
//do something
}
[OperationContract]
decimal CalculateTax(string state, decimal bookcost)
{
//do something
}
}
public interface CoolService
{
[OperationContract]
decimal CalculateShipping(string state, int shiptype)
{
//do something
}
[OperationContract]
decimal CalculateTax(string state, decimal bookcost)
{
//do something
}
}
for declarative programming, attributes are added and shown in the following:
[ServiceContract(Session=true)]
public interface coolservice
{
[OperationContract(IsOneWay=true)]
decimal CalculateShipping(string state, int shiptype)
public interface coolservice
{
[OperationContract(IsOneWay=true)]
decimal CalculateShipping(string state, int shiptype)
{
//do something
}
[OperationContract(IsOneWay=true)]
decimal CalculateTax(string state, decimal bookcost)
{
//do something
}
}
//do something
}
[OperationContract(IsOneWay=true)]
decimal CalculateTax(string state, decimal bookcost)
{
//do something
}
}
Explicit: It lets you work directly with all of the many classes and interfaces provided by the WCF object model. Working directly with the object model gives you as a developer much more flexibility and control over your code and this is much more extensive than that of attributes or using configuration files.
The following is the sample example how to create and start a service using the object model.
Class TestApp
{
Uri baseAddress=new Uri(ConfigurationManager.AppSettings["adddres"]);
AddressHeader=ah=AddressHeader.CreateAddressHeader("service1","http://localhost:8080/service");
EndpointAddress=ea=new EndpointAddress(new Uri("http://localhost:8081/testservice/service"),ah);
ServiceEndpoint se = new
ServiceEndpoint(ContractDescription.GetContract(typeof(BookOrderService)), new
WSHttpBinding), ea);
ServiceHost sh new ServiceHost(typeof(BookOrderService), baseAddress);
sh.Description.Endpoints.Add(se);
sh.Open();
sh.close();
}
Note: We will discuss in details later about the code.
Confuguration: Just like declarative programming, there are many things that you can specify regarding the behavior of a service via the configuration file of the service. The good thing using configuration file is that any changes do not necessitate a recompile of the service.
The following example uses configuration file to declare a service endpoints with an address, binding and contract.
<?xml version="1.0" encoding="UTF-8" ?>
<Configuration>
<System.serviceModel>
<services>
<service type="MyTestService">
<endpoint address="http://localhost:8080/MyTestService/" bindingConfiguration="usingDefaults"
binding="MyTestBinding" contract="MyTestService">
</endpoint>
</service>
</system.serviceModel>
</configuration>
WCF indeed have an execution order. First, attributes are applied. Second, settings from the configuration file are applied. Settings in the configuration file will override those of the attributes if there is a conflict. Lastly code executed.
WCF Programming Levels: WCF model offers the developer several options as to the level of control when dealing with data types, parameters, return values and overall development of WCF service.
.Net Remoting: It s feature of .net framework which provide a way to send object over the network in the binary format. Its Microsoft proprietary and it uses it proprietary protocol to send data over the network. It means two systems can send/receive to each other.
Benefits of Remoting: .Net remoting benefits are following:
The following is the sample example how to create and start a service using the object model.
Class TestApp
{
Uri baseAddress=new Uri(ConfigurationManager.AppSettings["adddres"]);
AddressHeader=ah=AddressHeader.CreateAddressHeader("service1","http://localhost:8080/service");
EndpointAddress=ea=new EndpointAddress(new Uri("http://localhost:8081/testservice/service"),ah);
ServiceEndpoint se = new
ServiceEndpoint(ContractDescription.GetContract(typeof(BookOrderService)), new
WSHttpBinding), ea);
ServiceHost sh new ServiceHost(typeof(BookOrderService), baseAddress);
sh.Description.Endpoints.Add(se);
sh.Open();
sh.close();
}
Note: We will discuss in details later about the code.
Confuguration: Just like declarative programming, there are many things that you can specify regarding the behavior of a service via the configuration file of the service. The good thing using configuration file is that any changes do not necessitate a recompile of the service.
The following example uses configuration file to declare a service endpoints with an address, binding and contract.
<?xml version="1.0" encoding="UTF-8" ?>
<Configuration>
<System.serviceModel>
<services>
<service type="MyTestService">
<endpoint address="http://localhost:8080/MyTestService/" bindingConfiguration="usingDefaults"
binding="MyTestBinding" contract="MyTestService">
</endpoint>
</service>
</system.serviceModel>
</configuration>
WCF indeed have an execution order. First, attributes are applied. Second, settings from the configuration file are applied. Settings in the configuration file will override those of the attributes if there is a conflict. Lastly code executed.
WCF Programming Levels: WCF model offers the developer several options as to the level of control when dealing with data types, parameters, return values and overall development of WCF service.
- Typed: With typed services , parameters and return types can be simple or complex data types. Service operations are very similar to functions, in that parameters and return values are used. Developers do not need to deal with messages directly. In fact, serialization and de-serialization of the parameters are return values happens automatically, but you also have the ability to use message contracts if you need a bit more control of the parameters and return values.
- Untyped: Untyped services are like functions, such that operations have parameters and return types. The difference with untyped service is that the parameters and return types are messages, not data types.Another difference between two types is that at this level the developers can access the messages directly providing more control over the sending and receiving of messages. You do not have this level of control at the typed level. Developer must have the ability to use message contracts.
- Messaging: You would program at this level that you need to have access to more than what the first two levels provide. e.g. if you need to create our own routers, you must program at this level because the other two levels do not support these operations.
.Net Remoting: It s feature of .net framework which provide a way to send object over the network in the binary format. Its Microsoft proprietary and it uses it proprietary protocol to send data over the network. It means two systems can send/receive to each other.
Benefits of Remoting: .Net remoting benefits are following:
- No communication process that means no data conversion while sending object/data over the network and no data conversion while receiving as well.
- Excellent performance.
- High security because no one else knows the format of data while transferring over the network.
- .Its .Net to .Net (Only one .Net program can communicate to another .Net program only.) It is not universal.
- It might not be firewall friendly because format of sending and receiving data the firewall might know know. So whatever format or data it does not know it blocks.
- 1980- Object Oriented techniques came into programming. ( language like C++)
- 1990 - Component based techniques came in programming. ( Like .net Language are component based)
- 2000 - Service oriented. ( like Web services, Windows services and now WCF services)
The biggest service oriented software is cloud operating system. Cloud concept is possible because of services.
Service Oriented: Service oriented is having following features.
- Self contained business functions/methods.
- Functionality exposed via a structured message scheme.
- Not just XML and HTTP. It can support XML, SOAP, JSON, images, TCP, Queue etc.
- Service oriented focuses on send & Receive.
- It moves from client/server to sender/receiver model.
- It provide rich communication pattern and functionality.
- Big win in messaging independence.
For example: A client makes a request and server sends a response. If anytime server data get updated, then the updated data will be sent to the client without requesting again.
.Net supports for developing distributed program. It provides the following three concepts.
- .Net Remoting
- Asp.net Web Services
- WCF
Remoting offers the following different formatters:
- Binary - Microsoft proprietary
- SOAP - Public
Common Channels we use in WCF services:
- HTTP (Hyper Text Transfer Protocol): This is very common and popular protocol in services. To make distributed program firewall friendly we use HTTP but it provides less security. HTTP is used for WAN.
- TCP (Transfer Control Protocol): It is fast communication protocol and provides high security. We use it in .Net Remoting when we send data in binary format. Both client and server programs must be CLR based (.Net programs). TCP can be used in LAN and MAN.
- IPC (Inter Program Communication): It is the fastest communication and provides high security. It carries data in single system. Like MS-Word and MS-Excel applications communication.
2. ASP.Net Web Services: It follows open standard (XML web service specification). .Net to non .Net distributed application can be developed. It provides low performance and security with additional installation and libraries we can get secured environment to an extent but with less feature and performance.
It provides SOAP formatter and
Addresses: Every endpoint must have an address so that other programs can communicate with it. Address tells the outside world where it is hosted. We discuss the following points in addresses.
Addresses: Every endpoint must have an address so that other programs can communicate with it. Address tells the outside world where it is hosted. We discuss the following points in addresses.
- Address types
- Address formats
- Programming addresses
WCF Addresses: There are three components that make up an endpoint. Those three are the address, binding and contract. Address will be the most important component of the endpoint because without the address, you would not be able to find the endpoint to begin with, the endpoint is basically useless without address.
Using the address, we can find endpoint and get to it to be able to use it and this is what the address does. Every endpoint must have an address to which endpoint is associated. This allows client applications to find and identify the endpoints of a service.
Taking a look at an endpoint address, it contains the following:
- Transport protocol, or scheme, such as http:
- The name of the machine running the service, such as //localhost or www.myservices.com
- The path to the specific service endpoint, such as /MyWcfservice
http://mymachine:8080/myservice
or
http://mymachine/myservice
It would be noted that there can be an optional part, the port, over which the service is being addresses. The port will be specified after the machine name.
To understand the addresses, you also need to know the different types of addresses, which are the following:
Address Types: WCF lets you use several types of addresses to associate with each endpoint, and it is through these addresses that the client communicates with the endpoint.
Endpoint Address: An endpoint address specifies the address of a specific service endpoint. Client can access the service via the endpoint address such as following:
http://mymachine:8080/myservice
Once the client has accessed the service via the endpoint address, the client can talk to the service and all communication to and from the service goes through this endpoint at this address.
Base Address: It provides a way to specify a single, primary address for a given service and assign relative addresses to each individual endpoint. Let say you have a service with three exposed endpoints. you can assign a given service the following primary or base address.
http://mymachine:8080/myservice
with the base address assigned to the service, you can then assign the three endpoints the following relative addresses:
http://mymachine:8080/myservice/service1
http://mymachine:8080/myservice/service2
http://mymachine:8080/myservice/service3
The base address is associated to the service, allowing you to assign relative addresses to the individual endpoint.
MEX Address: MEX addresses allow a client to gather information about a particular service. MEX, meaning metadata exchange, is an HTTP endpoint address used to obtain service information. e.g. the following address is an MEX address:
http://mymachine:8080/myservice/mex
MEX address provides the client a way to obtain information about the service. This information is provided through the service metadata, which describes the service.
Address Formats: Endpoint addresses are formatted on the selected transport used in communication. The transport or scheme is the part of the address that specifies and determines the transport that will be used. The developer who can choose the address and how it is deployed. It is important to remember that no matter the format, the client must be able to get to the address to get and consume the service.
There are two things to keep in mind as you develop a service:
- The environment in which the service will be hosted. A specific transport might need to be used.
- Where the address will be specified. You have the option of storing it in configuration file or you can hard-code it into the application. Good practice is to put it in configuration file.
- Scheme/Transport: The scheme that specifies the protocol.
- Domain Name: A fully qualified domain name. Typically during development this portion of the address would contain localhost or a specific machine name.
- Port: If you plan on running the service on a specific port, it is specified in this portion. If left out, it is default port 80.
- Path: The specific path to the service. Multiple paths can be specified by separating each path with a forward slash ( / ).
What makes them unique in and of themselves in their scheme, which identifies the protocol, and how they are used.
HTTP Address: One of the most common format for a service is that of an HTTP address. The format of an HTTP address is shown as follows:
http://domainname|machinename [:port]/path
The HTTP format contains four parts. Like following:
http://www.sqlxml.com:8080/myservice
An caution that is recommended that you run your service on a port other than 80 so that there are no conflicts with IIS on that port.
HTTPS Address: HTTP address can be secured by using SSL (Secure Socket Layer), which are then specified as HTTPS. HTTPS address formats are no different than normal HTTP addresses like following:
https://www.sqlxml.com:8080/myservice
When using HTTPS, you are required to obtain a certificate from a valid certificate authority such as Verisign or Thawte.
TCP Address: The format of the TCP address is as follows:
net.tcp://www.sqlxml.com:8080/myservice
MSMQ Address: The MSMQ address format differs from the others a bit. The format of the address is following:
net.msmq://hostname/[private]/queue-name
An example is following:
net.msmq://localhost/msmqshare/bookorder
In this address format, the following parts are identified:
- Scheme/Transport: The scheme that specifies the MSMQ protocol.
- HostName: A fully qualified domain name of the machine running MSMQ or localhost if MSMQ installed on local machine.
- [private]: This is optional but when used it contains the address of a target queue that is a private queue. This value is not specified when accessing a public queue.
- Queue-name: The name of the MSMQ queue.
Named Pipe Address: The Named Pipe address is formatted as follows:
net.pipe://localhost/myservice
There are two things to notice about this address format:
- There is no port number. This is because ports don't matter in Named Pipe addresses. They really don't benefit the address or add any value at all.
- Communication using named pipes cannot be "cross-machine" meaning between two separate machines.
http://domainname|machinename [:port]/virtualdirectoryname [.svcfilename]
The following list explains the part of an IIS address:
- Scheme: The scheme that specifies the HTTP protocol.
- Domain Name: A fully qualified domain name. Typically during development this portion of the address would contain localhost or a specific machine name.
- Port: If you plan on running the service on a specific port, it is specified in this option. If left out, it defaults to port 80.
- Virtual Directory Name: The name of the virtual directly where the service is residing.
- Service filename: The name of the service (.svc) file.
http://www.sqlxml.com/myservice/coolservice.svc
In an IIS address, the service (.svc) file is what defines the service, that is how the service is hosted and referenced.
Programming WCF Addresses:
Programming WCF addresses provides additional flexibility when working with endpoints and services because you can also Programmatically define and manipulate base addresses.
It is the best practice to define endpoints in configuration file.
Endpoint Address Class: Endpoint address class provides mechanism for uniquely identifying service endpoints. In its simplest form, an address is a URI (Uniform Resource Identifier) but can also contain an identity and a collection of headers.
The optional identity property allows for the authentication of an endpoint by other endpoints so that messages can be exchanged between endpoints. The header collection although optional, provides additional addressing information. An endpoint is specified by its URI address, but there are occasions when endpoints might share the same URI, multiple instances of the service have an endpoint that share the same address. It is in these cases where a header collection comes in handy by providing additional address information on top of information already specified by endpoint. This information would include issues such as how to handle incoming messages and what endpoint should process the message. e.g.
The following is a simple example of the Endpoint Address used to create a new instance of the class, specifying a URI string of an address:
EndPointAddress ea=new EndPointAddress("http://localhost:8080/testservice/service");
Identity Property: The identity property sets the identity for the associated endpoint used to authenticate it. This property is optional, but when included it specifies the identify of the service that is being accessed and called by the client. This value is used by the client to verify the validity of the service.
When the client begins the communication process with a service endpoint, the service endpoint then authenticates itself with the client. At this point an identity comparison takes place. The client compares the value of the endpoint identity with the value that was returned to the client via authentication process. If everything matches, communication flows continue between client and endpoint because the client at this point knows that it is communicating with the appropriate and correct endpoint. This prevents client from being redirected to the wrong endpoint.
There are six types of identities they are in the following table:
|
Identity Type
|
Description
|
|
DNS (Domain Name Service)
|
Checks the specified credential in the DNS name
|
|
Certificate
|
Returns an X.509 certificate value that is compared on the
client
|
|
Certificate Reference
|
The same as the Certificate option except that this option
allows you to specify the name and store location from which to obtain the
certificate.
|
|
RSA
|
Returns an RSA key value to compare on the client
|
|
UPN (User Principle Name)
|
Returns the UPN under which the service is running
|
|
SPN (Service Principle Name)
|
Returns the SPN associated with the service’s account
|