From d270c27f4ffc4e59831f4154a5865184ce06acb0 Mon Sep 17 00:00:00 2001 From: da3dsoul Date: Mon, 2 Oct 2023 18:28:30 -0400 Subject: [PATCH] Try a custom SerializationBinder so that moving namespaces doesn't completely break filters --- .../NHIbernate/FilterExpressionConverter.cs | 4 ++- .../SimpleNameSerializationBinder.cs | 33 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 Shoko.Server/Databases/NHIbernate/SimpleNameSerializationBinder.cs diff --git a/Shoko.Server/Databases/NHIbernate/FilterExpressionConverter.cs b/Shoko.Server/Databases/NHIbernate/FilterExpressionConverter.cs index f55c027c4..5456404a6 100644 --- a/Shoko.Server/Databases/NHIbernate/FilterExpressionConverter.cs +++ b/Shoko.Server/Databases/NHIbernate/FilterExpressionConverter.cs @@ -32,6 +32,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, System.Global { MissingMemberHandling = MissingMemberHandling.Ignore, TypeNameHandling = TypeNameHandling.Objects, + SerializationBinder = new SimpleNameSerializationBinder(), Error = (_, args) => { LogManager.GetCurrentClassLogger().Error(args.ErrorContext.Error); @@ -60,7 +61,8 @@ public override object ConvertTo(ITypeDescriptorContext context, System.Globaliz return JsonConvert.SerializeObject(value, new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Ignore, - TypeNameHandling = TypeNameHandling.Objects + TypeNameHandling = TypeNameHandling.Objects, + SerializationBinder = new SimpleNameSerializationBinder(), }); } diff --git a/Shoko.Server/Databases/NHIbernate/SimpleNameSerializationBinder.cs b/Shoko.Server/Databases/NHIbernate/SimpleNameSerializationBinder.cs new file mode 100644 index 000000000..a9b3688a4 --- /dev/null +++ b/Shoko.Server/Databases/NHIbernate/SimpleNameSerializationBinder.cs @@ -0,0 +1,33 @@ +using System; +using System.Linq; +using Newtonsoft.Json.Serialization; +using NLog; + +namespace Shoko.Server.Databases.NHIbernate; + +public class SimpleNameSerializationBinder : DefaultSerializationBinder +{ + private readonly Logger _logger = LogManager.GetCurrentClassLogger(); + private readonly Type _baseType; + + public SimpleNameSerializationBinder(Type baseType = null) + { + _baseType = baseType; + } + + public override void BindToName( + Type serializedType, out string assemblyName, out string typeName) + { + assemblyName = null; + typeName = serializedType.Name; + } + + public override Type BindToType(string assemblyName, string typeName) + { + var name = typeName.Split('.').LastOrDefault(); + var types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()) + .Where(a => a.Name.Equals(name) && (_baseType == null || _baseType.IsAssignableFrom(a))).ToArray(); + if (types.Length > 1) _logger.Warn($"SimpleNameSerializationBinder found multiple types that match {name}"); + return types.FirstOrDefault(); + } +}