rjrizzuto
rjrizzuto

Reputation: 71

protobuf versions and DateTimeOffset

I have an application that was using protobuf-net version 1.0.0.278, and I have an object that has this field in it:

    [ProtoBuf.ProtoMember(6)]
    public virtual DateTimeOffset? CreatedDate { get; set; }

I do not know for sure if this was being properly serialized and deserialized when serializing/deserializing the object that contained it, but there was no exception raised on either operation.

Recently I updated to protobuf-net version 2.0.0.621, and now I get a System.InvalidOperationException calling ProtoBuf.Serializer.PrepareSerializer<>. The message says "No serializer defined for type: System.Nullable`1[[System.DateTimeOffset, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]".

Is there a protobuf-net native way to serialize this type? Is there any reason why this behavior changed?

Upvotes: 3

Views: 970

Answers (1)

rjrizzuto
rjrizzuto

Reputation: 71

I created this surrogate class:

[ProtoContract]
public class DateTimeOffsetProxy
{
    [ProtoMember(1)] public DateTime UtcTime;
    [ProtoMember(2)] public TimeSpan Offset;

    public static implicit operator DateTimeOffsetProxy(DateTimeOffset value)
    {
        return new DateTimeOffsetProxy()
        {
            UtcTime = value.UtcDateTime,
            Offset = value.Offset
        };
    }

    public static implicit operator DateTimeOffset(DateTimeOffsetProxy value)
    {
        var result = new DateTimeOffset(value.UtcTime);
        return result.ToOffset(value.Offset);
    }
}

Then I registered it:

        Model = RuntimeTypeModel.Default;
        Model.Add(typeof(DateTimeOffset), 
                  false).SetSurrogate(typeof(DateTimeOffsetProxy));

That seems to work pretty well.

Upvotes: 2

Related Questions