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

BCDEDIT VHD error "The configuration for an element"

I used BCDEDIT to boot from my VHD. OS= Win7. But I got this error when I restarted my machine:
"The configuration for an element within the object is invalid in the boot configuration data store".

Problem: My C:\ drive had bitlocker enabled.

Solution: 1) Use partitions with no bitlocker.
                2) or Use External Sata drives (not usb)

in my case I only had a single drive. Nor did I have Sata external drives. So I disabled bitlocker on C:\ (it took 3 hours or so) and partitioned my hard disk(E: Drive). Renabled bitlocker on C:\ drive.

Wednesday, December 28, 2011

Ambiguous match found - VS2003 to VS2005/VS2010 conversion mystery resolved!!

So I converted from vs2003 to VS2005 (as well as VS2010) and got this infamous 'Ambiguous match found error'!

The error message clearly pointed to the first user control registered in my web page. So the problem should be with that user control!
I tried to solve it for a couple of hours -> failed -> googled/binged.
1) Some people said remove the control/ user control declarion from code behind because vs2005 automatically adds the user control.
but if I remove the declaration then how can I use the control in code ( I get compile time error)

2) Some users said they had declared the control two times in the code behind page (same name with different case)
and I searched every where for the second declaration but could not find any.

3) Another bunch of users found the control re-declared in designer.cs
but I could not create/find this designer.cs !!
mine was a class library (with .ascx pages) hence I dont get the convert to web application option (when right clicking project/ascx-page). There were tweaks to change class library to webapplication so that I get the option(convert to web application) but did not work for me.

now what!!
well, I did the good old method of commenting all the html and uncommenting section by section to see where it fails.(only in the .ascx , did not touch the code behind)

Surprisingly I found the page working with the erroneous control(in the first error message) still present but some other parts of the page commented. That was when I realized the truth, .Net was bluffing me! and pointing me towards the wrong user control!
I slowly uncommented line by line and pin pointed error:-
  protected RequiredFieldValidator rfvDateCheck;
  protected RequiredFieldValidator RfvDateCheck;
Bingo!!
one random control was declared twice but not the one shown by the .net error message!
So what people were telling on blogs and forums were correct but just that I was searching for the wrong control!




Thursday, December 15, 2011

Revert back to default theme in Sharepoint 2010 programmatically

We can set a custom theme in this manner:
SPWeb objectWeb = objectSite.OpenWeb();
ThmxTheme.SetThemeUrlForWeb(objectWeb , "/_catalogs/theme/CustomTheme.thmx", true);

what if we want to revert back to default theme?
call the method again with a null parameter:
ThmxTheme.SetThemeUrlForWeb(web, null, true);

Monday, December 12, 2011

Fix “Windows cannot access the specified device path or file” error

I copied an exe file from a remote machine to my virtual machine(windows server 2003). And when I try to run or 'run as' I get this strange error "Windows cannot access the specified device path or file." The error also says I dont have permission when I am logged in as administrator!



Solution: Right click exe -> properties and click the 'unblock' button and that is it!

Monday, December 5, 2011

Virtual PC 2007 compatibility Error

While installing Virtual PC 2007 if you get a compatibility error : "This program is blocked due to compatibility Issues" , then you need to do the following.

1) Uninstall Windows XP Mode (if present)
2) Uncheck Virtual PC in windows features
3) Uninstall Virtual PC update (KB...559)

Restart machine and install Virtual PC 2007 (64/32 bit)

Saturday, November 26, 2011

End-to-end vs point-to-point security in WCF

Consider a scenario where a message needs to be send from A to D. The message goes from A to B and from B to C and finally reaches D (from C).

The whole chain of communication from A to D can be called end-to-end. For this to happen we should give protection at message level
in WCF this can be done as follows :-

BasicHttpBinding bind = new BasicHttpBinding();
bind.Security.Mode = BasicHttpSecurityMode.Message


Point-to-Point communcation is what happens from A to B and this is done using transport level security

BasicHttpBinding bind = new BasicHttpBinding();
bind.Security.Mode = BasicHttpSecurityMode.Transport


Alternatively in config files(using wsHttpBinding as example) :-
<wsHttpBinding>
<binding name="TransportSecurity">
    <security mode="Transport" />
       <transport clientCredentialType = "Windows" />
    </security>
</binding>
</wsHttpBinding >

Thursday, November 3, 2011

Are Digital Certificates Confusing?

Public key, hashing, signatures blah blah ..really confusing aren't they?

Here we go!
Foo wants to send Assange a letter, only to be read by Assange. Yes, a very secret document for his drop box! Foo decides to encrypt the message. But which algorithm will Foo use and how will Assange know about the algorithm(to decrypt)? More over Intelligence Agencies (IA) are spying, so Foo cannot call Assange and say "Hey, I am using XOR".

Assange has a public encryption key(key = complex mathematical formulas to make data unreadable). Anyone can encrypt with the key and only Assange can read it. How? Public key has a pair called private decryption key, which helps to decrypt the message. And Assange won't share his private key.

Foo gets Assange's public key. Encrypts the message and sends it to Assange.  IA got the message before Assange, but fortunately they could not read it. And we know why :)

Happy ending is it not? But Assange received the wrong message!
IA destroyed the message on it's way to Assange's inbox and replaced it with another message using Assange's public key. And Assange mistook it for Foo's message!

[to be continued .. but meat to bite on-> how can such situations be prevented?]
Clue: What if we make the decryption key public and encryption key private! Plus we need to do one more thing.. think layering :). Oh! is that what we call a signature? And could these certificate thingies be outsourced to an external agency? Well... can't call it confusing anymore.. can we? :D
Comment your thoughts please :)