Friday, December 30, 2011

Data Contracts vs Message Contracts : A beat-abt-d-bush approach!

The idea is to cover EVERYTHING with out going into detail.
A) Learning effort comparison

Data Contracts are easy to learn. Easy to visualise a scenario where data contracts can be used. Less points to cover. But DataContract(default serialzer in WCF and prefered in .Net) has competitors such as Serializable & XmlSerialzer. Quick way to compare will be: Iserializable is old, Data Contracts is new and has more features. XmlSeriazer can be used in WCF if you need less features than DataContracts but more control over XML that is generated.

Message contracts are comparatively difficult to learn. Message Contracts are used in  not-so-familiar scenarios. More learning points.
B) Definition Comparison

Data Contracts: Service tells client what kind of data is exchanged. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts. "Is the data Serialized?" is often asked in data contracts.
eg: an integer data-type might be available in both Service and the client. But a
 'Account' class with 2 properties namely 'credit' and 'debit' may not be available in client. Use Data Contract in this scenario. Teaser: what is the use of KnownTypes then? ;)

Message Contracts: The focus is on the structure of a message rather then the contents.
Sometimes complete control over the structure of a SOAP message is just as important as control over its contents."Is it serialized?" is not important but "how or where or the format of serialization" is what you want to know in Message Contracts.
eg: The client wants to move some data from the body to the header. They think it is more secure in the header.

Sometimes you implement a wonderful data contract and then comes a requirement to encrypt a particular field and you are forced to convert data contract to message contract. Clue for KnownTypes teaser above is 'Inheritance'

C) Implementation Comparison (only hints are given)

Data Contract
1) 2 attributes :-
          a) [DataContract] = class/structure/enum level
          b) [DataMember] = for fields/properties
There is infact two more not-so-known attributes
          c) [EnumMember] = Enum members(used with [DataContract]).
          d) [Flag] = oops! I dont know. Something to do with sending multiple enum fields and is applied on enum.
2) Serialisation considerations
            1) EmitDefaultValue: default value to be serialised or not
            2) Order: order of serialization
            3) IsRequired: Must be present when reading or deserializing
            4) etc.
           eg: [DataMember(EmitDefaultValue = false)
3) forward compatiblilty with IExtensibleDataObject
that is all!
[PS] 2 useful tips: 1) Serialization order(alphabetical) : (1)Base Class members ->  (2)members with out 'Order' property -> (3)members with order property (numerically ascending, when common then alphabetical)
                              2) Those members with out [DataMember] are omitted from serializing.

Message Contract
1) 3 Attributes :-
          a) [MessageContract] = class level
          b) [MessageHeader] = for fields/properties
          b) [MessageBodyMember] = for fields/properties
2) Provide a different formatting for array fields with [MessageHeaderArray] attribute(wrapping)
3) Encrypting/signing parts of messages
eg: [MessageHeader(ProtectionLevel=None)]
4) Control how field appears in SOAP representation.
         a) name/namespace:
                     eg: [MessageBodyMember(Name="transactionData")]
                          public BankingTransactionData theData;
         b) wrapping of elements : eg: isWrapped (vs MessageHeaderArray)
5) Header specific properties like Actor, MustUnderstand
             [MessageHeader(Actor="http://auditingservice.contoso.com", MustUnderstand=true)]
               public bool IsAudited;
6) Assigning properties like MustUnderstand through code(dynamic). And when both static and dynamic are present which one will be used. (dynamic overrides static)
7) Order of SOAP body parts appearing in SOAP
Teaser: How is message contract 'order' different from data contracts 'order' property? :)
8) Inheritance consideration: when same name given for fields in parent and child classes which one to take?
9) Performance consideration: can the number of [BodyMembers] be reduced by moving it to sub class,  thus reducing namespaces ?

D) Examples

Data Contracts
 namespace MyTypes
{
    [DataContract]
    public class PurchaseOrder
    {
        private int poId_value;

        // Apply the DataMemberAttribute to the property.
        [DataMember]
        public int PurchaseOrderId
        {

            get { return poId_value; }
            set { poId_value = value; }
        }
    }
}

Message Contracts

[MessageContract]
public class BankingTransaction
{
  [MessageHeader] public MessageHeader<bool> IsAudited;
  [MessageHeader] public Operation operation;
  [MessageBodyMember] public BankingTransactionData theData;
}
// application code:
BankingTransaction bt = new BankingTransaction();
bt.IsAudited = new MessageHeader<bool>();
bt.IsAudited.Content = false; // Set IsAudited header value to "false"
bt.IsAudited.Actor="http://auditingservice.contoso.com";
bt.IsAudited.MustUnderstand=true;

How it works
1) WCF selects a serializer (Default DataContractsSerializer)
2) Apply Attributes(Datacontract,Datamember)
3) Objects are serialized into XML Infoset(intermediate form for all types of end results like XML, Binary, etc)
4) Based on WCF Binding the XML Infoset is converted into the byte representation
 a) BasicHttpBinding + WSHttpBinding = XML
 b) NetTcpBinding -> BinaryXml (xml but less size and less interoperable)
 c) WSHttpBinding->MTOM(raw binary data as attachment in SOAP)

In WCF context there is no stream but data is stored as a SOAP Message(based on a XSD scheme). Step #3 above is done with this Xsd.


And remember there are four type of contracts in WCF we learned two:












-The End- comment your thoughts please

2 comments: