Bug 21072

Summary: DataContractSerializer does not serialize enum flags the same as .net 4
Product: [Mono] Class Libraries Reporter: Chris Turner <cdturner567>
Component: WCF assembliesAssignee: marcos.henrich
Status: RESOLVED FIXED    
Severity: normal CC: alexrp, marcos.henrich, mono-bugs+mono
Priority: ---    
Version: unspecified   
Target Milestone: Untriaged   
Hardware: PC   
OS: Windows   
Tags: Is this bug a regression?: ---
Last known good build:

Description Chris Turner 2014-07-03 02:26:59 UTC
give an enum flags 

   [Serializable]
    [Flags()]
    public enum PortalNotifications
    {
        None = 0,
        TardyAlerts = 0x10,
        IncidentAlerts = 0x20,
        All = 0xffff,
        UseCurrent = 0x10000
    };


[Serializable]
public class DeviceNotifications
{
      public PortalNotifications NotificationsType = PortalNotifications.All;
}


.net 4 when serializing the value PortalNotifications.All will generate a single entry in the xml
<NotificationsType xmlns="http://schemas.datacontract.org/2004/07/PSRMWebService.Model.Version1">All</NotificationsType>

Xamarin datacontractserializer will serialize all applicable flag values
<NotificationsType xmlns:d2p1="http://schemas.datacontract.org/2004/07/PSRMWebService.Model.Version1">None TardyAlerts IncidentAlerts All</NotificationsType>


I assume the .net 4 one looks for exact matches first.


below is the code we use to do the serialization. On the server the deserialization is done automatically via MVC webapi
    protected void SerializeToString(object Data, Type DataType, out int DataLength, out string DataString)
        {
            DataLength = 0;
            using (var MS = new MemoryStream())
            {
                // default text encoding is UTF-8 apparently
                DataContractSerializer ser = new DataContractSerializer(DataType);
                ser.WriteObject(MS, Data);

 		byte[] Buffer = MS.ToArray();
		long Length = Buffer.LongLength;

		// the length parameter is becuase the buffer is a set size...
                DataString = Encoding.UTF8.GetString( Buffer, 0, (int) Length );

		// this looks hokey, it is, the datacontractserlializer is supposed to default to utf-8 but
		// some builds of monotuch it puts a double byte mark at the start. so we remove it otherwise
		// it wont deseaerlize
		if ( (int) DataString[0] > 65000 )
		{
		    DataString = DataString.Substring( 1 );
        	}

		DataLength = DataString.Length;
            }
        }



hopefully this is readable enough. We are basically using the standard datacontractserializer and writing it to a memorystream.
Comment 1 Chris Turner 2014-07-08 19:01:06 UTC
the .net enum encoder always seems to look for an exact match in flags first, then it looks for partial matches.
Comment 2 marcos.henrich 2014-11-27 08:09:36 UTC
Hi Chris,

Thank you for the detailed bug report.

The pull request for this issue can be found in the link below.
https://github.com/mono/mono/pull/1431