Categories
C# Programming Uncategorized

Serialize Size Struct In ProtoBuf-net

The following code allows you to serialise the Size struct when using ProtoBuf-net.

First define a surrogate.

[ProtoContract]
    struct ProtoSize
    {
        [ProtoMember(1)]
        int Width;
        [ProtoMember(2)]
        int Height;
      
        public static implicit operator Size(ProtoSize s)
        { return new Size(new Point(s.Width, s.Height)); }
        
        public static implicit operator ProtoSize(Size s)
        { return new ProtoSize { Width = s.Width, Height = s.Height };  }
    }

Then add it to the RuntimeTypeModel.

static RuntimeTypeModel Model;

Model = RuntimeTypeModel.Create();
Model.AllowParseableTypes = true;
Model.Add(typeof(Size), false).SetSurrogate(typeof(ProtoSize));

Then use it.

 Model.Serialize(someFile, someObjectWithSizeProperty);

Remember to decorate the size property with a [ProtoMember] attribute.

Here is a list of other useful surrogates for Dot Net, which I gleaned from the Internet.


    [ProtoContract]
    struct ProtoColor
    {
        [ProtoMember(1, DataFormat = DataFormat.FixedSize)]
        public uint argb;
        public static implicit operator Color(ProtoColor c)
        { return Color.FromArgb((int)c.argb); }
        public static implicit operator ProtoColor(Color c)
        { return new ProtoColor { argb = (uint)c.ToArgb() }; }
    }
    [ProtoContract()]
    class ProtoFont
    {
        [ProtoMember(1)]
        string FontFamily;
        [ProtoMember(2)]
        float SizeInPoints;
        [ProtoMember(3)]
        FontStyle Style;

        public static implicit operator Font(ProtoFont f)
        {
            return new Font(f.FontFamily, f.SizeInPoints, f.Style);
        }
        public static implicit operator ProtoFont(Font f)
        {
            return f == null ? null : new ProtoFont
            {
                FontFamily = f.FontFamily.Name,
                SizeInPoints = f.SizeInPoints,
                Style = f.Style
            };
        }
    }
    [ProtoContract()]
    class ProtoStringFormat
    {
        [ProtoMember(1, DataFormat = DataFormat.Group)]
        StringAlignment Alignment;
        [ProtoMember(2)]
        StringAlignment LineAlignment;
        [ProtoMember(3)]
        StringFormatFlags Flags;
        public static implicit operator StringFormat(ProtoStringFormat f)
        {
            return new StringFormat(f.Flags)
            {
                Alignment = f.Alignment,
                LineAlignment = f.LineAlignment
            };
        }
        public static implicit operator ProtoStringFormat(StringFormat f)
        {
            return f == null ? null : new ProtoStringFormat()
            {
                Flags = f.FormatFlags,
                Alignment = f.Alignment,
                LineAlignment = f.LineAlignment
            };
        }
    }