show-notice
hide-notice

Friday 5 July 2013

c# ProtoBuf serializer new types




Questions

I am using Protobuf-net to replace my DataContractSerializer, but is it possible to send other object types like Color, Size, Point and maybe more? Because this is possible with the DataContractSerializer. I could not find it in the documentation.


Answers

Firstly, note that a lot of types can be handled automatically as "tuples"; for example, I would expect System.Windows.Point to work fine, because it only has a X and Y, and it has a constructor that takes x and y. Unfortunately, System.Drawing.Point has X, Y and IsEmpty, and a constructor that takes x and y, so it can't automatically deduce the correct handling of System.Drawing.Point - but the point (hah) I'm trying to make there is that : some external types will work without any extra work.
For the rest, there are various ways of approaching the issue of types outside of your domain model, using the RuntimeTypeModel API. Depending on the specific type, either:
  • tell it how you want it to serialize that type in terms of its members
  • write a surrogate for that type (with appropriate conversion operators), and tell it about the surrogate
For example:

RuntimeTypeModel.Default.Add(typeof(System.Drawing.Point), false)

.Add("X", "Y");



which configures X as field 1, Y as field 2. The surrogate approach is more useful for complicated scenarios, but as a trivial example:

[ProtoContract]

    public class PointDto

    {

        [ProtoMember(1)]

        public int X { get; set; }

        [ProtoMember(2)]

        public int Y { get; set; }



        public static implicit operator System.Drawing.Point(PointDto value)

        {

            return value == null

                ? System.Drawing.Point.Empty

                : new System.Drawing.Point(value.X, value.Y);

        }

        public static implicit operator PointDto(System.Drawing.Point value)

        {

            return new PointDto { X = value.X, Y = value.Y };

        }

    }

   then:

RuntimeTypeModel.Default.Add(typeof(System.Drawing.Point), false)

.SetSurrogate(typeof(PointDto));



with this configuration, the library will convert to/from the surrogate type as needed - the idea being that you can add whatever code you need to in the operators, allowing the DTO to be very simple and opbvious to serialize.
Finally, note that many types will have a Parse API that works with their ToString implementation; if you want to enable use of the Parse methods (serializing as a string as a last-ditch effort), then:


RuntimeTypeModel.Default.AllowParseableTypes = true;


SHARE THIS POST   

0 comments :

Post a Comment

Design by Gohilinfotech | www.gohilinfotech.blogspot.com