using System.Collections.Concurrent; using System.Collections.ObjectModel; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Text.Json; using System.Text.Json.Serialization; using System.Windows.Media.Imaging; namespace Livia.Utility; public static class UtilityExtensions { public static readonly JsonSerializerOptions JsonSerializerOptions = new() { NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals }; public static string RemoveAllWhiteSpace(this string str) { return string.Concat(str.Where(c => !char.IsWhiteSpace(c))); } public static void AddRange(this ObservableCollection list, IEnumerable items) { foreach (T item in items) { list.Add(item); } } public static BitmapImage ToBitmapImage(this Bitmap bitmap) { BitmapImage bitmapImage = new(); bitmapImage.BeginInit(); using MemoryStream memoryStream = new(); bitmap.Save(memoryStream, ImageFormat.Bmp); memoryStream.Seek(0, SeekOrigin.Begin); bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.StreamSource = memoryStream; bitmapImage.EndInit(); bitmapImage.Freeze(); return bitmapImage; } public static void AddToCollectionWithKey(this IDictionary dictionary, TKey key, TValue value) where TCollection : ICollection, new() where TKey : notnull { if (!dictionary.TryGetValue(key, out TCollection? collection)) { collection = new TCollection(); dictionary.Add(key, collection); } collection.Add(value); } public static void AddToCollectionWithKey(this IDictionary> dictionary, TKey key, TValue value) where TKey : notnull { if (!dictionary.TryGetValue(key, out ConcurrentBag? collection)) { collection = new ConcurrentBag(); dictionary.Add(key, collection); } collection.Add(value); } }