7

OperationContract パラメータでNoda Time 型 (LocalDateおよびZonedDateTime) を使用するサービスがありますが、たとえば送信しようとするとLocalDate(1990,7,31)、サーバーはデフォルト値 (1970/1/1) のオブジェクトを受信します。クライアントまたはサーバーによってエラーがスローされることはありません。

以前は、対応する BCL タイプ ( ) でうまく機能していましたDateTimeOffset。Noda Time 型が WCF によって「認識」されていない可能性があることは理解していますが、それらを追加する方法がわかりません。既知の型に関するドキュメントでこのページを確認しましたが、役に立ちません。

BCL 型との間のダーティな (そしておそらく不完全な) 手動変換/シリアル化を回避するためにこれを行う方法はありますか?

ありがとうございました。

4

1 に答える 1

5

Aron の提案のおかげで、IDataContractSurrogate の実装を思いつくことができました。これは、(Noda Time だけでなく) WCF を介して非基本型のオブジェクトを渡すのに非常に役立ちます。

興味のある方は、LocalDate、LocalDateTime、および ZonedDateTime をサポートする説明付きの完全なコードを次に示します。私の単純な実装では時代/カレンダー情報をシリアル化しないため、Json.NET シリアル化を使用するなど、シリアル化方法はもちろん要件を満たすようにカスタマイズできます。

または、この Gist に完全なコードを投稿しました: https://gist.github.com/mayerwin/6468178

まず、基本型へのシリアル化/変換を処理するヘルパー クラス:

public static class DatesExtensions {
    public static DateTime ToDateTime(this LocalDate localDate) {
        return new DateTime(localDate.Year, localDate.Month, localDate.Day);
    }

    public static LocalDate ToLocalDate(this DateTime dateTime) {
        return new LocalDate(dateTime.Year, dateTime.Month, dateTime.Day);
    }

    public static string Serialize(this ZonedDateTime zonedDateTime) {
        return LocalDateTimePattern.ExtendedIsoPattern.Format(zonedDateTime.LocalDateTime) + "@O=" + OffsetPattern.GeneralInvariantPattern.Format(zonedDateTime.Offset) + "@Z=" + zonedDateTime.Zone.Id;
    }

    public static ZonedDateTime DeserializeZonedDateTime(string value) {
        var match = ZonedDateTimeRegex.Match(value);
        if (!match.Success) throw new InvalidOperationException("Could not parse " + value);
        var dtm = LocalDateTimePattern.ExtendedIsoPattern.Parse(match.Groups[1].Value).Value;
        var offset = OffsetPattern.GeneralInvariantPattern.Parse(match.Groups[2].Value).Value;
        var tz = DateTimeZoneProviders.Tzdb.GetZoneOrNull(match.Groups[3].Value);
        return new ZonedDateTime(dtm, tz, offset);
    }

    public static readonly Regex ZonedDateTimeRegex = new Regex(@"^(.*)@O=(.*)@Z=(.*)$");
}

次に、ReplacementTypeシリアル化されたデータ (Serialized は WCF シリアライザーによって認識される型のみを格納する必要があります) を含み、WCF 経由で渡すことができるクラス:

public class ReplacementType {
    [DataMember(Name = "Serialized")]
    public object Serialized { get; set; }
    [DataMember(Name = "OriginalType")]
    public string OriginalTypeFullName { get; set; }
}

シリアライゼーション/デシリアライゼーション ルールはTranslatorジェネリック クラスにラップされ、サロゲートへのルールの追加を簡素化します (サービス エンドポイントには 1 つのサロゲートのみが割り当てられるため、必要なすべてのルールを含める必要があります)。

public abstract class Translator {
    public abstract object Serialize(object obj);
    public abstract object Deserialize(object obj);
}

public class Translator<TOriginal, TSerialized> : Translator {
    private readonly Func<TOriginal, TSerialized> _Serialize;

    private readonly Func<TSerialized, TOriginal> _Deserialize;

    public Translator(Func<TOriginal, TSerialized> serialize, Func<TSerialized, TOriginal> deserialize) {
        this._Serialize = serialize;
        this._Deserialize = deserialize;
    }

    public override object Serialize(object obj) {
        return new ReplacementType { Serialized = this._Serialize((TOriginal)obj), OriginalTypeFullName = typeof(TOriginal).FullName };
    }

    public override object Deserialize(object obj) {
        return this._Deserialize((TSerialized)obj);
    }
}

最後にサロゲート クラスである各変換ルールは、静的コンストラクターに簡単に追加できます。

public class CustomSurrogate : IDataContractSurrogate {
    /// Type.GetType only works for the current assembly or mscorlib.dll
    private static readonly Dictionary<string, Type> AllLoadedTypesByFullName = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).Distinct().GroupBy(t => t.FullName).ToDictionary(t => t.Key, t => t.First());

    public static Type GetTypeExt(string typeFullName) {
        return Type.GetType(typeFullName) ?? AllLoadedTypesByFullName[typeFullName];
    }

    private static readonly Dictionary<Type, Translator> Translators;
    static CustomSurrogate() {
        Translators = new Dictionary<Type, Translator> {
            {typeof(LocalDate), new Translator<LocalDate, DateTime>(serialize: d => d.ToDateTime(), deserialize: d => d.ToLocalDate())},
            {typeof(LocalDateTime), new Translator<LocalDateTime, DateTime>(serialize:  d => d.ToDateTimeUnspecified(), deserialize: LocalDateTime.FromDateTime)},
            {typeof(ZonedDateTime), new Translator<ZonedDateTime, string> (serialize: d => d.Serialize(), deserialize: DatesExtensions.DeserializeZonedDateTime)}
        };
    }

    public Type GetDataContractType(Type type) {
        if (Translators.ContainsKey(type)) {
            type = typeof(ReplacementType);
        }
        return type;
    }

    public object GetObjectToSerialize(object obj, Type targetType) {
        Translator translator;
        if (Translators.TryGetValue(obj.GetType(), out translator)) {
            return translator.Serialize(obj);
        }
        return obj;
    }

    public object GetDeserializedObject(object obj, Type targetType) {
        var replacementType = obj as ReplacementType;
        if (replacementType != null) {
            var originalType = GetTypeExt(replacementType.OriginalTypeFullName);
            return Translators[originalType].Deserialize(replacementType.Serialized);
        }
        return obj;
    }

    public object GetCustomDataToExport(MemberInfo memberInfo, Type dataContractType) {
        throw new NotImplementedException();
    }

    public object GetCustomDataToExport(Type clrType, Type dataContractType) {
        throw new NotImplementedException();
    }

    public void GetKnownCustomDataTypes(Collection<Type> customDataTypes) {
        throw new NotImplementedException();
    }

    public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData) {
        throw new NotImplementedException();
    }

    public CodeTypeDeclaration ProcessImportedType(CodeTypeDeclaration typeDeclaration, CodeCompileUnit compileUnit) {
        throw new NotImplementedException();
    }
}

これを使用するために、次の名前のサービスを定義しますSurrogateService

[ServiceContract]
public interface ISurrogateService {
    [OperationContract]
    Tuple<LocalDate, LocalDateTime, ZonedDateTime> GetParams(LocalDate localDate, LocalDateTime localDateTime, ZonedDateTime zonedDateTime);
}

public class SurrogateService : ISurrogateService {
    public Tuple<LocalDate, LocalDateTime, ZonedDateTime> GetParams(LocalDate localDate, LocalDateTime localDateTime, ZonedDateTime zonedDateTime) {
        return Tuple.Create(localDate, localDateTime, zonedDateTime);
    }
}

クライアントとサーバーを同じマシン (コンソール アプリケーション内) で完全にスタンドアロン ベースで実行するには、次のコードを静的クラスに追加し、関数Start()を呼び出すだけです。

public static class SurrogateServiceTest {
    public static void DefineSurrogate(ServiceEndpoint endPoint, IDataContractSurrogate surrogate) {
        foreach (var operation in endPoint.Contract.Operations) {
            var ob = operation.Behaviors.Find<DataContractSerializerOperationBehavior>();
            ob.DataContractSurrogate = surrogate;
        }
    }

    public static void Start() {
        var baseAddress = "http://" + Environment.MachineName + ":8000/Service";
        var host = new ServiceHost(typeof(SurrogateService), new Uri(baseAddress));
        var endpoint = host.AddServiceEndpoint(typeof(ISurrogateService), new BasicHttpBinding(), "");
        host.Open();
        var surrogate = new CustomSurrogate();
        DefineSurrogate(endpoint, surrogate);

        Console.WriteLine("Host opened");

        var factory = new ChannelFactory<ISurrogateService>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
        DefineSurrogate(factory.Endpoint, surrogate);
        var client = factory.CreateChannel();
        var now = SystemClock.Instance.Now.InUtc();
        var p = client.GetParams(localDate: now.Date, localDateTime: now.LocalDateTime, zonedDateTime: now);

        if (p.Item1 == now.Date && p.Item2 == now.LocalDateTime && p.Item3 == now) {
            Console.WriteLine("Success");
        }
        else {
            Console.WriteLine("Failure");
        }
        ((IClientChannel)client).Close();
        factory.Close();

        Console.Write("Press ENTER to close the host");
        Console.ReadLine();
        host.Close();
    }
}

ほら!:)

于 2013-09-06T18:46:15.117 に答える