using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Avalonia.Controls; using MessagePack; using MessagePack.Resolvers; using ShakerApp.Models; using ShakerApp.ViewModels; namespace ShakerApp.Tools { public static class Tools { public static void CalcStatistics(ref StatisticsViewModel model,ref float value,uint len) { } public static string GetUnit(this Models.TimeDomainType type) { return (type.GetType()? .GetField(type.ToString())? .GetCustomAttributes() .FirstOrDefault())?.Unit ?? ""; } private static MessagePackSerializerOptions options = TypelessContractlessStandardResolver.Options.WithOmitAssemblyVersion(true); public static byte[] GetBytes(this T value) { return MessagePack.MessagePackSerializer.Serialize(value,options); } public static byte[] Serialize(Type type,object? value) { return MessagePack.MessagePackSerializer.Serialize(type, value, options); } public static object? Deserialize(Type type, ReadOnlyMemory bytes) { try { return MessagePack.MessagePackSerializer.Deserialize(type, bytes, options); } catch { return Activator.CreateInstance(type); } } public static T GetValue(this byte[] data) { return MessagePackSerializer.Deserialize(data,options); } public static T? ReadConfig(this string configPath) { try { return Newtonsoft.Json.JsonConvert.DeserializeObject(System.IO.File.ReadAllText(configPath)); } catch { } return default; } public static void SaveConfig(this T? value,string configPath) { value = value ?? default; try { if (System.IO.File.Exists(configPath)) System.IO.File.Delete(configPath); System.IO.File.WriteAllText(configPath, Newtonsoft.Json.JsonConvert.SerializeObject(value, Newtonsoft.Json.Formatting.Indented)); } catch { } } static Dictionary ViewCache = new Dictionary(); public static T CreateView(bool cache = true)where T:Control { if(cache) { Type t = typeof(T); if (ViewCache.TryGetValue(t.TypeHandle, out var control)) return (T)control; else { ViewCache[t.TypeHandle] = Activator.CreateInstance(); return (T)ViewCache[t.TypeHandle]; } } else { return Activator.CreateInstance(); } } public static Control CreateView(Type type, bool cache = true) { if (cache) { if (ViewCache.TryGetValue(type.TypeHandle, out var control)) return control; else { ViewCache[type.TypeHandle] = (Control)Activator.CreateInstance(type)!; return ViewCache[type.TypeHandle]; } } else { return (Control)Activator.CreateInstance(type)!; } } } }