From 40a44145feb32ce5cbe6aefcd3128b031013b1d6 Mon Sep 17 00:00:00 2001 From: jetsparrow Date: Thu, 22 Apr 2021 15:33:16 +0300 Subject: [PATCH] Add NamespacedId and converters --- JetHerald/DapperMappers.cs | 25 ++++++++++++++++++++ JetHerald/NamespacedId.cs | 47 ++++++++++++++++++++++++++++++++++++++ JetHerald/Program.cs | 2 ++ 3 files changed, 74 insertions(+) create mode 100644 JetHerald/DapperMappers.cs create mode 100644 JetHerald/NamespacedId.cs diff --git a/JetHerald/DapperMappers.cs b/JetHerald/DapperMappers.cs new file mode 100644 index 0000000..e22223b --- /dev/null +++ b/JetHerald/DapperMappers.cs @@ -0,0 +1,25 @@ +using System.Data; + +using Dapper; + +namespace JetHerald +{ + public static class DapperConverters + { + static bool registered = false; + public static void Register() + { + if (registered) + return; + registered = true; + + SqlMapper.AddTypeHandler(new NamespacedIdHandler()); + } + + class NamespacedIdHandler : SqlMapper.TypeHandler + { + public override void SetValue(IDbDataParameter parameter, NamespacedId value) => parameter.Value = value.ToString(); + public override NamespacedId Parse(object value) => new NamespacedId((string)value); + } + } +} \ No newline at end of file diff --git a/JetHerald/NamespacedId.cs b/JetHerald/NamespacedId.cs new file mode 100644 index 0000000..a8c8b3e --- /dev/null +++ b/JetHerald/NamespacedId.cs @@ -0,0 +1,47 @@ +using System; + +namespace JetHerald +{ + public struct NamespacedId + { + public string Namespace { get; init; } + public string Id { get; init; } + + public NamespacedId(string str) + { + var ind = str.IndexOf("://"); + if (ind < 0) throw new ArgumentException("Could not parse namespaced id"); + Namespace = str[..ind].ToLowerInvariant(); + Id = str[(ind + 3)..]; + } + + public NamespacedId(string ns, string id) + { + Namespace = ns; + Id = id; + } + + public static NamespacedId Telegram(long id) + => new NamespacedId("telegram", $"{id}"); + + public static NamespacedId Discord(ulong id) + => new NamespacedId("discord", $"{id}"); + + public override string ToString() => $"{Namespace}://{Id}"; + + public override int GetHashCode() => HashCode.Combine(Namespace, Id); + + public override bool Equals(object obj) + => obj is NamespacedId nsid && this == nsid; + + public static bool operator == (NamespacedId a, NamespacedId b) + => a.Namespace == b.Namespace && a.Id == b.Id; + + public static bool operator !=(NamespacedId a, NamespacedId b) + => !(a == b); + + } + + + +} diff --git a/JetHerald/Program.cs b/JetHerald/Program.cs index e1616c0..b6674e4 100644 --- a/JetHerald/Program.cs +++ b/JetHerald/Program.cs @@ -15,6 +15,8 @@ namespace JetHerald { public static void Main(string[] args) { + DapperConverters.Register(); + var logger = NLog.Web.NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger(); try {