Saturday, September 4, 2010

Enum usage in WCF

On working in a defect tracking tool using WCF, I faced a weird problem and thought it might be interesting to you.

Application throws service connection error when I used enums in data contract. The real problem was: DefectStatus
enums was assigned with int values. Itz started by 1 instead of 0. Obviously WCF requires that there is an enum value equal to 0 for serialization. If not, server layer won't get that to your client through WCF - strange but true!

On analysing this problem, there is a work around and a solution. Work around is simiple to start with zero as follows.
public enum DefectStatus
{Unknown = 0,Open = 1,Assigned = 2}

Solution is to put [ServiceKnownType(typeof(Enum))] attribute on the service interface contract, and also add the [EnumMember] attribute to every enum value within the Enumeration data contract
[ServiceKnownType(typeof(DefectStatus))]
public interface IDefectMaintenace
{
}

public enum DefectStatus
{
[EnumMember()]
Open = 1,
[EnumMember()]
Assigned = 2
}

Root cause for the problem is defined in msdn as 'enumeration types can be marked with the DataContractAttribute attribute, in which case every member that participates in serialization must be marked with the EnumMemberAttribute attribute. Members that are not marked are not serialized'. Ref is:
http://msdn.microsoft.com/en-us/library/ms731923.aspx

No comments:

Post a Comment