From 9f7e989e6bf015cbd610679efbd65c76e2b1c5b6 Mon Sep 17 00:00:00 2001 From: bluepilledgreat <97983689+bluepilledgreat@users.noreply.github.com> Date: Sat, 21 Sep 2024 18:46:33 +0100 Subject: [PATCH] add error handling to iconex getimagesource --- Bloxstrap/Extensions/IconEx.cs | 19 ++++++++++++++++--- Bloxstrap/Utilities.cs | 14 ++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/Bloxstrap/Extensions/IconEx.cs b/Bloxstrap/Extensions/IconEx.cs index 2cd48af7..2891c6e1 100644 --- a/Bloxstrap/Extensions/IconEx.cs +++ b/Bloxstrap/Extensions/IconEx.cs @@ -10,9 +10,22 @@ public static class IconEx public static ImageSource GetImageSource(this Icon icon) { - using MemoryStream stream = new(); - icon.Save(stream); - return BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); + const string LOG_IDENT = "IconEx::GetImageSource"; + + try + { + using MemoryStream stream = new(); + icon.Save(stream); + return BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); + } + catch (Exception ex) + { + App.Logger.WriteLine(LOG_IDENT, "Failed to get ImageSource"); + App.Logger.WriteException(LOG_IDENT, ex); + + // return fallback image + return Utilities.GetEmptyBitmap(); + } } } } diff --git a/Bloxstrap/Utilities.cs b/Bloxstrap/Utilities.cs index 327f7340..c0a8ffa5 100644 --- a/Bloxstrap/Utilities.cs +++ b/Bloxstrap/Utilities.cs @@ -1,4 +1,6 @@ using System.ComponentModel; +using System.Windows.Media.Imaging; +using System.Windows.Media; namespace Bloxstrap { @@ -81,5 +83,17 @@ public static Process[] GetProcessesSafe() return Array.Empty(); // can we retry? } } + + private static BitmapSource? _emptyBitmap; + public static BitmapSource GetEmptyBitmap() + { + return _emptyBitmap ??= CreateEmptyBitmap(); + } + + // https://stackoverflow.com/a/50316845 + public static BitmapSource CreateEmptyBitmap() + { + return BitmapSource.Create(1, 1, 1, 1, PixelFormats.BlackWhite, null, new byte[] { 0 }, 1); + } } }