//-----------------------------------------------------------------------
//
// Copyright (c) Andrew Arnott. All rights reserved.
//
//-----------------------------------------------------------------------
namespace DotNetOAuth.Messaging {
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Linq;
///
/// Serializes/deserializes OAuth messages for/from transit.
///
internal class MessageSerializer {
///
/// The serializer that will be used as a reflection engine to extract
/// the OAuth message properties out of their containing
/// objects.
///
private readonly DataContractSerializer serializer;
///
/// The specific -derived type
/// that will be serialized and deserialized using this class.
///
private readonly Type messageType;
///
/// An AppDomain-wide cache of shared serializers for optimization purposes.
///
private static Dictionary prebuiltSerializers = new Dictionary();
///
/// Backing field for the property
///
private XName rootElement;
///
/// A field sorter that puts fields in the right order for the .
///
private IComparer fieldSorter;
///
/// Initializes a new instance of the MessageSerializer class.
///
/// The specific -derived type
/// that will be serialized and deserialized using this class.
private MessageSerializer(Type messageType) {
Debug.Assert(messageType != null, "messageType == null");
if (!typeof(IProtocolMessage).IsAssignableFrom(messageType)) {
throw new ArgumentException(
string.Format(
CultureInfo.CurrentCulture,
MessagingStrings.UnexpectedType,
typeof(IProtocolMessage).FullName,
messageType.FullName),
"messageType");
}
this.messageType = messageType;
this.serializer = new DataContractSerializer(
messageType, this.RootElement.LocalName, this.RootElement.NamespaceName);
this.fieldSorter = new DataContractMemberComparer(messageType);
}
///
/// Gets the XML element that is used to surround all the XML values from the dictionary.
///
private XName RootElement {
get {
if (this.rootElement == null) {
DataContractAttribute attribute;
try {
attribute = this.messageType.GetCustomAttributes(typeof(DataContractAttribute), false).OfType().Single();
} catch (InvalidOperationException ex) {
throw new ProtocolException(
string.Format(
CultureInfo.CurrentCulture,
MessagingStrings.DataContractMissingFromMessageType,
this.messageType.FullName),
ex);
}
if (attribute.Namespace == null) {
throw new ProtocolException(string.Format(
CultureInfo.CurrentCulture,
MessagingStrings.DataContractMissingNamespace,
this.messageType.FullName));
}
this.rootElement = XName.Get("root", attribute.Namespace);
}
return this.rootElement;
}
}
///
/// Returns a message serializer from a reusable collection of serializers.
///
/// The type of message that will be serialized/deserialized.
/// A previously created serializer if one exists, or a newly created one.
internal static MessageSerializer Get(Type messageType) {
if (messageType == null) {
throw new ArgumentNullException("messageType");
}
// We do this as efficiently as possible by first trying to fetch the
// serializer out of the dictionary without taking a lock.
MessageSerializer serializer;
if (prebuiltSerializers.TryGetValue(messageType, out serializer)) {
return serializer;
}
// Since it wasn't there, we'll be trying to write to the dictionary so
// we take a lock and try reading again first, then creating the serializer
// and storing it when we're sure it absolutely necessary.
lock (prebuiltSerializers) {
if (prebuiltSerializers.TryGetValue(messageType, out serializer)) {
return serializer;
}
serializer = new MessageSerializer(messageType);
prebuiltSerializers.Add(messageType, serializer);
}
return serializer;
}
///
/// 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.
/// The dictionary of values to send for the message.
internal IDictionary Serialize(IProtocolMessage message) {
if (message == null) {
throw new ArgumentNullException("message");
}
var fields = new Dictionary(StringComparer.Ordinal);
this.Serialize(fields, message);
return fields;
}
///
/// Saves the [DataMember] properties of a message to an existing dictionary.
///
/// The dictionary to save values to.
/// The message to pull values from.
internal void Serialize(IDictionary fields, IProtocolMessage message) {
if (fields == null) {
throw new ArgumentNullException("fields");
}
if (message == null) {
throw new ArgumentNullException("message");
}
message.EnsureValidMessage();
using (XmlWriter writer = DictionaryXmlWriter.Create(fields)) {
this.serializer.WriteObjectContent(writer, message);
}
}
///
/// Reads name=value pairs into an OAuth message.
///
/// The name=value pairs that were read in from the transport.
/// The instantiated and initialized instance.
internal IProtocolMessage Deserialize(IDictionary fields) {
if (fields == null) {
throw new ArgumentNullException("fields");
}
var reader = DictionaryXmlReader.Create(this.RootElement, this.fieldSorter, fields);
IProtocolMessage result;
try {
result = (IProtocolMessage)this.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;
}
}
}