From aabe283eebb4cd84aafe5d3f0f20d260ce9c686e Mon Sep 17 00:00:00 2001
From: Drommedhar <drommedhar_gaming@gmx.de>
Date: Sat, 2 Nov 2024 18:08:24 +0100
Subject: [PATCH] Update logging & write dump

---
 DlssUpdater/App.xaml.cs                       | 78 ++++++++++++++++++-
 DlssUpdater/DLSSUpdater.csproj                |  3 +-
 DlssUpdater/Defines/GameInfo.cs               |  6 +-
 .../GameLibrary/EpicGames/EpicGamesLibrary.cs |  3 +-
 DlssUpdater/GameLibrary/GOGLibrary.cs         |  3 +-
 DlssUpdater/GameLibrary/Steam/SteamLibrary.cs |  8 +-
 .../GameLibrary/UbisoftConnectLibrary.cs      |  3 +-
 DlssUpdater/GameLibrary/XboxLibrary.cs        |  3 +-
 DlssUpdater/changelog.md                      | 12 ++-
 DlssUpdater/version.json                      |  2 +-
 10 files changed, 106 insertions(+), 15 deletions(-)

diff --git a/DlssUpdater/App.xaml.cs b/DlssUpdater/App.xaml.cs
index 815357f..6a0ee81 100644
--- a/DlssUpdater/App.xaml.cs
+++ b/DlssUpdater/App.xaml.cs
@@ -1,6 +1,11 @@
-using System.IO;
+using System.Diagnostics;
+using System.IO;
 using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Security.Policy;
 using System.Windows.Threading;
+using AdonisUI.Controls;
+using DlssUpdater.Helpers;
 using DlssUpdater.Services;
 using DlssUpdater.Singletons;
 using DlssUpdater.Singletons.AntiCheatChecker;
@@ -101,11 +106,80 @@ private async void OnExit(object sender, ExitEventArgs e)
         _host.Dispose();
     }
 
+    const string ISSUE_BUTTON_ID = "GithubIssue";
     /// <summary>
     ///     Occurs when an exception is thrown by an application but not handled.
     /// </summary>
     private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
     {
-        // For more info see https://docs.microsoft.com/en-us/dotnet/api/system.windows.application.dispatcherunhandledexception?view=windowsdesktop-6.0
+        var time = DateTime.UtcNow.ToString("s").Replace(":", ".");
+        var file = $"Dumps/{time}.dmp";
+        CreateMiniDump(file);
+
+        var messageBox = new MessageBoxModel
+        {
+            Caption = "Fatal error",
+            Text = $"Application has crashed unexpectedly. A dump file was created at '{file}'. Please provide this in your github issue (as a download link).\n" +
+            $"To open a new issue click the corresponding button below.",
+            Buttons = [
+                MessageBoxButtons.Ok(),
+                MessageBoxButtons.Custom("Open github issue", ISSUE_BUTTON_ID),
+            ]
+        };
+
+        _ = AdonisUI.Controls.MessageBox.Show(messageBox);
+        if((string)messageBox.ButtonPressed.Id == ISSUE_BUTTON_ID)
+        {
+            var body = $"&body={Uri.EscapeDataString($"Encountered an unhandled exception: \n ```{e.Exception}```")}";
+            var labels = "&labels=exception";
+            var title = $"&title=Unhandled%20Exception - '{e.Exception.Message}'";
+            var url = $"https://github.com/Drommedhar/DlssUpdater/issues/new?assignees=&labels=bug&projects=&template=bug_report.md" +
+                $"{title}{labels}{body}";
+            Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
+        }
+
+        e.Handled = true;
+    }
+
+    public static class MINIDUMP_TYPE
+    {
+        public const int MiniDumpNormal = 0x00000000;
+        public const int MiniDumpWithDataSegs = 0x00000001;
+        public const int MiniDumpWithFullMemory = 0x00000002;
+        public const int MiniDumpWithHandleData = 0x00000004;
+        public const int MiniDumpFilterMemory = 0x00000008;
+        public const int MiniDumpScanMemory = 0x00000010;
+        public const int MiniDumpWithUnloadedModules = 0x00000020;
+        public const int MiniDumpWithIndirectlyReferencedMemory = 0x00000040;
+        public const int MiniDumpFilterModulePaths = 0x00000080;
+        public const int MiniDumpWithProcessThreadData = 0x00000100;
+        public const int MiniDumpWithPrivateReadWriteMemory = 0x00000200;
+        public const int MiniDumpWithoutOptionalData = 0x00000400;
+        public const int MiniDumpWithFullMemoryInfo = 0x00000800;
+        public const int MiniDumpWithThreadInfo = 0x00001000;
+        public const int MiniDumpWithCodeSegs = 0x00002000;
+    }
+
+    [DllImport("dbghelp.dll")]
+    public static extern bool MiniDumpWriteDump(IntPtr hProcess,
+                                                Int32 ProcessId,
+                                                IntPtr hFile,
+                                                int DumpType,
+                                                IntPtr ExceptionParam,
+                                                IntPtr UserStreamParam,
+                                                IntPtr CallackParam);
+
+    private static void CreateMiniDump(string file)
+    {
+        DirectoryHelper.EnsureDirectoryExists("Dumps");
+        using FileStream fs = new(file, FileMode.Create);
+        using Process process = Process.GetCurrentProcess();
+        MiniDumpWriteDump(process.Handle,
+                                         process.Id,
+                                         fs.SafeFileHandle.DangerousGetHandle(),
+                                         MINIDUMP_TYPE.MiniDumpWithFullMemory,
+                                         IntPtr.Zero,
+                                         IntPtr.Zero,
+                                         IntPtr.Zero);
     }
 }
\ No newline at end of file
diff --git a/DlssUpdater/DLSSUpdater.csproj b/DlssUpdater/DLSSUpdater.csproj
index ac9e79d..fedc25f 100644
--- a/DlssUpdater/DLSSUpdater.csproj
+++ b/DlssUpdater/DLSSUpdater.csproj
@@ -13,7 +13,7 @@
         <SelfContained>true</SelfContained>
         <RuntimeIdentifiers>win-x64</RuntimeIdentifiers>
         <SignAssembly>False</SignAssembly>
-        <AssemblyVersion>2.0.4.0</AssemblyVersion>
+        <AssemblyVersion>2.0.5.1</AssemblyVersion>
     </PropertyGroup>
 
     <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
@@ -33,6 +33,7 @@
         <PackageReference Include="AdonisUI.ClassicTheme" Version="1.17.1" />
         <PackageReference Include="Microsoft.Security.Extensions" Version="1.3.0" />
         <PackageReference Include="NLog" Version="5.3.4" />
+        <PackageReference Include="Octokit" Version="13.0.1" />
         <PackageReference Include="System.Drawing.Common" Version="8.0.8" />
         <PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
         <PackageReference Include="CommunityToolkit.Mvvm" Version="8.3.1" />
diff --git a/DlssUpdater/Defines/GameInfo.cs b/DlssUpdater/Defines/GameInfo.cs
index 87c6242..97ff85b 100644
--- a/DlssUpdater/Defines/GameInfo.cs
+++ b/DlssUpdater/Defines/GameInfo.cs
@@ -39,7 +39,7 @@ public partial class GameInfo : ObservableObject, IEquatable<GameInfo>
     }
     [ObservableProperty] public Visibility _removeVisible;
 
-    [JsonIgnore] public AntiCheatProvider AntiCheat;
+    [JsonIgnore] public AntiCheatProvider AntiCheat = AntiCheatProvider.None;
 
     [ObservableProperty] [JsonIgnore] public GameInfo _self;
 
@@ -98,8 +98,6 @@ public GameInfo(string gameName, string gamePath, LibraryType type)
         foreach (DllType dllType in Enum.GetValues(typeof(DllType))) InstalledDlls.Add(dllType, new InstalledPackage());
 
         Self = this;
-        AntiCheat = App.GetService<AntiCheatChecker>()!.Check(gamePath);
-        SetAntiCheatImage();
         _updater = App.GetService<DllUpdater>()!;
         _logger = App.GetService<NLog.Logger>()!;
         _libPage = App.GetService<LibraryPage>()!;
@@ -161,7 +159,7 @@ await Task.Run(() =>
                 foreach (var (dll, info) in InstalledDlls)
                 {
                     var allFiles = Directory.GetFiles(GamePath, GetDllName(dll), SearchOption.AllDirectories);
-                    _logger.Debug($"Found '{allFiles?.Length.ToString() ?? "0"} files' for {GetDllName(dll)} in {GameName}");
+                    //_logger.Debug($"Found '{allFiles?.Length.ToString() ?? "0"} files' for {GetDllName(dll)} in {GameName}");
                     if (allFiles is null || allFiles.Length == 0)
                     {
                         continue;
diff --git a/DlssUpdater/GameLibrary/EpicGames/EpicGamesLibrary.cs b/DlssUpdater/GameLibrary/EpicGames/EpicGamesLibrary.cs
index c151c3b..bb0315c 100644
--- a/DlssUpdater/GameLibrary/EpicGames/EpicGamesLibrary.cs
+++ b/DlssUpdater/GameLibrary/EpicGames/EpicGamesLibrary.cs
@@ -136,11 +136,12 @@ private async Task<List<GameInfo>> getGames()
                     await info.GatherInstalledVersions();
                     if (info.HasInstalledDlls())
                     {
+                        _logger.Debug($"EpicGames: '{info.GamePath}' has DLSS dll and is being added.");
                         ret.Add(info);
                     }
                     else
                     {
-                        _logger.Debug($"EpicGames: '{info.GameName}' does not have any DLSS dll and is being ignored.");
+                        _logger.Debug($"EpicGames: '{info.GamePath}' does not have any DLSS dll and is being ignored.");
                     }
                 }
                 catch (Exception ex)
diff --git a/DlssUpdater/GameLibrary/GOGLibrary.cs b/DlssUpdater/GameLibrary/GOGLibrary.cs
index 185fd17..f249f39 100644
--- a/DlssUpdater/GameLibrary/GOGLibrary.cs
+++ b/DlssUpdater/GameLibrary/GOGLibrary.cs
@@ -95,11 +95,12 @@ private async Task<List<GameInfo>> getGames()
                     await info.GatherInstalledVersions();
                     if (info.HasInstalledDlls())
                     {
+                        _logger.Debug($"GOG: '{info.GamePath}' has DLSS dll and is being added.");
                         ret.Add(info);
                     }
                     else
                     {
-                        _logger.Debug($"GOG: '{info.GameName}' does not have any DLSS dll and is being ignored.");
+                        _logger.Debug($"GOG: '{info.GamePath}' does not have any DLSS dll and is being ignored.");
                     }
                 }
                 finally
diff --git a/DlssUpdater/GameLibrary/Steam/SteamLibrary.cs b/DlssUpdater/GameLibrary/Steam/SteamLibrary.cs
index 7122112..3f3d228 100644
--- a/DlssUpdater/GameLibrary/Steam/SteamLibrary.cs
+++ b/DlssUpdater/GameLibrary/Steam/SteamLibrary.cs
@@ -169,9 +169,13 @@ private async Task<List<GameInfo>> getGames(List<LibraryFolder> folder)
         }
 
         await info.GatherInstalledVersions();
-        if (info.HasInstalledDlls()) return info;
+        if (info.HasInstalledDlls())
+        {
+            _logger.Debug($"Steam: '{info.GamePath}' has DLSS dll and is being added.");
+            return info; 
+        }
 
-        _logger.Debug($"Steam: '{info.GameName}' does not have any DLSS dll and is being ignored.");
+        _logger.Debug($"Steam: '{info.GamePath}' does not have any DLSS dll and is being ignored.");
         return null;
     }
 
diff --git a/DlssUpdater/GameLibrary/UbisoftConnectLibrary.cs b/DlssUpdater/GameLibrary/UbisoftConnectLibrary.cs
index 1442b74..522f137 100644
--- a/DlssUpdater/GameLibrary/UbisoftConnectLibrary.cs
+++ b/DlssUpdater/GameLibrary/UbisoftConnectLibrary.cs
@@ -116,11 +116,12 @@ private async Task<List<GameInfo>> getGames()
                         {
                             info.SetGameImageUri(imageUri);
                         }
+                        _logger.Debug($"Ubisoft connect: '{info.GamePath}' has DLSS dll and is being added.");
                         ret.Add(info);
                     }
                     else
                     {
-                        _logger.Debug($"Ubisoft connect: '{info.GameName}' does not have any DLSS dll and is being ignored.");
+                        _logger.Debug($"Ubisoft connect: '{info.GamePath}' does not have any DLSS dll and is being ignored.");
                     }
                 }
                 finally
diff --git a/DlssUpdater/GameLibrary/XboxLibrary.cs b/DlssUpdater/GameLibrary/XboxLibrary.cs
index 262c10e..e7d1fce 100644
--- a/DlssUpdater/GameLibrary/XboxLibrary.cs
+++ b/DlssUpdater/GameLibrary/XboxLibrary.cs
@@ -135,11 +135,12 @@ private async Task<List<GameInfo>> getGames()
                             await info.GatherInstalledVersions();
                             if (info.HasInstalledDlls())
                             {
+                                _logger.Debug($"Xbox: '{info.GamePath}' has DLSS dll and is being added.");
                                 ret.Add(info);
                             }
                             else
                             {
-                                _logger.Debug($"Xbox: '{info.GameName}' does not have any DLSS dll and is being ignored.");
+                                _logger.Debug($"Xbox: '{info.GamePath}' does not have any DLSS dll and is being ignored.");
                             }
                         }
                     }
diff --git a/DlssUpdater/changelog.md b/DlssUpdater/changelog.md
index d9cd80d..9065773 100644
--- a/DlssUpdater/changelog.md
+++ b/DlssUpdater/changelog.md
@@ -1,4 +1,14 @@
-# 2.0.4.0
+# 2.0.5.1
+* Write dump on unhandled crash
+* Adjust logging for more readable information
+
+# 2.0.5.0
+* Executable is now properly signed
+* Splashscreen shows progress for each library
+* Correctly remove games from library if they are no logner reported by launcher
+* Detect anti cheat on startup again
+
+# 2.0.4.0
 * Improve speed of game gather step
 * Fix bug after adding a new game the game will be already selected on adding another manual game
 * Changing game data in configuration view only applies if clicking apply now not in realtime
diff --git a/DlssUpdater/version.json b/DlssUpdater/version.json
index e897162..026af40 100644
--- a/DlssUpdater/version.json
+++ b/DlssUpdater/version.json
@@ -1,3 +1,3 @@
 {
-  "version": "2.0.4.0"
+  "version": "2.0.5.1"
 }
\ No newline at end of file