Serialization Surrogates

E

elziko

I have a class that contains a field that is a System.Drawing.Pen. I need to
be able to serialize the class but since the .NET Framework does not have
the Pen marked as serializable I must create a surrogate class that handles
the serialization instead. So here's my class:

NotInheritable Class PenSerializationSurrogate

Implements ISerializationSurrogate

Public Sub GetObjectData(ByVal obj As Object, ByVal info As
System.Runtime.Serialization.SerializationInfo, ByVal context As
System.Runtime.Serialization.StreamingContext) Implements
System.Runtime.Serialization.ISerializationSurrogate.GetObjectData
Dim p As Drawing.Pen = CType(obj, Drawing.Pen)
info.AddValue("colour", p.Color)
info.AddValue("width", p.Width)
End Sub

Public Function SetObjectData(ByVal obj As Object, ByVal info As
System.Runtime.Serialization.SerializationInfo, ByVal context As
System.Runtime.Serialization.StreamingContext, ByVal selector As
System.Runtime.Serialization.ISurrogateSelector) As Object Implements
System.Runtime.Serialization.ISerializationSurrogate.SetObjectData
Dim p As Drawing.Pen = CType(obj, Drawing.Pen)
p.Color = CType(info.GetValue("colour", GetType(Drawing.Color)),
Drawing.Color)
p.Width = CType(info.GetValue("width", GetType(Single)), Single)
Return Nothing
End Function

End Class

However I'm unsure how I get my class to always use the surrogate when it is
serialised. There is an example here:

http://msdn.microsoft.com/msdnmag/issues/02/09/net/default.aspx?fig=true#fig2

....but it looks like I have to register the surrogate with the formatter
that does the serialization. However, I want this to be more automatic! I
want this class to use this surrogate every time ANY formatter tries to
serialize it. Is this possible?

TIA
 
G

Guest

Is there anything that you can do to Refactor you class so that the Pen field
does not have to be serialized?

e.g. Add a Color and Width properties and then add a read=only property that
constructs and returns a pen instance.

The central point to serialization is that you want to maindain/persist/copy
a state, not necessarily an object graph, per se.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top