Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add error handling to IconEx::GetImageSource #2941

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions Bloxstrap/Extensions/IconEx.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
}
}
}
14 changes: 14 additions & 0 deletions Bloxstrap/Utilities.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System.ComponentModel;
using System.Windows.Media.Imaging;
using System.Windows.Media;

namespace Bloxstrap
{
Expand Down Expand Up @@ -81,5 +83,17 @@ public static Process[] GetProcessesSafe()
return Array.Empty<Process>(); // 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);
}
}
}