/// <include file='doc\XmlMessageFormatter.uex' path='docs/doc[@for="XmlMessageFormatter.Write"]/*' /> /// <devdoc> /// This method is used to write the given object into the given message. /// If the formatter cannot understand the given object, an exception is thrown. /// </devdoc> public void Write(Message message, object obj) { if (message == null) { throw new ArgumentNullException("message"); } if (obj == null) { throw new ArgumentNullException("obj"); } Stream stream = new MemoryStream(); Type serializedType = obj.GetType(); XmlSerializer serializer = null; if (this.targetSerializerTable.ContainsKey(serializedType)) { serializer = (XmlSerializer)this.targetSerializerTable[serializedType]; } else { serializer = new XmlSerializer(serializedType); this.targetSerializerTable[serializedType] = serializer; } serializer.Serialize(stream, obj); message.BodyStream = BodyStreamConverter.FromBodyStream(stream); //Need to reset the body type, in case the same message //is reused by some other formatter. message.BodyType = 0; }
/// <include file='doc\XmlMessageFormatter.uex' path='docs/doc[@for="XmlMessageFormatter.Read"]/*' /> /// <devdoc> /// This method is used to read the contents from the given message /// and create an object. /// </devdoc> public object Read(Message message) { if (message == null) { throw new ArgumentNullException("message"); } this.CreateTargetSerializerTable(); Stream stream = BodyStreamConverter.ToBodyStream(message.BodyStream); XmlTextReader reader = new XmlTextReader(stream); reader.WhitespaceHandling = WhitespaceHandling.Significant; reader.DtdProcessing = DtdProcessing.Prohibit; foreach (XmlSerializer serializer in targetSerializerTable.Values) { if (serializer.CanDeserialize(reader)) { return(serializer.Deserialize(reader)); } } throw new InvalidOperationException(); }