Thursday, February 18, 2010

Notes on Programming WCF - Part V - Instance Management


Excerpts on a great WCF book: "Programming WCF Services- by Juval Lowy"

Instance Management

Instance management is applied by Service Behavior attribute InstanceContextMode which could hold three below values:
1.       Per Call
Pros:
1-      Highly scalable          
Cons:
1-      State overhead
2.       Per Session (WCF default) Similar to client/server model. It cannot serve more than couple of hundreds request at the same time.
1.       Session Modes: this mandates the use of a transport session, and It depends on support of session on bindings (e.g. httpBinding does not have session).
Each proxy and its channels are bound to an instance of the service.
1.       Allowed (WCF Default)
2.       Required
3.       NotAllowed
3.       Singleton

Involved elements in service instance management:
1-      Service context instance mode
2-      Session Mode: transport session mode
3-      Proxy
4-      Binding
5-      Instance deactivation : this is an optimization technique which should be avoided until it’s needed
ReleaseInstanceMode: this is a method level attribute that mandates when to re-instantiate the service instance
a.       None: no impact on instance life
b.      BeforeCall: This mode tells WCF to create a new instance before making the call, this is usually good for create() methods that are initializing
c.       AfterCall: This mode tells WCF to drop the instance after the call is completed, this is usually a good for CleanUp() methods
d.      BeforeAndAfterCall:

WCF Operations, Streaming, Faults - Part IV


Excerpts on a great WCF book: "Programming WCF Services- by Juval Lowy"

Operations:
1- One-Way Operations:
- The methods should return void if they are marked as One-Way
- It is recommended that one-way operations should be applied on per-call or singleton services only.
2- Callback Operations: a.k.a Duplex Operations
- In order to wire a call back to a client it needs to be derived from a proxy with bidirectional communication , DuplexClientBase
i. Client needs to implement the call back interface,
ii. Create an instance off of the interface
iii. Create a new InstanceContext passing the callback instance
iv. Wait for call back while the proxy is still open
class MyContractClient : DuplexClientBase, IMyContract
{
public MyContractClient(object callbackInstance)
: base(callbackInstance)
{ }
//More constructors
public void DoSomething()
{
Channel.DoSomething();
}
}
class MyClient : IMyContractCallback, IDisposable
{
MyContractClient m_Proxy;
public void CallService()
{
m_Proxy = new MyContractClient(this);
m_Proxy.DoSomething();
}
public void OnCallback()
{...}
public void Dispose()
{
m_Proxy.Close();
}
}
Streaming
1- I/O Streams
WCF allows services to stream the reply, request or both.
2- Streaming and Binding
Only TCP, IPC and basic HTTP bindings support streaming.
You cannot use streaming if contract is set to SessionMode.Required
All streaming is off by default even you use Stream which is an abstract class.
To enable streaming set transferMode=”Streamed”
It is most likely required to set maxReceivedMessageSize to proper number (Default is 64K)
Faults:
1- Error Masking:
Client should not care about service errors just need to know something happened.
There are three types of exceptions that clients face dealing with WCF services.
1- Communication errors: bad network, bad uri and etc …
2- Proxy state errors: proxy is closed but is accessed or is faulted and is accesses , contract and binding mismatch, security protection level
3- Service generated errors:
2- Channel Faulting:
- Client can’t even close the proxy after an exception, only proxy.Abort is available
3- Fault propagation:
Using FaultException: T is an Exception (recommended)or any other type. This approach returns a non-CLR compatible type.

Wednesday, February 17, 2010

Notes on Programming WCF - Part III - Client side programming


Excerpts on a great WCF book: "Programming WCF Services- by Juval Lowy"


Client Side Programming:
1- Generating the Proxy
a. Add a reference , point to metadata address click go and then ok to generate proxy and have client config file modified
1. Regenerate by going to service references right click on your service and choose update
b. SvcUtil : the only advantage of this to VS 2008 method (above) is that you can run it before build in a command line
1. When in-proc client and server configuration file could be one
2- WCF provided host
a. WcfSvcHost.exe
3- Working with the proxy
a. Closing the proxy
Always close proxy after being done with it to release the connection held toward the service
Call to Close() could be replaced by calling Dispose() which means we can use
Using (MycontractProxy proxy = new MycontractProxy ())
{
// …
}
Or
IMyContract proxy = new MyContractClient( );
using(proxy as IDisposable)
{
proxy.MyMethod( );
}
b. Call time out
Each call made by a WCF client must complete within a configurable timeout, this offers an elegant way to deal with deadlocks.
The exact value of the timeout is a property of the binding, where the default timeout is one minute. To provide a different timeout, set the SendTimeout property of the abstract Binding base class.
4- Transport Level Sessions
- The transport session is one of the key fundamental concepts of WCF, affecting reliability, instance management, error management, synchronization, transactions and security.
- WCF makes sure that every request from the same client gets channeled through same transport channel,
- This will insure that calls from client are processed in the same order they have been sent
- Transport session is usually closed upon closing the proxy, but if connection breaks there’s a 10 minutes timeout by default,
- If client tries to use the proxy after 10 minutes an exception will be thrown CommunicationObjectFaultedException
- You can reconfigure the idle time time-out through ReliableSession or OptionalReliableSession property from bindings that support the time-out, InactivityTimeout
- If both client and service configure the time-out the shorter period prevails
5- Reliability
Message reliability in WCF does not guaranty message delivery. All it provides is a guarantee that is the message does not reach its destination, the sender will be notified.
Ordered Delivery
WCF guarantees ordering of messages if protocol supports it
6- Client-side proxy hierarchy
- Proxy chaining
- Contract factoring:
Proper contract factoring results in more specialized, loosely coupled, fine-tuned and reusable contracts.

Notes on Programming WCF - Part II - Bindings, Enpoints, MetaDataExchange


Excerpts on a great WCF book: "Programming WCF Services- by Juval Lowy"

Bindings:
WCF defines six frequently used bindings:
1- Basic binding Offered by
1- BasicHttpBinding class
2- Exposes a WCF as legacy ASMX web service
2- TCP binding offered by
1- NetTcpBinding class for
2- cross machine communication on Intranet
3- optimized for WCF-to-WCF
3- IPC binding offered by
1- NetNamedPipeBinding class
2- It uses named pipe as transport for
3- same- machine communication
4- Fastest binding since lighter than TCP
4- Web Service (WS) binding offered by
1- WSHttpBinding
2- Uses HTTP, HTTPS
3- Uses WS-* standards
5- Dual WS Binding offered by
1- WSDualHTTPBinding
2- Bidirectional Duplex
6- MSMQ binding offered by
1- NetMsmqBinding class


Table 1-1. Transport and encoding for standard bindings
Name
Transport
Encoding
Interoperable
BasicHttpBinding
HTTP/HTTPS
Text, MTOM
Yes
NetTcpBinding
TCP
Binary
No
NetPeerTcpBinding
P2P
Binary
No
NetNamedPipeBinding
IPC
Binary
No
WSHttpBinding
HTTP/HTTPS
Text, MTOM
Yes
WSFederationHttpBinding
HTTP/HTTPS
Text, MTOM
Yes
WSDualHttpBinding
HTTP
Text, MTOM
Yes
NetMsmqBinding
MSMQ
Binary
No
MsmqIntegrationBinding
MSMQ
Binary
Yes


Endpoints:
Every service is associated with an address that defines where the service is, a binding that defines how to communicate with the service, and a contract that defines what the service does. This triumvirate governing the service is easy to remember as the ABC of the service. WCF formalizes this relationship in the form of an endpoint.
Endpoint is the ABC of a service
1. Address
2. Binding
1. Binding Configuration
3. Contract
Metadata Exchange
By default, the service will not publish its metadata. However, this does not preclude clients that have obtained the metadata via some other mechanism from invoking operations on the service. A service that does not publish metadata is the WCF analogy to an internal class in .NET.
There are two options for publishing a service's metadata: you can provide the metadata over HTTP-GET, a simple text-based protocol that most platforms support, or you can use a dedicated endpoint.
1- Create WSDL
2- Publish service’s Metadata
i. HTTP-GET : This need the service to have http address
This is enabled through service behavior configuration:
behaviorConfiguration = "MEXGET">
ii. Metadata Exchange Endpoint

Notes on Programming WCF - Part I - Contracts


Excerpts on a great WCF book: "Programming WCF Services- by Juval Lowy"

Contracts
In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does. WCF defines four types of contracts:
1. Service contracts:
Describe which operations the client can perform on the service. Service contracts are the subject of the next chapter, but they are used extensively in every chapter in this book
2. Data contracts:
Define which data types are passed to and from the service.
1. Even if the DataMember attribute on the service side is applied on a private field or property, as shown here:
[DataContract]
struct Contact
{
[DataMember]
string FirstName
{get;set;}
[DataMember]
string LastName;
}
2. The imported definition will have a public property instead.
3. Do not apply the DataMember attribute both on a property and on its underlying field—this will result in duplication of the members on the importing side.
4. A type marked only with the DataContract attribute cannot be serialized using the legacy formatters. If you want to serialize such a type, you must apply both the DataContract attribute and the Serializable attribute on it. In the resulting data contract for the type, the effect will be the same as if only the DataContract attribute had been applied, and you will still need to use the DataMember attribute on the members you want to serialize.
5. Inferred data contracts are sometimes called POCO, or Plain Old CLR Object.
6. Data Contract Events
7. OnSerializing attribute designates a method to handle the serializing event
8. OnSerialized attribute designates a method to handle the serialized event
9. OnDeserializing attribute designates a method to handle the deserializing event
10. OnDeserialized attribute designates a method to handle the deserialized event
11. Failing to designate every level in the class hierarchy as serializable or as a data contract will result in an InvalidDataContractException at the service load time.
12. Known Types:
In traditional object-oriented programming, a reference to a subclass is also a reference to its base class, so the subclass maintains an Is-A relationship with its base class. Any method that expects a reference to a base class can also accept a reference to its subclass. This is a direct result of the way the compiler spans the state of the subclass in memory, by appending it right after the base class section. While languages such as C# let you substitute a subclass for a base class in this manner, this is not the case with WCF operations. By default, you cannot use a subclass of a data contract class instead of its base class.
13. Service Known Types:
14. Data Contract Equivalence:
Two data contracts are considered equivalent if they have the same wire representation—that is, if they have the same infoset schema. This can be the case if they define the same type (but not necessarily the same version of the type), or if the two data contracts refer to two different types with the same data contract and data member names. Equivalent data contracts are interchangeable: WCF will let any service that was defined with one data contract operate with an equivalent data contract.
15. Serialization Order:
16. Versioning:
1. New members
2. Missing members
3. Round-tripping
4. Using OnDeserializing() event
17. Required members:
18. Schema compatibility
While implementing IExtensibleDataObject enables round-tripping, it has the downside of enabling a service that is compatible with one data contract schema to interact successfully with another service that expects another data contract schema.
The best practice is to always have your data contracts implement IExtensibleDataObject and to avoid setting IgnoreExtensionDataObject to true. IExtensibleDataObject decouples the service from its downstream services, allowing them to evolve separately.
Unlike ignoring new members, which for the most part is benign, the default handling of missing members may very likely cause the receiving side to fail further down the call chain, because the missing members may be essential for correct operation. This may have disastrous results. You can instruct WCF to avoid invoking the operation and to fail the call if a data member is missing by setting the IsRequired property of the DataMember attribute to true. When, on the receiving side, DataContractSerializer does not find the information required to de-serialize a member marked as required in the message, it will abort the call, resulting in a NeTDispatcherFaultException on the sending side.
3. Fault contracts:
Define which errors are raised by the service, and how the service handles and propagates errors to its clients.
4. Message contracts:
Allow the service to interact directly with messages
1. MaxReceivedMessageSize defaults to 64K. While this is adequate for simple services, services that have many endpoints that use complex types will generate larger messages, causing the call to MetadataExchangeClient.GetMetadata( ) to fail. My experimentations indicate that 5 is an adequate fudge factor for most cases.