//-----------------------------------------------------------------------
//
// Copyright (c) Outercurve Foundation. All rights reserved.
//
//-----------------------------------------------------------------------
namespace DotNetOpenAuth.Messaging {
using System;
using System.Globalization;
using DotNetOpenAuth.Messaging.Reflection;
///
/// Encodes and decodes the as an integer of total seconds.
///
internal class TimespanSecondsEncoder : IMessagePartEncoder, IMessagePartFormattingEncoder {
///
/// Initializes a new instance of the class.
///
public TimespanSecondsEncoder() {
// Note that this constructor is public so it can be instantiated via Activator.
}
#region IMessagePartFormattingEncoder members
///
/// Gets the type of the encoded values produced by this encoder, as they would appear in their preferred form.
///
public Type FormattingType {
get { return typeof(int); }
}
#endregion
#region IMessagePartEncoder Members
///
/// Encodes the specified value.
///
/// The value. Guaranteed to never be null.
///
/// The in string form, ready for message transport.
///
public string Encode(object value) {
TimeSpan? timeSpan = value as TimeSpan?;
if (timeSpan.HasValue) {
return timeSpan.Value.TotalSeconds.ToString(CultureInfo.InvariantCulture);
} else {
return null;
}
}
///
/// Decodes the specified value.
///
/// The string value carried by the transport. Guaranteed to never be null, although it may be empty.
///
/// The deserialized form of the given string.
///
/// Thrown when the string value given cannot be decoded into the required object type.
public object Decode(string value) {
return TimeSpan.FromSeconds(double.Parse(value, CultureInfo.InvariantCulture));
}
#endregion
}
}