using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Xml;
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(StringComparer.Ordinal);
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;
try {
result = (T)serializer.ReadObject(reader, false);
} catch (SerializationException ex) {
// Missing required fields is one cause of this exception.
throw new ProtocolException(Strings.InvalidIncomingMessage, ex);
}
result.EnsureValidMessage();
return result;
}
}
}