- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个在 OperationContract 参数中使用 Noda Time 类型(LocalDate
和 ZonedDateTime
)的服务,但是当我尝试发送例如 LocalDate(1990,7 ,31)
服务器接收到一个具有默认值 (1970/1/1) 的对象。客户端或服务器不会抛出任何错误。
以前它与相应的 BCL 类型 (DateTimeOffset
) 配合得很好。我知道 WCF 可能不“知道”Noda Time 类型,但我不知道应该如何添加它们。我检查了 this page in the documentation about known types , 但它没有帮助。
有什么方法可以避免从 BCL 类型到 BCL 类型的肮脏(并且可能不完整)手动转换/序列化?
谢谢。
最佳答案
感谢 Aron 的建议,我能够想出一个 IDataContractSurrogate 的实现,这对于通过 WCF 传递非基本类型的对象非常有帮助(不仅是 Noda Time)。
有兴趣的 friend ,这里有完整的代码和解释,支持LocalDate、LocalDateTime和ZonedDateTime。序列化方式当然可以根据需要定制,比如使用Json.NET序列化,我的简单实现是不会序列化年历信息的。
或者,我已经在这个要点上发布了完整的代码: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
类(序列化应该只存储 WCF 序列化程序已知的类型)并且可以通过 WCF 传递:
public class ReplacementType {
[DataMember(Name = "Serialized")]
public object Serialized { get; set; }
[DataMember(Name = "OriginalType")]
public string OriginalTypeFullName { get; set; }
}
序列化/反序列化规则包装在 Translator
泛型类中以简化向代理项添加规则(只有一个代理项分配给服务端点,因此它应该包含所有必要的规则):
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();
}
}
瞧! :)
关于c# - 如何在 WCF 中将 Noda Time(或任何第三方类型)对象作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18632361/
这个问题在这里已经有了答案: How to initialize var? (11 个答案) 关闭 8 年前。 我想给一个变量赋初值 null,并在下一个 if-else block 中赋值,但是编
我正在使用 TypeScript 3.8 编写 JS 和 TS 混合的代码。我写了以下行: export * as Easing from './easing'; 应该是 fair game在 Typ
我需要将 R 代码中的“/”更改为“\”。我有这样的事情: tmp <- paste(getwd(),"tmp.xls",sep="/") 所以我的 tmp是 c:/Study/tmp.xls 我希望
我有个问题。例如我有这个: id truth count 1 1 1 2 1 2 3 0 0 4 1 1 5 1 2 6 1
我正在尝试使用“IN”和“=”来查找一些 bean。我目前正在使用此代码: $ids = array(1,2,3,4); $user = 1; $things = R::find( 'thing'
是否可以在 Xcode 中部署到其他人的手机上?我没有 iPhone,但我想测试我在 friend 手机上制作的应用程序。在我支付 99 美元之前,我想确保这不会造成麻烦。 谢谢。 最佳答案 不会有任
我试图得到一个非常大的数字(超过 unsigned long long int )。所以我把它作为一个字符串,然后一个数字一个数字地转换成整数并使用它。 #include #include int
我在 Rust 中有 C 语言库的绑定(bind),但它们并不完整。 在 C 代码中,我定义了一个简化的宏,如下所示: #define MY_MACROS1(PTR) (((my_struct1
我正在努力解决这个问题。 http://jsfiddle.net/yhcqfy44/ 动画应该自动相对于 滚动到顶部每次出现滚动条时的高度。 我已经写了这个,但没有运气: var hheight =
我正在处理一个将数字作为字符串返回的 JSON API。例如 "12" ,但是,该字段值也可以是非数字的,例如:"-" . 我已将 JSON 数据解析为映射,我想将此字段提取为 elixir 中的整数
我正在尝试编写一个类,将.wav文件转换为.aiff文件作为项目的一部分。 我遇到了几个库Alvas.Audio(http://alvas.net/alvas.audio,overview.aspx)
我想在 Lucene 中将像“New York”这样的“复合词”索引为单个术语,而不是像“new”、“york”那样。这样,如果有人搜索“new place”,则包含“new york”的文档将不会匹
我希望这个解释能让我更好地了解使用宏的优点。 最佳答案 在函数中,所有参数在调用之前都会被评估。 这意味着 or 作为函数不能是惰性的,而宏可以将 or 重写为 if 语句,该语句仅在以下情况下计算分
我有一些看起来像这样的 XML foo ]]> (注意 > 登录 "> foo")和 XSLT 样式表 当我运行xsltproc stylesheet.xs
当我尝试将 Any 转换为 List 时,如下面的示例所示,我得到“Unchecked cast: Any!”到列表'警告。有没有解决此类问题的方法? val x: List = objectOfTy
我正在使用 Python 开发一个简单的爬虫。目的是创建一个 sitemap.xml。(你可以在这里找到真正的 alpha 版本:http://code.google.com/p/sitemappy/
我想知道在 VBScript 中是否可以在多行中中断 If 语句。喜欢: If (UCase(Trim(objSheet.Cells(i, a).Value)) = "YES") Or _ (UCas
for (String item : someList) { System.out.println(item); } 使用“do while”是否等效? 谢谢。 最佳答案 如果列表为空,f
这个问题已经有答案了: 已关闭10 年前。 Possible Duplicate: Split string with delimiters in C 在 C 中将“,”分隔的列表拆分为数组的最佳方法
我有一个如下所示的字符数组: [0, 10, 20, 30, 670] 如何将此字符串转换为整数数组? 这是我的数组 int i=0; size_t dim = 1; char* array = (c
我是一名优秀的程序员,十分优秀!