Search code examples
wcfdatacontract

DataContract classes uninitialized at client side


I have the following class I'd like to send from my WCF (C#) service to my client (WPF):

[DataContract]
    public class OutputAvailableEventArgs
    {
        [DataMember]
        public int ID { get; set; }
        [DataMember]
        public string Message { get; private set; }
        [DataMember]
        public bool IsError { get; private set; }

        public OutputAvailableEventArgs(int id) : this(id, false, "") { }

        public OutputAvailableEventArgs(int id, string output) : this(id, false, output) { }

        public OutputAvailableEventArgs(int id, bool isError, string output)
        {
            ID = id;
            IsError = isError;
            Message = output;
        }
    }

It's used by the service as follows:

var channel = OperationContext.Current.GetCallbackChannel<IClientCallback>();

channel.OutputAvailable(new OutputAvailableEventArgs(1, false, "some message"));

At the client side, the members get their default values.
I tried marking them with IsRequired attribute but now the OutputAvailable at the client is not called. The code at the service side seems to run smoothly (I didn't notice anything with the debugger).

How can I transfer a DataContract class with WCF while maintaining the members' values?
(I saw solutions that suggested to use OnSerialized and OnDeserialized but I don't need just a default constructor.)


Solution

  • I saw many different solutions for this problem. For other people's sake I'll write some of them down + what worked for me:

    1. It seems that in some cases specifying the items' order solves the problem. Please see this SO question for full details.
    2. If it's some default initialization you're after, you can use OnSerialized and OnDeserialized methods to call your initialization methods.
    3. I also tried using the IsRequired attribute on my DataMembers but still didn't get my objects.

    What worked for me was adding NameSpace property in the DataContract attribute. Apparently, In order to have the contracts be considered equal, you must set the Namespace property on the DataContract to the same value on both sides.