using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Xml; using System.Diagnostics; using System.IO; using System.Xml.Linq; namespace DotNetOAuth { /// /// Serializes/deserializes OAuth messages for/from transit. /// internal class ProtocolMessageSerializer where T : IProtocolMessage { DataContractSerializer serializer; readonly XName rootElement = XName.Get("root", Protocol.DataContractNamespace); internal ProtocolMessageSerializer() { serializer = new DataContractSerializer(typeof(T), rootElement.LocalName, rootElement.NamespaceName); } /// /// Reads the data from a message instance and returns a series of name=value pairs for the fields that must be included in the message. /// /// The message to be serialized. internal IDictionary Serialize(T message) { if (message == null) throw new ArgumentNullException("message"); var fields = new Dictionary(); Serialize(fields, message); return fields; } internal void Serialize(IDictionary fields, T message) { if (fields == null) throw new ArgumentNullException("fields"); if (message == null) throw new ArgumentNullException("message"); message.EnsureValidMessage(); using (XmlWriter writer = DictionaryXmlWriter.Create(fields)) { serializer.WriteObjectContent(writer, message); } } /// /// Reads name=value pairs into an OAuth message. /// /// The name=value pairs that were read in from the transport. internal T Deserialize(IDictionary fields) { if (fields == null) throw new ArgumentNullException("fields"); var reader = DictionaryXmlReader.Create(rootElement, fields); T result = (T)serializer.ReadObject(reader, false); result.EnsureValidMessage(); return result; } } }