views:

71

answers:

1

I've done a lot of serialization development lately, mostly for sending objects over sockets, but I've run into an interesting question: Is it possible to send just a few of the properties from an object through a serializer?

My envisioned scenario is this: You have some sort of "state" object for each client, consisting of many properties (strings, ints, bools, etc). When your client first connects, the entire state object is serialized via an Xml or Binary serializer, and sent over the socket, to be recreated on the other side. Now both client and server have identical state objects. Your server then needs to change the state, and does so by simply setting one of the state object's property. The socket (either hooked to the state's events, or part of the state object itself) could synchronize the two states by reserializing the entire object, but it seems like a single "property change" object would do.

Obviously, this could be implemented manually. But it seems like a serializer should be able to serialize just a single property, and apply it like a patch on the other side. Does anyone know if this is possible, or would I have to write the entire thing from scratch?

+1  A: 

With XmlSerializer (and protobuf-net, for a binary equivalent, since protobuf-net adopts most of XmlSerializer's patterns) you could do this by having a method:

public bool SouldSerializeFoo() {
    return fooIsDirty;
}
public string Foo {get;set;}

for each property Foo - but you'd need to maintain the "what is dirty" manually in your own code (perhaps in the set). Lots of work; I've done a diffing serializer in the past - it was a real PITA, to be honest. I should also note that the [XmlIgnore] public bool FooSpecified {get{...} set{...}} pattern does the same thing, but for what you want, ShouldSerialize* is more appropriate.

Marc Gravell
Does the XML Serializer Look for `ShouldSerialize____` automatically for every item?
Daniel Rasmussen
I had no idea that this worked for the `XmlSerializer` - I thought it was only used by form designers. I take it this isn't documented anywhere obvious?
Aaronaught
@cyclotis04 - yes; and *Specified properties.
Marc Gravell
@Aaronaught - don't know. I do know that it works, though.
Marc Gravell
@Marc: What do you mean by *Specified properties?
Daniel Rasmussen
A public `bool` property (with public get and set) called `BlahSpecified`, which tells `XmlSerializer` whether to even *look* at field/property `Blah`. It is usually marked `[XmlIgnore]` too. `XmlSerializer` has a few tricks ;p This is just one of the patterns that it looks for.
Marc Gravell
Cool. Is there a link to go along with all these tricks, or are they just something you've picked up over the ages?
Daniel Rasmussen
@cyclotis04 - hmm; I can't track anything down. Sorry....
Marc Gravell
That's alright. If you find something, an update would be helpful, but for now I'll mess around with it. =]
Daniel Rasmussen