1

I'm having trouble serializing types acquired through WCF mex endpoint point, if I use those types to display data in WPF.

This is because the auto generated types do Implement the INotifyPropertyChanged interface, and because WPF binding subscribes to it.

The normal way of doing this would be adding [field: NonSerialized] to the event declaration. I don't want to do this, because the classes were auto generated.

I also do not want to switch to DataContractSerializer, mostly because I find BinaryFormatter that I'm using rather convenient in all other cases.

What I'd like to do is to find a field, in which event data is stored and mark it as NonSerialized before the serialization begins using reflection.

Here are my questions:

  1. Is it possible to add attributes at runtime?
  2. How do I find the field associated with the event?
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
serentei
  • 57
  • 1
  • 1
  • 5
  • http://stackoverflow.com/questions/2160476/how-to-set-attributes-values-using-reflection – BenCamps May 05 '12 at 22:19
  • That can't work. If you really want to avoid the attributes on your main class then declare another one that represents the serialized state of it. Plus the code that converts from one to the other. – Hans Passant May 05 '12 at 22:48
  • If you're using WCF, how are you using the BinaryFormatter now?? The only ways I know of to do that is to use the NetDataContractSerializer and provider a serialization surrogate that uses the BinaryFormatter...or to create your own WCF Message Formatter. I ask, because it's relevant to the answer to your question. – Jeff May 06 '12 at 01:14

1 Answers1

0

Here are a few ideas off the top of my head.

  1. Create dynamic proxy classes (that don't implement INotifyPropertyChanged) at serialization time using CodeDom or ILGenerator. Then use something like AutoMapper to map your original object graph onto these proxy classes.

  2. If your only real problem is the events subscription...and you know these classes are auto-generated (so they don't have any kind of special implementations for the events, that is, they just use a normal underlying field delegate)...you could temporarily remove then re-add the events subscriptions at serialization time. Random google reference: How to get a delegate object from an EventInfo?. Basically, you could grab all the current event subscriptions, wipe the delegate clean, then re-add the subscriptions.....or you could just null the underlying delegate field and then re-set it once serialization completes.

  3. If you're not too concerned about performance, you could use a ISerializationSurrogate http://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializationsurrogate.getobjectdata.aspx that reflects your object for all FieldInfos and makes sure to ignore fields that are of a delegate type.

Community
  • 1
  • 1
Jeff
  • 35,755
  • 15
  • 108
  • 220