context: //
  // Message.cs
  //
  // Author:
  //	Atsushi Enomoto <atsushi@ximian.com>
  //
  // Copyright (C) 2005-2006,2010 Novell, Inc.  http://www.novell.com
  //
  // Permission is hereby granted, free of charge, to any person obtaining
  // a copy of this software and associated documentation files (the
  // "Software"), to deal in the Software without restriction, including
  // without limitation the rights to use, copy, modify, merge, publish,
  // distribute, sublicense, and/or sell copies of the Software, and to
  // permit persons to whom the Software is furnished to do so, subject to
  // the following conditions:
  // 
  // The above copyright notice and this permission notice shall be
  // included in all copies or substantial portions of the Software.
  // 
  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  //
  using System;
  using System.Collections.Generic;
  using System.IO;
  using System.Runtime.Serialization;
  using System.Xml;
  using System.Xml.Schema;
  
  namespace System.ServiceModel.Channels
  {
  	public abstract class Message : IDisposable
  	{
  		bool disposed;
  		string body_id;
  		Message copied_message;
  		string string_cache;
  
  		protected Message () {
  			State = MessageState.Created;
  		}
  
  		public abstract MessageHeaders Headers { get; }
  
  		public virtual bool IsEmpty {
  			get { return false; }
  		}
  
  		public virtual bool IsFault {
  			get { return false; }
  		}
  
  		public abstract MessageProperties Properties { get; }
  
  		public MessageState State { get; private set; }
  
  		public abstract MessageVersion Version { get; }
  
  		protected bool IsDisposed {
  			get { return disposed; }
  		}
  
  		public void Close ()
  		{
  			if (!disposed)
  				OnClose ();
  			State = MessageState.Closed;
  			disposed = true;
  		}
  
  		public MessageBuffer CreateBufferedCopy (int maxBufferSize)
  		{
  			if (State != MessageState.Created)
  				throw new InvalidOperationException (String.Format ("The message is already at {0} state", State));
  
  			if (copied_message != null)
  				return copied_message.CreateBufferedCopy (maxBufferSize);
  
  			try {
  				return OnCreateBufferedCopy (maxBufferSize);
  			} finally {
  				State = MessageState.Copied;
  			}
  		}
  
  		void IDisposable.Dispose ()
  		{
  			Close ();
  		}
  
  		public T GetBody<T> ()
  		{
  			return OnGetBody<T> (GetReaderAtBodyContents ());
  		}
  
  		public T GetBody<T> (XmlObjectSerializer xmlFormatter)
  		{
  			// FIXME: Somehow use OnGetBody() here as well?
  			return (T)xmlFormatter.ReadObject (GetReaderAtBodyContents ());
  		}
  
  		protected virtual T OnGetBody<T> (XmlDictionaryReader reader)
  		{
  			var xmlFormatter = new DataContractSerializer (typeof (T));
  			return (T)xmlFormatter.ReadObject (reader);
  		}
  
  		public string GetBodyAttribute (string localName, string ns)
  		{
  			return OnGetBodyAttribute (localName, ns);
  		}
  
  		public XmlDictionaryReader GetReaderAtBodyContents ()
  		{
  			if (copied_message != null)
  				return copied_message.GetReaderAtBodyContents ();
  
  			return OnGetReaderAtBodyContents ();
  		}
  
  		public override string ToString ()
  		{
  			if (string_cache != null)
  				return string_cache;
  
  			StringWriter sw = new StringWriter ();
  			XmlWriterSettings settings = new XmlWriterSettings ();
  			settings.Indent = true;
  			settings.OmitXmlDeclaration = true;
  
  			using (XmlWriter w = XmlWriter.Create (sw, settings)) {
  				OnBodyToString (XmlDictionaryWriter.CreateDictionaryWriter (w));
  			}
  			string_cache = sw.ToString ();
  			return string_cache;
  		}
  
  		void WriteXsiNil (XmlDictionaryWriter writer)
  		{
  			var dic = Constants.SoapDictionary;
  			writer.WriteStartElement ("z", dic.Add ("anyType"), dic.Add (Constants.MSSerialization));
  			writer.WriteAttributeString ("i", dic.Add ("nil"), dic.Add ("http://www.w3.org/2001/XMLSchema-instance"), "true");
  			writer.WriteEndElement ();
  		}
  
  		public void WriteBody (XmlDictionaryWriter writer)
  		{
  			if (Version.Envelope != EnvelopeVersion.None)
  				WriteStartBody (writer);
  			WriteBodyContents (writer);
  			if (Version.Envelope != EnvelopeVersion.None)
  				writer.WriteEndElement ();
  		}
  
  		public void WriteBody (XmlWriter writer)
  		{
  			WriteBody (XmlDictionaryWriter.CreateDictionaryWriter (writer));
  		}
  
  		public void WriteBodyContents (XmlDictionaryWriter writer)
  		{
  			if (!IsEmpty) {
  				if (copied_message != null)
  					copied_message.WriteBodyContents (writer);
  				else
  					OnWriteBodyContents (writer);
  			}
  			else if (Version.Envelope == EnvelopeVersion.None)
  				WriteXsiNil (writer);
  			State = MessageState.Written;
  		}
  
  		public void WriteMessage (XmlDictionaryWriter writer)
  		{
  			if (State != MessageState.Created)
  				throw new InvalidOperationException (String.Format ("The message is already at {0} state", State));
  
  			OnWriteMessage (writer);
  		}
  
  		public void WriteMessage (XmlWriter writer)
  		{
  			WriteMessage (XmlDictionaryWriter.CreateDictionaryWriter (writer));
  		}
  
  		public void WriteStartBody (XmlDictionaryWriter writer)
  		{
  			if (State != MessageState.Created)
  				throw new InvalidOperationException (String.Format ("The message is already at {0} state", State));
  
  			OnWriteStartBody (writer);
  		}
  
  		public void WriteStartBody (XmlWriter writer)
  		{
  			WriteStartBody (
  				XmlDictionaryWriter.CreateDictionaryWriter (writer));
  		}
  
  		public void WriteStartEnvelope (XmlDictionaryWriter writer)
  		{
  			if (State != MessageState.Created)
  				throw new InvalidOperationException (String.Format ("The message is already at {0} state", State));
  
  			OnWriteStartEnvelope (writer);
  		}
  
  		protected virtual void OnBodyToString (
  			XmlDictionaryWriter writer)
  		{
  			MessageState tempState = State;
  			try {
  				var mb = CreateBufferedCopy (int.MaxValue);
  
gt: 				copied_message = mb.CreateMessage ();