From 67d0771b28aaeb221313502ebe7500ac1bbe6967 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Mon, 20 Apr 2020 18:16:16 +0530 Subject: [PATCH 001/181] Enabled settings syncing accross all windowss --- .../InteropConnectionService.cs | 51 +++++++ .../Notepads.Services.csproj | 143 ++++++++++++++++++ .../Properties/AssemblyInfo.cs | 29 ++++ src/Notepads.sln | 38 +++++ src/Notepads/App.xaml.cs | 1 - src/Notepads/Notepads.csproj | 15 +- src/Notepads/Package.appxmanifest | 6 +- .../Services/EditorSettingsService.cs | 34 ++--- src/Notepads/Services/InteropService.cs | 100 ++++++++++++ src/Notepads/Services/ThemeSettingsService.cs | 70 +++------ src/Notepads/Settings/SettingsDelegate.cs | 138 +++++++++++++++++ src/Notepads/Settings/SettingsKey.cs | 1 - src/Notepads/Strings/en-US/Resources.resw | 2 +- .../Views/AdvancedSettingsPage.xaml.cs | 3 + .../Views/NotepadsMainPage.MainMenu.cs | 3 +- src/Notepads/Views/NotepadsMainPage.xaml.cs | 20 +++ .../Views/PersonalizationSettingsPage.xaml.cs | 43 +++--- .../Views/TextAndEditorSettingsPage.xaml.cs | 20 +++ 18 files changed, 627 insertions(+), 90 deletions(-) create mode 100644 src/Notepads.Services/InteropConnectionService.cs create mode 100644 src/Notepads.Services/Notepads.Services.csproj create mode 100644 src/Notepads.Services/Properties/AssemblyInfo.cs create mode 100644 src/Notepads/Services/InteropService.cs create mode 100644 src/Notepads/Settings/SettingsDelegate.cs diff --git a/src/Notepads.Services/InteropConnectionService.cs b/src/Notepads.Services/InteropConnectionService.cs new file mode 100644 index 000000000..2b09acd07 --- /dev/null +++ b/src/Notepads.Services/InteropConnectionService.cs @@ -0,0 +1,51 @@ +namespace Notepads.Services +{ + using System; + using System.Collections.Generic; + using Windows.ApplicationModel; + using Windows.ApplicationModel.AppService; + using Windows.ApplicationModel.Background; + using Windows.Foundation.Collections; + + public sealed class InteropConnectionService : IBackgroundTask + { + private BackgroundTaskDeferral backgroundTaskDeferral; + private AppServiceConnection appServiceConnection; + private static IList appServiceConnections = new List(); + + public void Run(IBackgroundTaskInstance taskInstance) + { + // Get a deferral so that the service isn't terminated. + this.backgroundTaskDeferral = taskInstance.GetDeferral(); + + // Associate a cancellation handler with the background task. + taskInstance.Canceled += OnTaskCanceled; + + // Retrieve the app service connection and set up a listener for incoming app service requests. + var details = taskInstance.TriggerDetails as AppServiceTriggerDetails; + appServiceConnection = details.AppServiceConnection; + appServiceConnections.Add(appServiceConnection); + appServiceConnection.RequestReceived += OnRequestReceived; + } + + private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) + { + foreach(var serviceConnection in appServiceConnections) + { + if (serviceConnection != appServiceConnection) + await serviceConnection.SendMessageAsync(args.Request.Message); + } + } + + private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) + { + if (this.backgroundTaskDeferral != null) + { + // Complete the service deferral. + this.backgroundTaskDeferral.Complete(); + var details = sender.TriggerDetails as AppServiceTriggerDetails; + appServiceConnections.Remove(details.AppServiceConnection); + } + } + } +} diff --git a/src/Notepads.Services/Notepads.Services.csproj b/src/Notepads.Services/Notepads.Services.csproj new file mode 100644 index 000000000..6e17a1787 --- /dev/null +++ b/src/Notepads.Services/Notepads.Services.csproj @@ -0,0 +1,143 @@ + + + + + Debug + AnyCPU + {29DCAA68-1B6B-4290-8C05-691F52645D55} + winmdobj + Properties + Notepads.Services + Notepads.Services + en-US + UAP + 10.0.18362.0 + 10.0.17763.0 + 14 + 512 + {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} + false + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + prompt + 4 + + + x86 + true + bin\x86\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ;2008 + full + false + prompt + + + x86 + bin\x86\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + true + ;2008 + pdbonly + false + prompt + + + ARM + true + bin\ARM\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ;2008 + full + false + prompt + + + ARM + bin\ARM\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + true + ;2008 + pdbonly + false + prompt + + + ARM64 + true + bin\ARM64\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ;2008 + full + false + prompt + + + ARM64 + bin\ARM64\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + true + ;2008 + pdbonly + false + prompt + + + x64 + true + bin\x64\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP + ;2008 + full + false + prompt + + + x64 + bin\x64\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP + true + ;2008 + pdbonly + false + prompt + + + PackageReference + + + + + + + + 6.2.9 + + + + 14.0 + + + + \ No newline at end of file diff --git a/src/Notepads.Services/Properties/AssemblyInfo.cs b/src/Notepads.Services/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..7b0f0f6c3 --- /dev/null +++ b/src/Notepads.Services/Properties/AssemblyInfo.cs @@ -0,0 +1,29 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Notepads.Services")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Notepads.Services")] +[assembly: AssemblyCopyright("Copyright © 2020")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: ComVisible(false)] \ No newline at end of file diff --git a/src/Notepads.sln b/src/Notepads.sln index ad5a84593..cf7f8698f 100644 --- a/src/Notepads.sln +++ b/src/Notepads.sln @@ -15,16 +15,24 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution .editorconfig = .editorconfig EndProjectSection EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Notepads.Services", "Notepads.Services\Notepads.Services.csproj", "{29DCAA68-1B6B-4290-8C05-691F52645D55}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|ARM = Debug|ARM Debug|ARM64 = Debug|ARM64 Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|ARM = Release|ARM Release|ARM64 = Release|ARM64 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution + {99274932-9E86-480C-8142-38525F80007D}.Debug|Any CPU.ActiveCfg = Debug|x86 + {99274932-9E86-480C-8142-38525F80007D}.Debug|ARM.ActiveCfg = Debug|x86 {99274932-9E86-480C-8142-38525F80007D}.Debug|ARM64.ActiveCfg = Debug|ARM64 {99274932-9E86-480C-8142-38525F80007D}.Debug|ARM64.Build.0 = Debug|ARM64 {99274932-9E86-480C-8142-38525F80007D}.Debug|ARM64.Deploy.0 = Debug|ARM64 @@ -34,6 +42,8 @@ Global {99274932-9E86-480C-8142-38525F80007D}.Debug|x86.ActiveCfg = Debug|x86 {99274932-9E86-480C-8142-38525F80007D}.Debug|x86.Build.0 = Debug|x86 {99274932-9E86-480C-8142-38525F80007D}.Debug|x86.Deploy.0 = Debug|x86 + {99274932-9E86-480C-8142-38525F80007D}.Release|Any CPU.ActiveCfg = Release|x86 + {99274932-9E86-480C-8142-38525F80007D}.Release|ARM.ActiveCfg = Release|x86 {99274932-9E86-480C-8142-38525F80007D}.Release|ARM64.ActiveCfg = Release|ARM64 {99274932-9E86-480C-8142-38525F80007D}.Release|ARM64.Build.0 = Release|ARM64 {99274932-9E86-480C-8142-38525F80007D}.Release|ARM64.Deploy.0 = Release|ARM64 @@ -43,18 +53,46 @@ Global {99274932-9E86-480C-8142-38525F80007D}.Release|x86.ActiveCfg = Release|x86 {99274932-9E86-480C-8142-38525F80007D}.Release|x86.Build.0 = Release|x86 {99274932-9E86-480C-8142-38525F80007D}.Release|x86.Deploy.0 = Release|x86 + {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|Any CPU.Build.0 = Debug|Any CPU + {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|ARM.ActiveCfg = Debug|ARM + {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|ARM.Build.0 = Debug|ARM {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|ARM64.ActiveCfg = Debug|ARM64 {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|ARM64.Build.0 = Debug|ARM64 {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|x64.ActiveCfg = Debug|x64 {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|x64.Build.0 = Debug|x64 {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|x86.ActiveCfg = Debug|x86 {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|x86.Build.0 = Debug|x86 + {7AA5E631-B663-420E-A08F-002CD81DF855}.Release|Any CPU.ActiveCfg = Release|Any CPU + {7AA5E631-B663-420E-A08F-002CD81DF855}.Release|Any CPU.Build.0 = Release|Any CPU + {7AA5E631-B663-420E-A08F-002CD81DF855}.Release|ARM.ActiveCfg = Release|ARM + {7AA5E631-B663-420E-A08F-002CD81DF855}.Release|ARM.Build.0 = Release|ARM {7AA5E631-B663-420E-A08F-002CD81DF855}.Release|ARM64.ActiveCfg = Release|ARM64 {7AA5E631-B663-420E-A08F-002CD81DF855}.Release|ARM64.Build.0 = Release|ARM64 {7AA5E631-B663-420E-A08F-002CD81DF855}.Release|x64.ActiveCfg = Release|x64 {7AA5E631-B663-420E-A08F-002CD81DF855}.Release|x64.Build.0 = Release|x64 {7AA5E631-B663-420E-A08F-002CD81DF855}.Release|x86.ActiveCfg = Release|x86 {7AA5E631-B663-420E-A08F-002CD81DF855}.Release|x86.Build.0 = Release|x86 + {29DCAA68-1B6B-4290-8C05-691F52645D55}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {29DCAA68-1B6B-4290-8C05-691F52645D55}.Debug|Any CPU.Build.0 = Debug|Any CPU + {29DCAA68-1B6B-4290-8C05-691F52645D55}.Debug|ARM.ActiveCfg = Debug|ARM + {29DCAA68-1B6B-4290-8C05-691F52645D55}.Debug|ARM.Build.0 = Debug|ARM + {29DCAA68-1B6B-4290-8C05-691F52645D55}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {29DCAA68-1B6B-4290-8C05-691F52645D55}.Debug|ARM64.Build.0 = Debug|ARM64 + {29DCAA68-1B6B-4290-8C05-691F52645D55}.Debug|x64.ActiveCfg = Debug|x64 + {29DCAA68-1B6B-4290-8C05-691F52645D55}.Debug|x64.Build.0 = Debug|x64 + {29DCAA68-1B6B-4290-8C05-691F52645D55}.Debug|x86.ActiveCfg = Debug|x86 + {29DCAA68-1B6B-4290-8C05-691F52645D55}.Debug|x86.Build.0 = Debug|x86 + {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|Any CPU.ActiveCfg = Release|Any CPU + {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|Any CPU.Build.0 = Release|Any CPU + {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|ARM.ActiveCfg = Release|ARM + {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|ARM.Build.0 = Release|ARM + {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|ARM64.ActiveCfg = Release|ARM64 + {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|ARM64.Build.0 = Release|ARM64 + {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|x64.ActiveCfg = Release|x64 + {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|x64.Build.0 = Release|x64 + {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|x86.ActiveCfg = Release|x86 + {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/Notepads/App.xaml.cs b/src/Notepads/App.xaml.cs index 7db90ff14..980f080f6 100644 --- a/src/Notepads/App.xaml.cs +++ b/src/Notepads/App.xaml.cs @@ -92,7 +92,6 @@ private async Task ActivateAsync(IActivatedEventArgs e) { { "OSArchitecture", SystemInformation.OperatingSystemArchitecture.ToString() }, { "OSVersion", SystemInformation.OperatingSystemVersion.ToString() }, - { "UseWindowsTheme", ThemeSettingsService.UseWindowsTheme.ToString() }, { "ThemeMode", ThemeSettingsService.ThemeMode.ToString() }, { "UseWindowsAccentColor", ThemeSettingsService.UseWindowsAccentColor.ToString() }, { "AppBackgroundTintOpacity", $"{(int) (ThemeSettingsService.AppBackgroundPanelTintOpacity * 100.0)}" }, diff --git a/src/Notepads/Notepads.csproj b/src/Notepads/Notepads.csproj index aaeaf7495..7b3a9c8ed 100644 --- a/src/Notepads/Notepads.csproj +++ b/src/Notepads/Notepads.csproj @@ -124,6 +124,8 @@ PrintPageFormat.xaml + + AboutPage.xaml @@ -612,9 +614,15 @@ {7aa5e631-b663-420e-a08f-002cd81df855} Notepads.Controls + + {29dcaa68-1b6b-4290-8c05-691f52645d55} + Notepads.Services + - + + Designer + @@ -739,6 +747,11 @@ + + + Windows Desktop Extensions for the UWP + + 14.0 diff --git a/src/Notepads/Package.appxmanifest b/src/Notepads/Package.appxmanifest index 40063562f..dc09e0ffe 100644 --- a/src/Notepads/Package.appxmanifest +++ b/src/Notepads/Package.appxmanifest @@ -4,11 +4,12 @@ xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" + xmlns:uap3="http://schemas.microsoft.com/appx/manifest/uap/windows10/3" xmlns:uap5="http://schemas.microsoft.com/appx/manifest/uap/windows10/5" xmlns:desktop4="http://schemas.microsoft.com/appx/manifest/desktop/windows10/4" xmlns:iot2="http://schemas.microsoft.com/appx/manifest/iot/windows10/2" xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" - IgnorableNamespaces="uap mp uap5 desktop4 iot2 rescap"> + IgnorableNamespaces="mp uap uap3 uap5 desktop4 iot2 rescap"> + + + diff --git a/src/Notepads/Services/EditorSettingsService.cs b/src/Notepads/Services/EditorSettingsService.cs index 2a50bfc4b..7e66f0114 100644 --- a/src/Notepads/Services/EditorSettingsService.cs +++ b/src/Notepads/Services/EditorSettingsService.cs @@ -28,7 +28,7 @@ public static string EditorFontFamily { _editorFontFamily = value; OnFontFamilyChanged?.Invoke(null, value); - ApplicationSettingsStore.Write(SettingsKey.EditorFontFamilyStr, value); + if(InteropService.EnableSettingsLogging) ApplicationSettingsStore.Write(SettingsKey.EditorFontFamilyStr, value); } } @@ -41,7 +41,7 @@ public static int EditorFontSize { _editorFontSize = value; OnFontSizeChanged?.Invoke(null, value); - ApplicationSettingsStore.Write(SettingsKey.EditorFontSizeInt, value); + if (InteropService.EnableSettingsLogging) ApplicationSettingsStore.Write(SettingsKey.EditorFontSizeInt, value); } } @@ -54,7 +54,7 @@ public static TextWrapping EditorDefaultTextWrapping { _editorDefaultTextWrapping = value; OnDefaultTextWrappingChanged?.Invoke(null, value); - ApplicationSettingsStore.Write(SettingsKey.EditorDefaultTextWrappingStr, value.ToString()); + if (InteropService.EnableSettingsLogging) ApplicationSettingsStore.Write(SettingsKey.EditorDefaultTextWrappingStr, value.ToString()); } } @@ -67,7 +67,7 @@ public static bool IsLineHighlighterEnabled { _isLineHighlighterEnabled = value; OnDefaultLineHighlighterViewStateChanged?.Invoke(null, value); - ApplicationSettingsStore.Write(SettingsKey.EditorDefaultLineHighlighterViewStateBool, value); + if (InteropService.EnableSettingsLogging) ApplicationSettingsStore.Write(SettingsKey.EditorDefaultLineHighlighterViewStateBool, value); } } @@ -80,7 +80,7 @@ public static LineEnding EditorDefaultLineEnding { _editorDefaultLineEnding = value; OnDefaultLineEndingChanged?.Invoke(null, value); - ApplicationSettingsStore.Write(SettingsKey.EditorDefaultLineEndingStr, value.ToString()); + if (InteropService.EnableSettingsLogging) ApplicationSettingsStore.Write(SettingsKey.EditorDefaultLineEndingStr, value.ToString()); } } @@ -95,12 +95,12 @@ public static Encoding EditorDefaultEncoding if (value is UTF8Encoding) { - ApplicationSettingsStore.Write(SettingsKey.EditorDefaultUtf8EncoderShouldEmitByteOrderMarkBool, + if (InteropService.EnableSettingsLogging) ApplicationSettingsStore.Write(SettingsKey.EditorDefaultUtf8EncoderShouldEmitByteOrderMarkBool, Equals(value, new UTF8Encoding(true))); } OnDefaultEncodingChanged?.Invoke(null, value); - ApplicationSettingsStore.Write(SettingsKey.EditorDefaultEncodingCodePageInt, value.CodePage); + if (InteropService.EnableSettingsLogging) ApplicationSettingsStore.Write(SettingsKey.EditorDefaultEncodingCodePageInt, value.CodePage); } } @@ -137,7 +137,7 @@ public static Encoding EditorDefaultDecoding { _editorDefaultDecoding = value; var codePage = value?.CodePage ?? -1; - ApplicationSettingsStore.Write(SettingsKey.EditorDefaultDecodingCodePageInt, codePage); + if (InteropService.EnableSettingsLogging) ApplicationSettingsStore.Write(SettingsKey.EditorDefaultDecodingCodePageInt, codePage); } } @@ -150,7 +150,7 @@ public static int EditorDefaultTabIndents { _editorDefaultTabIndents = value; OnDefaultTabIndentsChanged?.Invoke(null, value); - ApplicationSettingsStore.Write(SettingsKey.EditorDefaultTabIndentsInt, value); + if (InteropService.EnableSettingsLogging) ApplicationSettingsStore.Write(SettingsKey.EditorDefaultTabIndentsInt, value); } } @@ -162,7 +162,7 @@ public static SearchEngine EditorDefaultSearchEngine set { _editorDefaultSearchEngine = value; - ApplicationSettingsStore.Write(SettingsKey.EditorDefaultSearchEngineStr, value.ToString()); + if (InteropService.EnableSettingsLogging) ApplicationSettingsStore.Write(SettingsKey.EditorDefaultSearchEngineStr, value.ToString()); } } @@ -174,7 +174,7 @@ public static string EditorCustomMadeSearchUrl set { _editorCustomMadeSearchUrl = value; - ApplicationSettingsStore.Write(SettingsKey.EditorCustomMadeSearchUrlStr, value); + if (InteropService.EnableSettingsLogging) ApplicationSettingsStore.Write(SettingsKey.EditorCustomMadeSearchUrlStr, value); } } @@ -187,7 +187,7 @@ public static bool ShowStatusBar { _showStatusBar = value; OnStatusBarVisibilityChanged?.Invoke(null, value); - ApplicationSettingsStore.Write(SettingsKey.EditorShowStatusBarBool, value); + if (InteropService.EnableSettingsLogging) ApplicationSettingsStore.Write(SettingsKey.EditorShowStatusBarBool, value); } } @@ -200,7 +200,7 @@ public static bool IsSessionSnapshotEnabled { _isSessionSnapshotEnabled = value; OnSessionBackupAndRestoreOptionChanged?.Invoke(null, value); - ApplicationSettingsStore.Write(SettingsKey.EditorEnableSessionBackupAndRestoreBool, value); + if (InteropService.EnableSettingsLogging) ApplicationSettingsStore.Write(SettingsKey.EditorEnableSessionBackupAndRestoreBool, value); } } @@ -213,7 +213,7 @@ public static bool IsHighlightMisspelledWordsEnabled { _isHighlightMisspelledWordsEnabled = value; OnHighlightMisspelledWordsChanged?.Invoke(null, value); - ApplicationSettingsStore.Write(SettingsKey.EditorHighlightMisspelledWordsBool, value); + if (InteropService.EnableSettingsLogging) ApplicationSettingsStore.Write(SettingsKey.EditorHighlightMisspelledWordsBool, value); } } @@ -225,7 +225,7 @@ public static bool AlwaysOpenNewWindow set { _alwaysOpenNewWindow = value; - ApplicationSettingsStore.Write(SettingsKey.AlwaysOpenNewWindowBool, value); + if (InteropService.EnableSettingsLogging) ApplicationSettingsStore.Write(SettingsKey.AlwaysOpenNewWindowBool, value); } } @@ -342,7 +342,7 @@ private static void InitializeLineHighlighterSettings() } } - private static void InitializeEncodingSettings() + public static void InitializeEncodingSettings() { Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); @@ -370,7 +370,7 @@ private static void InitializeEncodingSettings() } } - private static void InitializeDecodingSettings() + public static void InitializeDecodingSettings() { if (ApplicationSettingsStore.Read(SettingsKey.EditorDefaultDecodingCodePageInt) is int decodingCodePage) { diff --git a/src/Notepads/Services/InteropService.cs b/src/Notepads/Services/InteropService.cs new file mode 100644 index 000000000..f3a122bea --- /dev/null +++ b/src/Notepads/Services/InteropService.cs @@ -0,0 +1,100 @@ +namespace Notepads.Services +{ + using Notepads.Settings; + using System; + using System.Collections.Generic; + using Windows.ApplicationModel; + using Windows.ApplicationModel.AppService; + using Windows.Foundation.Collections; + using Windows.UI.Xaml; + + public static class InteropService + { + public static EventHandler HideSettingsPane; + public static bool EnableSettingsLogging = true; + public static bool ISAppExited = false; + + public static AppServiceConnection InteropServiceConnection = null; + + private static readonly string _appIdLabel = "Instance"; + private static readonly string _settingsKeyLabel = "Settings"; + private static readonly string _valueLabel = "Value"; + + private static IReadOnlyDictionary SettingsManager = new Dictionary + { + {SettingsKey.AlwaysOpenNewWindowBool, SettingsDelegate.AlwaysOpenNewWindow}, + {SettingsKey.AppAccentColorHexStr, SettingsDelegate.AppAccentColor}, + {SettingsKey.AppBackgroundTintOpacityDouble, SettingsDelegate.AppBackgroundPanelTintOpacity}, + {SettingsKey.CustomAccentColorHexStr, SettingsDelegate.CustomAccentColor}, + {SettingsKey.EditorCustomMadeSearchUrlStr, SettingsDelegate.EditorCustomMadeSearchUrl}, + {SettingsKey.EditorDefaultDecodingCodePageInt, SettingsDelegate.EditorDefaultDecoding}, + {SettingsKey.EditorDefaultEncodingCodePageInt, SettingsDelegate.EditorDefaultEncoding}, + {SettingsKey.EditorDefaultLineEndingStr, SettingsDelegate.EditorDefaultLineEnding}, + {SettingsKey.EditorDefaultLineHighlighterViewStateBool, SettingsDelegate.IsLineHighlighterEnabled}, + {SettingsKey.EditorDefaultSearchEngineStr, SettingsDelegate.EditorDefaultSearchEngine}, + {SettingsKey.EditorDefaultTabIndentsInt, SettingsDelegate.EditorDefaultTabIndents}, + {SettingsKey.EditorDefaultTextWrappingStr, SettingsDelegate.EditorDefaultTextWrapping}, + {SettingsKey.EditorFontFamilyStr, SettingsDelegate.EditorFontFamily}, + {SettingsKey.EditorFontSizeInt, SettingsDelegate.EditorFontSize}, + {SettingsKey.EditorHighlightMisspelledWordsBool, SettingsDelegate.IsHighlightMisspelledWordsEnabled}, + {SettingsKey.EditorShowStatusBarBool, SettingsDelegate.ShowStatusBar}, + {SettingsKey.UseWindowsAccentColorBool, SettingsDelegate.UseWindowsAccentColor}, + {SettingsKey.RequestedThemeStr, SettingsDelegate.ThemeMode} + }; + + public static async void Initialize() + { + InteropServiceConnection = new AppServiceConnection() + { + AppServiceName = "InteropServiceConnection", + PackageFamilyName = Package.Current.Id.FamilyName + }; + + InteropServiceConnection.RequestReceived += InteropServiceConnection_RequestReceived; + InteropServiceConnection.ServiceClosed += InteropServiceConnection_ServiceClosed; + + AppServiceConnectionStatus status = await InteropServiceConnection.OpenAsync(); + if (status != AppServiceConnectionStatus.Success) Application.Current.Exit(); + } + + private static void InteropServiceConnection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) + { + var message = args.Request.Message; + if (message.ContainsKey(_appIdLabel) && message[_appIdLabel] is Guid appID && appID != App.Id) + { + EnableSettingsLogging = false; + HideSettingsPane?.Invoke(null, true); + var settingsKey = message[_settingsKeyLabel] as string; + var value = message[_valueLabel] as object; + SettingsManager[settingsKey](value); + EnableSettingsLogging = true; + } + } + + private static void InteropServiceConnection_ServiceClosed(AppServiceConnection sender, AppServiceClosedEventArgs args) + { + return; + } + + public static async void SyncSettings(string settingsKey, object value) + { + var message = new ValueSet(); + message.Add(_appIdLabel, App.Id); + message.Add(_settingsKeyLabel, settingsKey); + try + { + message.Add(_valueLabel, value); + } + catch (Exception) + { + message.Add(_valueLabel, value.ToString()); + } + await InteropServiceConnection.SendMessageAsync(message); + } + + public static void CloseConnectionOnExit() + { + InteropServiceConnection.Dispose(); + } + } +} diff --git a/src/Notepads/Services/ThemeSettingsService.cs b/src/Notepads/Services/ThemeSettingsService.cs index ef1202c13..cc546e348 100644 --- a/src/Notepads/Services/ThemeSettingsService.cs +++ b/src/Notepads/Services/ThemeSettingsService.cs @@ -18,28 +18,22 @@ public static class ThemeSettingsService public static event EventHandler OnBackgroundChanged; public static event EventHandler OnAccentColorChanged; - public static ElementTheme ThemeMode { get; set; } - private static readonly UISettings UISettings = new UISettings(); private static readonly ThemeListener ThemeListener = new ThemeListener(); private static Brush _currentAppBackgroundBrush; - private static bool _useWindowsTheme; + private static ElementTheme _themeMode; - public static bool UseWindowsTheme + public static ElementTheme ThemeMode { - get => _useWindowsTheme; + get => _themeMode; set { - if (value != _useWindowsTheme) + if(value!=_themeMode) { - _useWindowsTheme = value; - if (value) - { - ThemeMode = Application.Current.RequestedTheme.ToElementTheme(); - OnThemeChanged?.Invoke(null, ThemeMode); - } - ApplicationSettingsStore.Write(SettingsKey.UseWindowsThemeBool, _useWindowsTheme); + _themeMode = value; + OnThemeChanged?.Invoke(null, value); + if (InteropService.EnableSettingsLogging) ApplicationSettingsStore.Write(SettingsKey.RequestedThemeStr, value.ToString()); } } } @@ -56,7 +50,7 @@ public static bool UseWindowsAccentColor { AppAccentColor = UISettings.GetColorValue(UIColorType.Accent); } - ApplicationSettingsStore.Write(SettingsKey.UseWindowsAccentColorBool, _useWindowsAccentColor); + if (InteropService.EnableSettingsLogging) ApplicationSettingsStore.Write(SettingsKey.UseWindowsAccentColorBool, _useWindowsAccentColor); } } @@ -69,7 +63,7 @@ public static double AppBackgroundPanelTintOpacity { _appBackgroundPanelTintOpacity = value; OnBackgroundChanged?.Invoke(null, GetAppBackgroundBrush(ThemeMode)); - ApplicationSettingsStore.Write(SettingsKey.AppBackgroundTintOpacityDouble, value); + if (InteropService.EnableSettingsLogging) ApplicationSettingsStore.Write(SettingsKey.AppBackgroundTintOpacityDouble, value); } } @@ -82,7 +76,7 @@ public static Color AppAccentColor { _appAccentColor = value; OnAccentColorChanged?.Invoke(null, _appAccentColor); - ApplicationSettingsStore.Write(SettingsKey.AppAccentColorHexStr, value.ToHex()); + if (InteropService.EnableSettingsLogging) ApplicationSettingsStore.Write(SettingsKey.AppAccentColorHexStr, value.ToHex()); } } @@ -94,7 +88,7 @@ public static Color CustomAccentColor set { _customAccentColor = value; - ApplicationSettingsStore.Write(SettingsKey.CustomAccentColorHexStr, value.ToHex()); + if (InteropService.EnableSettingsLogging) ApplicationSettingsStore.Write(SettingsKey.CustomAccentColorHexStr, value.ToHex()); } } @@ -167,44 +161,24 @@ private static void InitializeAppBackgroundPanelTintOpacity() private static void InitializeThemeMode() { - if (ApplicationSettingsStore.Read(SettingsKey.UseWindowsThemeBool) is bool useWindowsTheme) - { - _useWindowsTheme = useWindowsTheme; - } - else - { - _useWindowsTheme = true; - } - ThemeListener.ThemeChanged += ThemeListener_ThemeChanged; - ThemeMode = Application.Current.RequestedTheme.ToElementTheme(); - - if (!UseWindowsTheme) + if (ApplicationSettingsStore.Read(SettingsKey.RequestedThemeStr) is string themeModeStr) { - if (ApplicationSettingsStore.Read(SettingsKey.RequestedThemeStr) is string themeModeStr) + if (Enum.TryParse(typeof(ElementTheme), themeModeStr, out var theme)) { - if (Enum.TryParse(typeof(ElementTheme), themeModeStr, out var theme)) - { - ThemeMode = (ElementTheme)theme; - } + _themeMode = (ElementTheme)theme; } } - } - - private static void ThemeListener_ThemeChanged(ThemeListener sender) - { - if (UseWindowsTheme) + else { - SetTheme(sender.CurrentTheme.ToElementTheme()); + _themeMode = ElementTheme.Default; } } - public static void SetTheme(ElementTheme theme) + private static void ThemeListener_ThemeChanged(ThemeListener sender) { - ThemeMode = theme; - OnThemeChanged?.Invoke(null, theme); - ApplicationSettingsStore.Write(SettingsKey.RequestedThemeStr, ThemeMode.ToString()); + _themeMode = sender.CurrentTheme.ToElementTheme(); } public static void SetRequestedTheme(Panel backgroundPanel, UIElement currentContent, ApplicationViewTitleBar titleBar) @@ -227,8 +201,10 @@ public static void SetRequestedTheme(Panel backgroundPanel, UIElement currentCon } // Set ContentDialog background dimming color + var themeMode = ThemeMode; + if (themeMode == ElementTheme.Default) themeMode = Application.Current.RequestedTheme.ToElementTheme(); ((SolidColorBrush)Application.Current.Resources["SystemControlPageBackgroundMediumAltMediumBrush"]).Color = - ThemeMode == ElementTheme.Dark ? Color.FromArgb(153, 0, 0, 0) : Color.FromArgb(153, 255, 255, 255); + themeMode == ElementTheme.Dark ? Color.FromArgb(153, 0, 0, 0) : Color.FromArgb(153, 255, 255, 255); // Set accent color UpdateSystemAccentColorAndBrushes(AppAccentColor); @@ -257,6 +233,7 @@ private static Brush GetAppBackgroundBrush(ElementTheme theme) var darkModeBaseColor = Color.FromArgb(255, 50, 50, 50); var lightModeBaseColor = Color.FromArgb(255, 240, 240, 240); + if (theme == ElementTheme.Default) theme = Application.Current.RequestedTheme.ToElementTheme(); var baseColor = theme == ElementTheme.Light ? lightModeBaseColor : darkModeBaseColor; if (AppBackgroundPanelTintOpacity > 0.99f || @@ -279,6 +256,7 @@ private static Brush GetAppBackgroundBrush(ElementTheme theme) public static void ApplyThemeForTitleBarButtons(ApplicationViewTitleBar titleBar, ElementTheme theme) { + if (theme == ElementTheme.Default) theme = Application.Current.RequestedTheme.ToElementTheme(); if (theme == ElementTheme.Dark) { // Set active window colors @@ -368,7 +346,7 @@ private static void UpdateSystemAccentColorAndBrushes(Color color) } } - private static Color GetColor(string hex) + public static Color GetColor(string hex) { hex = hex.Replace("#", string.Empty); byte a = (byte)(Convert.ToUInt32(hex.Substring(0, 2), 16)); diff --git a/src/Notepads/Settings/SettingsDelegate.cs b/src/Notepads/Settings/SettingsDelegate.cs new file mode 100644 index 000000000..a25d57d40 --- /dev/null +++ b/src/Notepads/Settings/SettingsDelegate.cs @@ -0,0 +1,138 @@ +using Notepads.Services; +using Notepads.Utilities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Windows.UI; +using Windows.UI.Core; +using Windows.UI.Xaml; + +namespace Notepads.Settings +{ + public delegate void Settings(object value); + + public static class SettingsDelegate + { + public static CoreDispatcher Dispatcher; + + public static Settings EditorFontFamily = SetEditorFontFamily; + public static Settings EditorFontSize = SetEditorFontSize; + public static Settings EditorDefaultTextWrapping = SetEditorDefaultTextWrapping; + public static Settings IsLineHighlighterEnabled = SetIsLineHighlighterEnabled; + public static Settings EditorDefaultLineEnding = SetEditorDefaultLineEnding; + public static Settings EditorDefaultEncoding = SetEditorDefaultEncoding; + public static Settings EditorDefaultDecoding = SetEditorDefaultDecoding; + public static Settings EditorDefaultTabIndents = SetEditorDefaultTabIndents; + public static Settings EditorDefaultSearchEngine = SetEditorDefaultSearchEngine; + public static Settings EditorCustomMadeSearchUrl = SetEditorCustomMadeSearchUrl; + public static Settings ShowStatusBar = SetShowStatusBar; + public static Settings IsHighlightMisspelledWordsEnabled = SetIsHighlightMisspelledWordsEnabled; + public static Settings AlwaysOpenNewWindow = SetAlwaysOpenNewWindow; + + private static void SetEditorFontFamily(object value) + { + EditorSettingsService.EditorFontFamily = (string)value; + } + + private static void SetEditorFontSize(object value) + { + EditorSettingsService.EditorFontSize = (int)value; + } + + private static void SetEditorDefaultTextWrapping(object value) + { + Enum.TryParse(typeof(TextWrapping), (string)value, out var result); + EditorSettingsService.EditorDefaultTextWrapping = (TextWrapping)result; + } + + private static void SetIsLineHighlighterEnabled(object value) + { + EditorSettingsService.IsLineHighlighterEnabled = (bool)value; + } + + private static void SetEditorDefaultLineEnding(object value) + { + Enum.TryParse(typeof(LineEnding), (string)value, out var result); + EditorSettingsService.EditorDefaultLineEnding = (LineEnding)result; + } + + private static void SetEditorDefaultEncoding(object value) + { + EditorSettingsService.InitializeEncodingSettings(); + } + + private static void SetEditorDefaultDecoding(object value) + { + EditorSettingsService.InitializeDecodingSettings(); + } + + private static void SetEditorDefaultTabIndents(object value) + { + EditorSettingsService.EditorDefaultTabIndents = (int)value; + } + + private static void SetEditorDefaultSearchEngine(object value) + { + Enum.TryParse(typeof(SearchEngine), (string)value, out var result); + EditorSettingsService.EditorDefaultSearchEngine = (SearchEngine)result; + } + + private static void SetEditorCustomMadeSearchUrl(object value) + { + EditorSettingsService.EditorCustomMadeSearchUrl = (string)value; + } + + private static void SetShowStatusBar(object value) + { + EditorSettingsService.ShowStatusBar = (bool)value; + } + + private static void SetIsHighlightMisspelledWordsEnabled(object value) + { + EditorSettingsService.IsHighlightMisspelledWordsEnabled = (bool)value; + } + + private static void SetAlwaysOpenNewWindow(object value) + { + EditorSettingsService.AlwaysOpenNewWindow = (bool)value; + } + + + public static Settings UseWindowsAccentColor = SetUseWindowsAccentColor; + public static Settings AppBackgroundPanelTintOpacity = SetAppBackgroundPanelTintOpacity; + public static Settings AppAccentColor = SetAppAccentColor; + public static Settings CustomAccentColor = SetCustomAccentColor; + public static Settings ThemeMode = SetThemeMode; + + private static void SetUseWindowsAccentColor(object value) + { + ThemeSettingsService.UseWindowsAccentColor = (bool)value; + } + + private static async void SetAppBackgroundPanelTintOpacity(object value) + { + await ThreadUtility.CallOnUIThreadAsync(Dispatcher, () => + { + ThemeSettingsService.AppBackgroundPanelTintOpacity = (double)value; + }); + } + + private static void SetAppAccentColor(object value) + { + ThemeSettingsService.AppAccentColor = ThemeSettingsService.GetColor((string)value); + } + + private static void SetCustomAccentColor(object value) + { + ThemeSettingsService.CustomAccentColor = ThemeSettingsService.GetColor((string)value); + } + + private static void SetThemeMode(object value) + { + Enum.TryParse(typeof(ElementTheme), (string)value, out var result); + ThemeSettingsService.ThemeMode = (ElementTheme)result; + } + } +} diff --git a/src/Notepads/Settings/SettingsKey.cs b/src/Notepads/Settings/SettingsKey.cs index 6ee35742a..121a63427 100644 --- a/src/Notepads/Settings/SettingsKey.cs +++ b/src/Notepads/Settings/SettingsKey.cs @@ -10,7 +10,6 @@ internal static class SettingsKey // Theme related internal static string RequestedThemeStr = "RequestedThemeStr"; - internal static string UseWindowsThemeBool = "UseWindowsThemeBool"; internal static string AppBackgroundTintOpacityDouble = "AppBackgroundTintOpacityDouble"; internal static string AppAccentColorHexStr = "AppAccentColorHexStr"; internal static string CustomAccentColorHexStr = "CustomAccentColorHexStr"; diff --git a/src/Notepads/Strings/en-US/Resources.resw b/src/Notepads/Strings/en-US/Resources.resw index 91afff174..a65a265b2 100644 --- a/src/Notepads/Strings/en-US/Resources.resw +++ b/src/Notepads/Strings/en-US/Resources.resw @@ -438,7 +438,7 @@ App: DragAndDrop UIOverride Caption: "Open with Notepads" display text - This is a shadow window of Notepads. Session snapshot and settings are disabled. + This is a shadow window of Notepads. Session snapshot is disabled. App: ShadowWindowIndicator Description display text. diff --git a/src/Notepads/Views/AdvancedSettingsPage.xaml.cs b/src/Notepads/Views/AdvancedSettingsPage.xaml.cs index 1e1a64322..29ad0fe5d 100644 --- a/src/Notepads/Views/AdvancedSettingsPage.xaml.cs +++ b/src/Notepads/Views/AdvancedSettingsPage.xaml.cs @@ -1,6 +1,7 @@ namespace Notepads.Views { using Notepads.Services; + using Notepads.Settings; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; @@ -60,11 +61,13 @@ private void EnableSessionBackupAndRestoreToggleSwitch_Toggled(object sender, Ro private void ShowStatusBarToggleSwitch_Toggled(object sender, RoutedEventArgs e) { EditorSettingsService.ShowStatusBar = ShowStatusBarToggleSwitch.IsOn; + InteropService.SyncSettings(SettingsKey.EditorShowStatusBarBool, EditorSettingsService.ShowStatusBar); } private void AlwaysOpenNewWindowToggleSwitch_Toggled(object sender, RoutedEventArgs e) { EditorSettingsService.AlwaysOpenNewWindow = AlwaysOpenNewWindowToggleSwitch.IsOn; + InteropService.SyncSettings(SettingsKey.AlwaysOpenNewWindowBool, EditorSettingsService.AlwaysOpenNewWindow); } } } \ No newline at end of file diff --git a/src/Notepads/Views/NotepadsMainPage.MainMenu.cs b/src/Notepads/Views/NotepadsMainPage.MainMenu.cs index e01ca1456..45c2d0842 100644 --- a/src/Notepads/Views/NotepadsMainPage.MainMenu.cs +++ b/src/Notepads/Views/NotepadsMainPage.MainMenu.cs @@ -34,8 +34,7 @@ private void InitializeMainMenu() if (!App.IsFirstInstance) { - MainMenuButton.Foreground = new SolidColorBrush(ThemeSettingsService.AppAccentColor); - MenuSettingsButton.IsEnabled = false; + MainMenuButton.Foreground = (SolidColorBrush)Application.Current.Resources["SystemControlForegroundAccentBrush"]; } if (App.IsGameBarWidget) diff --git a/src/Notepads/Views/NotepadsMainPage.xaml.cs b/src/Notepads/Views/NotepadsMainPage.xaml.cs index b54c28a82..59ad7cfe9 100644 --- a/src/Notepads/Views/NotepadsMainPage.xaml.cs +++ b/src/Notepads/Views/NotepadsMainPage.xaml.cs @@ -26,6 +26,7 @@ using Windows.UI.Xaml.Navigation; using Microsoft.AppCenter.Analytics; using Windows.Graphics.Printing; + using Windows.ApplicationModel; public sealed partial class NotepadsMainPage : Page { @@ -273,6 +274,10 @@ private async void Sets_Loaded(object sender, RoutedEventArgs e) Window.Current.CoreWindow.Activated -= CoreWindow_Activated; Window.Current.CoreWindow.Activated += CoreWindow_Activated; } + + InteropService.Initialize(); + InteropService.HideSettingsPane += HideSettingsPane_OnSettingsChanged; + SettingsDelegate.Dispatcher = Dispatcher; } private async void App_EnteredBackground(object sender, Windows.ApplicationModel.EnteredBackgroundEventArgs e) @@ -284,6 +289,9 @@ private async void App_EnteredBackground(object sender, Windows.ApplicationModel await SessionManager.SaveSessionAsync(); } + if (InteropService.ISAppExited) + InteropService.CloseConnectionOnExit(); + deferral.Complete(); } @@ -348,12 +356,14 @@ private async void MainPage_CloseRequested(object sender, Windows.UI.Core.Previe { // Save session before app exit await SessionManager.SaveSessionAsync(() => { SessionManager.IsBackupEnabled = false; }); + InteropService.ISAppExited = true; deferral.Complete(); return; } if (!NotepadsCore.HaveUnsavedTextEditor()) { + InteropService.ISAppExited = true; deferral.Complete(); return; } @@ -383,10 +393,12 @@ private async void MainPage_CloseRequested(object sender, Windows.UI.Core.Previe await BuildOpenRecentButtonSubItems(); } + InteropService.ISAppExited = true; deferral.Complete(); }, discardAndExitAction: () => { + InteropService.ISAppExited = true; deferral.Complete(); }, cancelAction: () => @@ -435,6 +447,14 @@ private static void UpdateApplicationTitle(ITextEditor activeTextEditor) } } + private async void HideSettingsPane_OnSettingsChanged(object sender, bool hideArgs) + { + await ThreadUtility.CallOnUIThreadAsync(Dispatcher, () => + { + RootSplitView.IsPaneOpen = !hideArgs; + }); + } + #endregion #region NotepadsCore Events diff --git a/src/Notepads/Views/PersonalizationSettingsPage.xaml.cs b/src/Notepads/Views/PersonalizationSettingsPage.xaml.cs index b9978856c..dd1b46057 100644 --- a/src/Notepads/Views/PersonalizationSettingsPage.xaml.cs +++ b/src/Notepads/Views/PersonalizationSettingsPage.xaml.cs @@ -1,6 +1,7 @@ namespace Notepads.Views { using Notepads.Services; + using Notepads.Settings; using Notepads.Utilities; using Windows.System.Power; using Windows.UI; @@ -18,21 +19,17 @@ public PersonalizationSettingsPage() { InitializeComponent(); - if (ThemeSettingsService.UseWindowsTheme) + switch (ThemeSettingsService.ThemeMode) { - ThemeModeDefaultButton.IsChecked = true; - } - else - { - switch (ThemeSettingsService.ThemeMode) - { - case ElementTheme.Light: - ThemeModeLightButton.IsChecked = true; - break; - case ElementTheme.Dark: - ThemeModeDarkButton.IsChecked = true; - break; - } + case ElementTheme.Default: + ThemeModeDefaultButton.IsChecked = true; + break; + case ElementTheme.Light: + ThemeModeLightButton.IsChecked = true; + break; + case ElementTheme.Dark: + ThemeModeDarkButton.IsChecked = true; + break; } AccentColorToggle.IsOn = ThemeSettingsService.UseWindowsAccentColor; @@ -124,17 +121,16 @@ private void ThemeRadioButton_OnChecked(object sender, RoutedEventArgs e) switch (radioButton.Tag) { case "Light": - ThemeSettingsService.UseWindowsTheme = false; - ThemeSettingsService.SetTheme(ElementTheme.Light); + ThemeSettingsService.ThemeMode = ElementTheme.Light; break; case "Dark": - ThemeSettingsService.UseWindowsTheme = false; - ThemeSettingsService.SetTheme(ElementTheme.Dark); + ThemeSettingsService.ThemeMode = ElementTheme.Dark; break; case "Default": - ThemeSettingsService.UseWindowsTheme = true; + ThemeSettingsService.ThemeMode = ElementTheme.Default; break; } + InteropService.SyncSettings(SettingsKey.RequestedThemeStr, ThemeSettingsService.ThemeMode); } } @@ -143,13 +139,19 @@ private void AccentColorPicker_OnColorChanged(ColorPicker sender, ColorChangedEv if (AccentColorPicker.IsEnabled) { ThemeSettingsService.AppAccentColor = args.NewColor; - if (!AccentColorToggle.IsOn) ThemeSettingsService.CustomAccentColor = args.NewColor; + if (!AccentColorToggle.IsOn) + { + ThemeSettingsService.CustomAccentColor = args.NewColor; + InteropService.SyncSettings(SettingsKey.CustomAccentColorHexStr, ThemeSettingsService.CustomAccentColor); + } + InteropService.SyncSettings(SettingsKey.AppAccentColorHexStr, ThemeSettingsService.AppAccentColor); } } private void BackgroundTintOpacitySlider_OnValueChanged(object sender, RangeBaseValueChangedEventArgs e) { ThemeSettingsService.AppBackgroundPanelTintOpacity = e.NewValue / 100; + InteropService.SyncSettings(SettingsKey.AppBackgroundTintOpacityDouble, ThemeSettingsService.AppBackgroundPanelTintOpacity); } private void WindowsAccentColorToggle_OnToggled(object sender, RoutedEventArgs e) @@ -157,6 +159,7 @@ private void WindowsAccentColorToggle_OnToggled(object sender, RoutedEventArgs e AccentColorPicker.IsEnabled = !AccentColorToggle.IsOn; ThemeSettingsService.UseWindowsAccentColor = AccentColorToggle.IsOn; AccentColorPicker.Color = AccentColorToggle.IsOn ? ThemeSettingsService.AppAccentColor : ThemeSettingsService.CustomAccentColor; + InteropService.SyncSettings(SettingsKey.UseWindowsAccentColorBool, ThemeSettingsService.UseWindowsAccentColor); } } } \ No newline at end of file diff --git a/src/Notepads/Views/TextAndEditorSettingsPage.xaml.cs b/src/Notepads/Views/TextAndEditorSettingsPage.xaml.cs index f8b684f34..411ee94d5 100644 --- a/src/Notepads/Views/TextAndEditorSettingsPage.xaml.cs +++ b/src/Notepads/Views/TextAndEditorSettingsPage.xaml.cs @@ -10,6 +10,7 @@ using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Microsoft.AppCenter.Analytics; + using Notepads.Settings; public sealed partial class TextAndEditorSettingsPage : Page { @@ -250,8 +251,11 @@ private void SearchEngineRadioButton_Checked(object sender, RoutedEventArgs e) CustomSearchUrl.Select(CustomSearchUrl.Text.Length, 0); CustomUrlErrorReport.Visibility = IsValidUrl(CustomSearchUrl.Text) ? Visibility.Collapsed : Visibility.Visible; EditorSettingsService.EditorCustomMadeSearchUrl = CustomSearchUrl.Text; + InteropService.SyncSettings(SettingsKey.EditorCustomMadeSearchUrlStr, CustomSearchUrl.Text); break; } + + InteropService.SyncSettings(SettingsKey.EditorDefaultSearchEngineStr, EditorSettingsService.EditorDefaultSearchEngine); } private void TabBehaviorRadioButton_Checked(object sender, RoutedEventArgs e) @@ -273,6 +277,8 @@ private void TabBehaviorRadioButton_Checked(object sender, RoutedEventArgs e) EditorSettingsService.EditorDefaultTabIndents = 8; break; } + + InteropService.SyncSettings(SettingsKey.EditorDefaultTabIndentsInt, EditorSettingsService.EditorDefaultTabIndents); } private void EncodingRadioButton_Checked(object sender, RoutedEventArgs e) @@ -294,6 +300,8 @@ private void EncodingRadioButton_Checked(object sender, RoutedEventArgs e) EditorSettingsService.EditorDefaultEncoding = new UnicodeEncoding(true, true); break; } + + InteropService.SyncSettings(SettingsKey.EditorDefaultEncodingCodePageInt, EditorSettingsService.EditorDefaultEncoding); } private void DecodingRadioButton_Checked(object sender, RoutedEventArgs e) @@ -323,6 +331,8 @@ private void DecodingRadioButton_Checked(object sender, RoutedEventArgs e) } break; } + + InteropService.SyncSettings(SettingsKey.EditorDefaultDecodingCodePageInt, EditorSettingsService.EditorDefaultDecoding); } private void LineEndingRadioButton_OnChecked(object sender, RoutedEventArgs e) @@ -341,31 +351,38 @@ private void LineEndingRadioButton_OnChecked(object sender, RoutedEventArgs e) EditorSettingsService.EditorDefaultLineEnding = LineEnding.Lf; break; } + + InteropService.SyncSettings(SettingsKey.EditorDefaultLineEndingStr, EditorSettingsService.EditorDefaultLineEnding); } private void FontFamilyPicker_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { EditorSettingsService.EditorFontFamily = (string)e.AddedItems.First(); + InteropService.SyncSettings(SettingsKey.EditorFontFamilyStr, EditorSettingsService.EditorFontFamily); } private void FontSizePicker_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { EditorSettingsService.EditorFontSize = (int)e.AddedItems.First(); + InteropService.SyncSettings(SettingsKey.EditorFontSizeInt, EditorSettingsService.EditorFontSize); } private void TextWrappingToggle_OnToggled(object sender, RoutedEventArgs e) { EditorSettingsService.EditorDefaultTextWrapping = TextWrappingToggle.IsOn ? TextWrapping.Wrap : TextWrapping.NoWrap; + InteropService.SyncSettings(SettingsKey.EditorDefaultTextWrappingStr, EditorSettingsService.EditorDefaultTextWrapping); } private void HighlightMisspelledWordsToggle_OnToggled(object sender, RoutedEventArgs e) { EditorSettingsService.IsHighlightMisspelledWordsEnabled = HighlightMisspelledWordsToggle.IsOn; + InteropService.SyncSettings(SettingsKey.EditorHighlightMisspelledWordsBool, EditorSettingsService.IsHighlightMisspelledWordsEnabled); } private void LineHighlighterToggle_OnToggled(object sender, RoutedEventArgs e) { EditorSettingsService.IsLineHighlighterEnabled = LineHighlighterToggle.IsOn; + InteropService.SyncSettings(SettingsKey.EditorDefaultLineHighlighterViewStateBool, EditorSettingsService.IsLineHighlighterEnabled); } private void CustomSearchUrl_TextChanged(object sender, TextChangedEventArgs e) @@ -380,10 +397,13 @@ private void CustomSearchUrl_LostFocus(object sender, RoutedEventArgs e) (IsValidUrl(CustomSearchUrl.Text) && (bool)CustomSearchUrlRadioButton.IsChecked)) { EditorSettingsService.EditorDefaultSearchEngine = SearchEngine.Custom; + InteropService.SyncSettings(SettingsKey.EditorCustomMadeSearchUrlStr, CustomSearchUrl.Text); + InteropService.SyncSettings(SettingsKey.EditorDefaultSearchEngineStr, EditorSettingsService.EditorDefaultSearchEngine); } else if (!IsValidUrl(CustomSearchUrl.Text) && EditorSettingsService.EditorDefaultSearchEngine == SearchEngine.Custom) { EditorSettingsService.EditorDefaultSearchEngine = SearchEngine.Bing; + InteropService.SyncSettings(SettingsKey.EditorDefaultSearchEngineStr, EditorSettingsService.EditorDefaultSearchEngine); } CustomUrlErrorReport.Visibility = IsValidUrl(CustomSearchUrl.Text) ? Visibility.Collapsed : Visibility.Visible; From 73bc69965dda654add4fff33d0ad8ea8b6f7cecf Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Mon, 20 Apr 2020 19:27:31 +0530 Subject: [PATCH 002/181] Codefactor changes. --- src/Notepads/Settings/SettingsDelegate.cs | 3 +-- src/Notepads/Views/NotepadsMainPage.xaml.cs | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/Notepads/Settings/SettingsDelegate.cs b/src/Notepads/Settings/SettingsDelegate.cs index a25d57d40..83e8100e6 100644 --- a/src/Notepads/Settings/SettingsDelegate.cs +++ b/src/Notepads/Settings/SettingsDelegate.cs @@ -99,7 +99,6 @@ private static void SetAlwaysOpenNewWindow(object value) EditorSettingsService.AlwaysOpenNewWindow = (bool)value; } - public static Settings UseWindowsAccentColor = SetUseWindowsAccentColor; public static Settings AppBackgroundPanelTintOpacity = SetAppBackgroundPanelTintOpacity; public static Settings AppAccentColor = SetAppAccentColor; @@ -113,7 +112,7 @@ private static void SetUseWindowsAccentColor(object value) private static async void SetAppBackgroundPanelTintOpacity(object value) { - await ThreadUtility.CallOnUIThreadAsync(Dispatcher, () => + await Dispatcher.RunAsync(CoreDispatcherPriority.High, () => { ThemeSettingsService.AppBackgroundPanelTintOpacity = (double)value; }); diff --git a/src/Notepads/Views/NotepadsMainPage.xaml.cs b/src/Notepads/Views/NotepadsMainPage.xaml.cs index 0a1bc5168..dab64cdf6 100644 --- a/src/Notepads/Views/NotepadsMainPage.xaml.cs +++ b/src/Notepads/Views/NotepadsMainPage.xaml.cs @@ -449,7 +449,7 @@ private static void UpdateApplicationTitle(ITextEditor activeTextEditor) private async void HideSettingsPane_OnSettingsChanged(object sender, bool hideArgs) { - await ThreadUtility.CallOnUIThreadAsync(Dispatcher, () => + await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () => { RootSplitView.IsPaneOpen = !hideArgs; }); From c50834a70b2db041f1ff9b6e4b64a0e6d8da7116 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Mon, 20 Apr 2020 19:53:34 +0530 Subject: [PATCH 003/181] Made security improvement. --- .../InteropConnectionService.cs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/Notepads.Services/InteropConnectionService.cs b/src/Notepads.Services/InteropConnectionService.cs index 2b09acd07..7a9f924ac 100644 --- a/src/Notepads.Services/InteropConnectionService.cs +++ b/src/Notepads.Services/InteropConnectionService.cs @@ -18,14 +18,21 @@ public void Run(IBackgroundTaskInstance taskInstance) // Get a deferral so that the service isn't terminated. this.backgroundTaskDeferral = taskInstance.GetDeferral(); - // Associate a cancellation handler with the background task. - taskInstance.Canceled += OnTaskCanceled; - // Retrieve the app service connection and set up a listener for incoming app service requests. var details = taskInstance.TriggerDetails as AppServiceTriggerDetails; - appServiceConnection = details.AppServiceConnection; - appServiceConnections.Add(appServiceConnection); - appServiceConnection.RequestReceived += OnRequestReceived; + if(details.CallerPackageFamilyName == Package.Current.Id.FamilyName) + { + appServiceConnection = details.AppServiceConnection; + appServiceConnections.Add(appServiceConnection); + appServiceConnection.RequestReceived += OnRequestReceived; + + // Associate a cancellation handler with the background task. + taskInstance.Canceled += OnTaskCanceled; + } + else + { + this.backgroundTaskDeferral.Complete(); + } } private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) From a9f16e83f0f9ba993bade63b44bc6e12b1b2670b Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Mon, 20 Apr 2020 20:21:08 +0530 Subject: [PATCH 004/181] Small refactoring. --- src/Notepads.Services/InteropConnectionService.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Notepads.Services/InteropConnectionService.cs b/src/Notepads.Services/InteropConnectionService.cs index 7a9f924ac..96b1f57f8 100644 --- a/src/Notepads.Services/InteropConnectionService.cs +++ b/src/Notepads.Services/InteropConnectionService.cs @@ -5,7 +5,6 @@ using Windows.ApplicationModel; using Windows.ApplicationModel.AppService; using Windows.ApplicationModel.Background; - using Windows.Foundation.Collections; public sealed class InteropConnectionService : IBackgroundTask { From ccd750057b0c5643e860390fef104cc3912c0e2e Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Mon, 20 Apr 2020 22:59:35 +0530 Subject: [PATCH 005/181] Made some enhancements. --- src/Notepads/Services/EditorSettingsService.cs | 14 ++++++++++++++ src/Notepads/Services/InteropService.cs | 6 ------ src/Notepads/Services/ThemeSettingsService.cs | 8 ++++++++ src/Notepads/Views/NotepadsMainPage.xaml.cs | 17 ++++++++++------- 4 files changed, 32 insertions(+), 13 deletions(-) diff --git a/src/Notepads/Services/EditorSettingsService.cs b/src/Notepads/Services/EditorSettingsService.cs index 7e66f0114..4a6374a87 100644 --- a/src/Notepads/Services/EditorSettingsService.cs +++ b/src/Notepads/Services/EditorSettingsService.cs @@ -468,5 +468,19 @@ private static void InitializeAppOpeningPreferencesSettings() _alwaysOpenNewWindow = false; } } + + public static void UpdateAllSettings() + { + Initialize(); + OnStatusBarVisibilityChanged?.Invoke(null, _showStatusBar); + OnFontFamilyChanged?.Invoke(null, _editorFontFamily); + OnFontSizeChanged?.Invoke(null, _editorFontSize); + OnDefaultTextWrappingChanged?.Invoke(null, _editorDefaultTextWrapping); + OnDefaultLineHighlighterViewStateChanged?.Invoke(null, _isLineHighlighterEnabled); + OnHighlightMisspelledWordsChanged?.Invoke(null, _isHighlightMisspelledWordsEnabled); + OnDefaultLineEndingChanged?.Invoke(null, _editorDefaultLineEnding); + OnDefaultEncodingChanged?.Invoke(null, _editorDefaultEncoding); + OnDefaultTabIndentsChanged?.Invoke(null, _editorDefaultTabIndents); + } } } \ No newline at end of file diff --git a/src/Notepads/Services/InteropService.cs b/src/Notepads/Services/InteropService.cs index f3a122bea..bc7ca1162 100644 --- a/src/Notepads/Services/InteropService.cs +++ b/src/Notepads/Services/InteropService.cs @@ -12,7 +12,6 @@ public static class InteropService { public static EventHandler HideSettingsPane; public static bool EnableSettingsLogging = true; - public static bool ISAppExited = false; public static AppServiceConnection InteropServiceConnection = null; @@ -91,10 +90,5 @@ public static async void SyncSettings(string settingsKey, object value) } await InteropServiceConnection.SendMessageAsync(message); } - - public static void CloseConnectionOnExit() - { - InteropServiceConnection.Dispose(); - } } } diff --git a/src/Notepads/Services/ThemeSettingsService.cs b/src/Notepads/Services/ThemeSettingsService.cs index cc546e348..cd2772ea5 100644 --- a/src/Notepads/Services/ThemeSettingsService.cs +++ b/src/Notepads/Services/ThemeSettingsService.cs @@ -355,5 +355,13 @@ public static Color GetColor(string hex) byte b = (byte)(Convert.ToUInt32(hex.Substring(6, 2), 16)); return Windows.UI.Color.FromArgb(a, r, g, b); } + + public static void UpdateAllSettings() + { + Initialize(); + OnThemeChanged?.Invoke(null, _themeMode); + OnBackgroundChanged?.Invoke(null, GetAppBackgroundBrush(ThemeMode)); + OnAccentColorChanged?.Invoke(null, _appAccentColor); + } } } \ No newline at end of file diff --git a/src/Notepads/Views/NotepadsMainPage.xaml.cs b/src/Notepads/Views/NotepadsMainPage.xaml.cs index dab64cdf6..316f7e942 100644 --- a/src/Notepads/Views/NotepadsMainPage.xaml.cs +++ b/src/Notepads/Views/NotepadsMainPage.xaml.cs @@ -269,7 +269,9 @@ private async void Sets_Loaded(object sender, RoutedEventArgs e) // To work around this do not use the EnteredBackground event when running as a widget. // Microsoft is tracking this issue as VSO#25735260 Application.Current.EnteredBackground -= App_EnteredBackground; + Application.Current.LeavingBackground -= App_LeavingBackground; Application.Current.EnteredBackground += App_EnteredBackground; + Application.Current.LeavingBackground += App_LeavingBackground; Window.Current.CoreWindow.Activated -= CoreWindow_Activated; Window.Current.CoreWindow.Activated += CoreWindow_Activated; @@ -289,12 +291,17 @@ private async void App_EnteredBackground(object sender, Windows.ApplicationModel await SessionManager.SaveSessionAsync(); } - if (InteropService.ISAppExited) - InteropService.CloseConnectionOnExit(); - + InteropService.InteropServiceConnection.Dispose(); deferral.Complete(); } + private void App_LeavingBackground(object sender, LeavingBackgroundEventArgs e) + { + ThemeSettingsService.UpdateAllSettings(); + EditorSettingsService.UpdateAllSettings(); + InteropService.Initialize(); + } + public void ExecuteProtocol(Uri uri) { LoggingService.LogInfo($"[{nameof(NotepadsMainPage)}] Executing protocol: {uri}", consoleOnly: true); @@ -356,14 +363,12 @@ private async void MainPage_CloseRequested(object sender, Windows.UI.Core.Previe { // Save session before app exit await SessionManager.SaveSessionAsync(() => { SessionManager.IsBackupEnabled = false; }); - InteropService.ISAppExited = true; deferral.Complete(); return; } if (!NotepadsCore.HaveUnsavedTextEditor()) { - InteropService.ISAppExited = true; deferral.Complete(); return; } @@ -393,12 +398,10 @@ private async void MainPage_CloseRequested(object sender, Windows.UI.Core.Previe await BuildOpenRecentButtonSubItems(); } - InteropService.ISAppExited = true; deferral.Complete(); }, discardAndExitAction: () => { - InteropService.ISAppExited = true; deferral.Complete(); }, cancelAction: () => From a527e8c4047192deba8c9b154b9eec07ddba6ec0 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Wed, 22 Apr 2020 20:06:14 +0530 Subject: [PATCH 006/181] Added syncing of recent list accross all windows. --- .../InteropConnectionService.cs | 29 ++++++++++++-- src/Notepads/Services/InteropService.cs | 38 +++++++++++++++---- .../Views/NotepadsMainPage.MainMenu.cs | 4 +- src/Notepads/Views/NotepadsMainPage.xaml.cs | 7 +++- 4 files changed, 66 insertions(+), 12 deletions(-) diff --git a/src/Notepads.Services/InteropConnectionService.cs b/src/Notepads.Services/InteropConnectionService.cs index 96b1f57f8..18a121aee 100644 --- a/src/Notepads.Services/InteropConnectionService.cs +++ b/src/Notepads.Services/InteropConnectionService.cs @@ -6,12 +6,20 @@ using Windows.ApplicationModel.AppService; using Windows.ApplicationModel.Background; + public enum CommandArgs + { + SyncSettings, + SyncRecentList + } + public sealed class InteropConnectionService : IBackgroundTask { private BackgroundTaskDeferral backgroundTaskDeferral; private AppServiceConnection appServiceConnection; private static IList appServiceConnections = new List(); + private static readonly string _commandLabel = "Command"; + public void Run(IBackgroundTaskInstance taskInstance) { // Get a deferral so that the service isn't terminated. @@ -36,11 +44,26 @@ public void Run(IBackgroundTaskInstance taskInstance) private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { - foreach(var serviceConnection in appServiceConnections) + var messagedeferral = args.GetDeferral(); + var message = args.Request.Message; + if (!message.ContainsKey(_commandLabel) || !Enum.TryParse(typeof(CommandArgs), (string)message[_commandLabel], out var result)) return; + var command = (CommandArgs)result; + switch (command) { - if (serviceConnection != appServiceConnection) - await serviceConnection.SendMessageAsync(args.Request.Message); + case CommandArgs.SyncSettings: + foreach (var serviceConnection in appServiceConnections) + { + if (serviceConnection != appServiceConnection) await serviceConnection.SendMessageAsync(args.Request.Message); + } + break; + case CommandArgs.SyncRecentList: + foreach (var serviceConnection in appServiceConnections) + { + if (serviceConnection != appServiceConnection) await serviceConnection.SendMessageAsync(args.Request.Message); + } + break; } + messagedeferral.Complete(); } private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) diff --git a/src/Notepads/Services/InteropService.cs b/src/Notepads/Services/InteropService.cs index bc7ca1162..3142486fd 100644 --- a/src/Notepads/Services/InteropService.cs +++ b/src/Notepads/Services/InteropService.cs @@ -11,10 +11,12 @@ public static class InteropService { public static EventHandler HideSettingsPane; + public static EventHandler UpdateRecentList; public static bool EnableSettingsLogging = true; public static AppServiceConnection InteropServiceConnection = null; + private static readonly string _commandLabel = "Command"; private static readonly string _appIdLabel = "Instance"; private static readonly string _settingsKeyLabel = "Settings"; private static readonly string _valueLabel = "Value"; @@ -59,14 +61,24 @@ public static async void Initialize() private static void InteropServiceConnection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { var message = args.Request.Message; - if (message.ContainsKey(_appIdLabel) && message[_appIdLabel] is Guid appID && appID != App.Id) + if (!message.ContainsKey(_commandLabel) || !Enum.TryParse(typeof(CommandArgs), (string)message[_commandLabel], out var result)) return; + var command = (CommandArgs)result; + switch(command) { - EnableSettingsLogging = false; - HideSettingsPane?.Invoke(null, true); - var settingsKey = message[_settingsKeyLabel] as string; - var value = message[_valueLabel] as object; - SettingsManager[settingsKey](value); - EnableSettingsLogging = true; + case CommandArgs.SyncSettings: + if (message.ContainsKey(_appIdLabel) && message[_appIdLabel] is Guid appID && appID != App.Id) + { + EnableSettingsLogging = false; + HideSettingsPane?.Invoke(null, true); + var settingsKey = message[_settingsKeyLabel] as string; + var value = message[_valueLabel] as object; + SettingsManager[settingsKey](value); + EnableSettingsLogging = true; + } + break; + case CommandArgs.SyncRecentList: + UpdateRecentList?.Invoke(null, false); + break; } } @@ -77,7 +89,10 @@ private static void InteropServiceConnection_ServiceClosed(AppServiceConnection public static async void SyncSettings(string settingsKey, object value) { + if (InteropServiceConnection == null) return; + var message = new ValueSet(); + message.Add(_commandLabel, CommandArgs.SyncSettings.ToString()); message.Add(_appIdLabel, App.Id); message.Add(_settingsKeyLabel, settingsKey); try @@ -90,5 +105,14 @@ public static async void SyncSettings(string settingsKey, object value) } await InteropServiceConnection.SendMessageAsync(message); } + + public static async void SyncRecentList() + { + if (InteropServiceConnection == null) return; + + var message = new ValueSet(); + message.Add(_commandLabel, CommandArgs.SyncRecentList.ToString()); + await InteropServiceConnection.SendMessageAsync(message); + } } } diff --git a/src/Notepads/Views/NotepadsMainPage.MainMenu.cs b/src/Notepads/Views/NotepadsMainPage.MainMenu.cs index 45c2d0842..cfd8b4c87 100644 --- a/src/Notepads/Views/NotepadsMainPage.MainMenu.cs +++ b/src/Notepads/Views/NotepadsMainPage.MainMenu.cs @@ -105,7 +105,7 @@ private void MainMenuButtonFlyout_Opening(object sender, object e) MenuSaveAllButton.IsEnabled = NotepadsCore.HaveUnsavedTextEditor(); } - private async Task BuildOpenRecentButtonSubItems() + private async Task BuildOpenRecentButtonSubItems(bool updateForOtherInstane = true) { var openRecentSubItem = new MenuFlyoutSubItem { @@ -167,6 +167,8 @@ private async Task BuildOpenRecentButtonSubItems() var indexToInsert = MainMenuButtonFlyout.Items.IndexOf(MenuOpenFileButton) + 1; MainMenuButtonFlyout.Items.Insert(indexToInsert, openRecentSubItem); } + + if (updateForOtherInstane) InteropService.SyncRecentList(); } } } \ No newline at end of file diff --git a/src/Notepads/Views/NotepadsMainPage.xaml.cs b/src/Notepads/Views/NotepadsMainPage.xaml.cs index f10a540db..15d378ce5 100644 --- a/src/Notepads/Views/NotepadsMainPage.xaml.cs +++ b/src/Notepads/Views/NotepadsMainPage.xaml.cs @@ -280,6 +280,10 @@ private async void Sets_Loaded(object sender, RoutedEventArgs e) InteropService.Initialize(); InteropService.HideSettingsPane += HideSettingsPane_OnSettingsChanged; + InteropService.UpdateRecentList += async (_, updateForOtherInstaneArgs) => await Dispatcher.CallOnUIThreadAsync(async () => + { + await BuildOpenRecentButtonSubItems(updateForOtherInstaneArgs); + }); SettingsDelegate.Dispatcher = Dispatcher; } @@ -296,10 +300,11 @@ private async void App_EnteredBackground(object sender, Windows.ApplicationModel deferral.Complete(); } - private void App_LeavingBackground(object sender, LeavingBackgroundEventArgs e) + private async void App_LeavingBackground(object sender, LeavingBackgroundEventArgs e) { ThemeSettingsService.UpdateAllSettings(); EditorSettingsService.UpdateAllSettings(); + await BuildOpenRecentButtonSubItems(false); InteropService.Initialize(); } From d19f6e78d2eca8f734495fa175f00cd664d8264e Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sun, 3 May 2020 02:22:07 +0530 Subject: [PATCH 007/181] Improved syncing perfermance. --- .../InteropConnectionService.cs | 10 +++++----- src/Notepads/Services/InteropService.cs | 16 ++++++---------- 2 files changed, 11 insertions(+), 15 deletions(-) diff --git a/src/Notepads.Services/InteropConnectionService.cs b/src/Notepads.Services/InteropConnectionService.cs index 96b1f57f8..c0112aa6b 100644 --- a/src/Notepads.Services/InteropConnectionService.cs +++ b/src/Notepads.Services/InteropConnectionService.cs @@ -2,6 +2,7 @@ { using System; using System.Collections.Generic; + using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.AppService; using Windows.ApplicationModel.Background; @@ -34,13 +35,12 @@ public void Run(IBackgroundTaskInstance taskInstance) } } - private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) + private void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { - foreach(var serviceConnection in appServiceConnections) + Parallel.ForEach(appServiceConnections, async (serviceConnection) => { - if (serviceConnection != appServiceConnection) - await serviceConnection.SendMessageAsync(args.Request.Message); - } + if (serviceConnection != appServiceConnection) await serviceConnection.SendMessageAsync(args.Request.Message); + }); } private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) diff --git a/src/Notepads/Services/InteropService.cs b/src/Notepads/Services/InteropService.cs index bc7ca1162..a4a672dc6 100644 --- a/src/Notepads/Services/InteropService.cs +++ b/src/Notepads/Services/InteropService.cs @@ -59,15 +59,12 @@ public static async void Initialize() private static void InteropServiceConnection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { var message = args.Request.Message; - if (message.ContainsKey(_appIdLabel) && message[_appIdLabel] is Guid appID && appID != App.Id) - { - EnableSettingsLogging = false; - HideSettingsPane?.Invoke(null, true); - var settingsKey = message[_settingsKeyLabel] as string; - var value = message[_valueLabel] as object; - SettingsManager[settingsKey](value); - EnableSettingsLogging = true; - } + EnableSettingsLogging = false; + HideSettingsPane?.Invoke(null, true); + var settingsKey = message[_settingsKeyLabel] as string; + var value = message[_valueLabel] as object; + SettingsManager[settingsKey](value); + EnableSettingsLogging = true; } private static void InteropServiceConnection_ServiceClosed(AppServiceConnection sender, AppServiceClosedEventArgs args) @@ -78,7 +75,6 @@ private static void InteropServiceConnection_ServiceClosed(AppServiceConnection public static async void SyncSettings(string settingsKey, object value) { var message = new ValueSet(); - message.Add(_appIdLabel, App.Id); message.Add(_settingsKeyLabel, settingsKey); try { From 95e607fe11f04cbb9c21deff18bd41de96aaf96a Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sun, 3 May 2020 02:28:03 +0530 Subject: [PATCH 008/181] Improved perfermance. --- .../InteropConnectionService.cs | 11 ++++++----- src/Notepads/Services/InteropService.cs | 16 ++++++---------- 2 files changed, 12 insertions(+), 15 deletions(-) diff --git a/src/Notepads.Services/InteropConnectionService.cs b/src/Notepads.Services/InteropConnectionService.cs index 18a121aee..be64ebabd 100644 --- a/src/Notepads.Services/InteropConnectionService.cs +++ b/src/Notepads.Services/InteropConnectionService.cs @@ -2,6 +2,7 @@ { using System; using System.Collections.Generic; + using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.AppService; using Windows.ApplicationModel.Background; @@ -42,7 +43,7 @@ public void Run(IBackgroundTaskInstance taskInstance) } } - private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) + private void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { var messagedeferral = args.GetDeferral(); var message = args.Request.Message; @@ -51,16 +52,16 @@ private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequ switch (command) { case CommandArgs.SyncSettings: - foreach (var serviceConnection in appServiceConnections) + Parallel.ForEach(appServiceConnections, async (serviceConnection) => { if (serviceConnection != appServiceConnection) await serviceConnection.SendMessageAsync(args.Request.Message); - } + }); break; case CommandArgs.SyncRecentList: - foreach (var serviceConnection in appServiceConnections) + Parallel.ForEach(appServiceConnections, async (serviceConnection) => { if (serviceConnection != appServiceConnection) await serviceConnection.SendMessageAsync(args.Request.Message); - } + }); break; } messagedeferral.Complete(); diff --git a/src/Notepads/Services/InteropService.cs b/src/Notepads/Services/InteropService.cs index 3142486fd..121f00937 100644 --- a/src/Notepads/Services/InteropService.cs +++ b/src/Notepads/Services/InteropService.cs @@ -66,15 +66,12 @@ private static void InteropServiceConnection_RequestReceived(AppServiceConnectio switch(command) { case CommandArgs.SyncSettings: - if (message.ContainsKey(_appIdLabel) && message[_appIdLabel] is Guid appID && appID != App.Id) - { - EnableSettingsLogging = false; - HideSettingsPane?.Invoke(null, true); - var settingsKey = message[_settingsKeyLabel] as string; - var value = message[_valueLabel] as object; - SettingsManager[settingsKey](value); - EnableSettingsLogging = true; - } + EnableSettingsLogging = false; + HideSettingsPane?.Invoke(null, true); + var settingsKey = message[_settingsKeyLabel] as string; + var value = message[_valueLabel] as object; + SettingsManager[settingsKey](value); + EnableSettingsLogging = true; break; case CommandArgs.SyncRecentList: UpdateRecentList?.Invoke(null, false); @@ -93,7 +90,6 @@ public static async void SyncSettings(string settingsKey, object value) var message = new ValueSet(); message.Add(_commandLabel, CommandArgs.SyncSettings.ToString()); - message.Add(_appIdLabel, App.Id); message.Add(_settingsKeyLabel, settingsKey); try { From 1ef07ac023ac0d9ddb35d9d8803d7e32fd6e7219 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 7 May 2020 10:44:33 +0530 Subject: [PATCH 009/181] Implemented desktop extension to save file anywhere. --- src/Notepads.DesktopExtension/App.config | 27 + .../ExtensionService.cs | 29 + .../IExtensionService.cs | 17 + .../Notepads.DesktopExtension.csproj | 86 +++ src/Notepads.DesktopExtension/Program.cs | 152 +++++ .../Properties/AssemblyInfo.cs | 36 ++ .../Properties/Resources.Designer.cs | 71 +++ .../Properties/Resources.resx | 117 ++++ .../Properties/Settings.Designer.cs | 30 + .../Properties/Settings.settings | 7 + src/Notepads.Package/Notepads.Package.wapproj | 70 +++ src/Notepads.Package/Package.appxmanifest | 560 ++++++++++++++++++ .../InteropConnectionService.cs | 64 +- .../Notepads.Services.csproj | 3 + src/Notepads.sln | 55 +- .../ExtensionService/ExtensionService.disco | 4 + .../ExtensionService/ExtensionService.wsdl | 76 +++ .../ExtensionService/ExtensionService.xsd | 43 ++ .../ExtensionService/ExtensionService1.xsd | 42 ++ .../ExtensionService/Reference.cs | 126 ++++ .../ExtensionService/Reference.svcmap | 36 ++ .../ExtensionService/configuration.svcinfo | 6 + .../ExtensionService/configuration91.svcinfo | 5 + .../Controls/Dialog/NotepadsDialogFactory.cs | 15 + src/Notepads/Notepads.csproj | 28 + src/Notepads/Package.appxmanifest | 485 --------------- src/Notepads/Program.cs | 7 + .../ServiceReferences.Designer.ClientConfig | 4 + src/Notepads/Services/InteropService.cs | 99 +++- src/Notepads/Strings/en-US/Resources.resw | 12 + src/Notepads/Utilities/FileSystemUtility.cs | 13 + src/Notepads/Views/NotepadsMainPage.IO.cs | 46 +- .../Views/NotepadsMainPage.MainMenu.cs | 4 +- src/Notepads/Views/NotepadsMainPage.xaml.cs | 7 +- 34 files changed, 1876 insertions(+), 506 deletions(-) create mode 100644 src/Notepads.DesktopExtension/App.config create mode 100644 src/Notepads.DesktopExtension/ExtensionService.cs create mode 100644 src/Notepads.DesktopExtension/IExtensionService.cs create mode 100644 src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj create mode 100644 src/Notepads.DesktopExtension/Program.cs create mode 100644 src/Notepads.DesktopExtension/Properties/AssemblyInfo.cs create mode 100644 src/Notepads.DesktopExtension/Properties/Resources.Designer.cs create mode 100644 src/Notepads.DesktopExtension/Properties/Resources.resx create mode 100644 src/Notepads.DesktopExtension/Properties/Settings.Designer.cs create mode 100644 src/Notepads.DesktopExtension/Properties/Settings.settings create mode 100644 src/Notepads.Package/Notepads.Package.wapproj create mode 100644 src/Notepads.Package/Package.appxmanifest create mode 100644 src/Notepads/Connected Services/ExtensionService/ExtensionService.disco create mode 100644 src/Notepads/Connected Services/ExtensionService/ExtensionService.wsdl create mode 100644 src/Notepads/Connected Services/ExtensionService/ExtensionService.xsd create mode 100644 src/Notepads/Connected Services/ExtensionService/ExtensionService1.xsd create mode 100644 src/Notepads/Connected Services/ExtensionService/Reference.cs create mode 100644 src/Notepads/Connected Services/ExtensionService/Reference.svcmap create mode 100644 src/Notepads/Connected Services/ExtensionService/configuration.svcinfo create mode 100644 src/Notepads/Connected Services/ExtensionService/configuration91.svcinfo create mode 100644 src/Notepads/Properties/ServiceReferences.Designer.ClientConfig diff --git a/src/Notepads.DesktopExtension/App.config b/src/Notepads.DesktopExtension/App.config new file mode 100644 index 000000000..4137210b1 --- /dev/null +++ b/src/Notepads.DesktopExtension/App.config @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/ExtensionService.cs b/src/Notepads.DesktopExtension/ExtensionService.cs new file mode 100644 index 000000000..5bc257faa --- /dev/null +++ b/src/Notepads.DesktopExtension/ExtensionService.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.Serialization; +using System.ServiceModel; +using System.Text; + +namespace Notepads.DesktopExtension +{ + // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "ExtensionService" in both code and config file together. + public class ExtensionService : IExtensionService + { + public bool ReplaceFile(string newPath, string oldPath) + { + try + { + if (File.Exists(oldPath)) File.Delete(oldPath); + File.Move(newPath, oldPath); + if (File.Exists(newPath)) File.Delete(newPath); + } + catch (Exception) + { + return false; + } + return true; + } + } +} diff --git a/src/Notepads.DesktopExtension/IExtensionService.cs b/src/Notepads.DesktopExtension/IExtensionService.cs new file mode 100644 index 000000000..22b6dbabb --- /dev/null +++ b/src/Notepads.DesktopExtension/IExtensionService.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.ServiceModel; +using System.Text; + +namespace Notepads.DesktopExtension +{ + // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IExtensionService" in both code and config file together. + [ServiceContract] + public interface IExtensionService + { + [OperationContract] + bool ReplaceFile(string newPath, string oldPath); + } +} diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj new file mode 100644 index 000000000..9510a2ef1 --- /dev/null +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -0,0 +1,86 @@ + + + + + Debug + AnyCPU + {66937CD2-5D8C-42F6-88B9-C963D68ACD08} + WinExe + Notepads.DesktopExtension + Notepads.DesktopExtension + v4.7.2 + 512 + true + true + True + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + False + C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll + + + + + + + + + + + + + C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.17763.0\Windows.winmd + + + + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs new file mode 100644 index 000000000..2406f1089 --- /dev/null +++ b/src/Notepads.DesktopExtension/Program.cs @@ -0,0 +1,152 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Security.Principal; +using System.ServiceModel; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using Windows.ApplicationModel; +using Windows.ApplicationModel.Activation; +using Windows.ApplicationModel.AppService; +using Windows.Foundation.Collections; +using Windows.Storage; + +public enum CommandArgs +{ + SyncSettings, + SyncRecentList, + RegisterExtension, + CreateElevetedExtension, + ReplaceFile +} + +namespace Notepads.DesktopExtension +{ + static class Program + { + private static AppServiceConnection connection = null; + private static readonly string _commandLabel = "Command"; + private static readonly string _newFileLabel = "From"; + private static readonly string _oldFileLabel = "To"; + private static readonly string _failureLabel = "Failed"; + + private static ServiceHost selfHost = null; + + /// + /// The main entry point for the application. + /// + static void Main(string[] args) + { + if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) + { + InitializeExtensionService(); + } + else + { + InitializeAppServiceConnection(); + } + + Application.Run(); + } + + private static async void InitializeAppServiceConnection() + { + connection = new AppServiceConnection() + { + AppServiceName = "InteropServiceConnection", + PackageFamilyName = Package.Current.Id.FamilyName + }; + + connection.RequestReceived += Connection_RequestReceived; + connection.ServiceClosed += Connection_ServiceClosed; + + AppServiceConnectionStatus status = await connection.OpenAsync(); + + if(status != AppServiceConnectionStatus.Success) + { + Application.Exit(); + } + + var message = new ValueSet(); + message.Add(_commandLabel, CommandArgs.RegisterExtension.ToString()); + await connection.SendMessageAsync(message); + } + + private static void InitializeExtensionService() + { + selfHost = new ServiceHost(typeof(ExtensionService)); + selfHost.Open(); + } + + private static void Connection_ServiceClosed(AppServiceConnection sender, AppServiceClosedEventArgs args) + { + // connection to the UWP lost, so we shut down the desktop process + Application.Exit(); + } + + private static async void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) + { + // Get a deferral because we use an awaitable API below to respond to the message + // and we don't want this call to get canceled while we are waiting. + var messageDeferral = args.GetDeferral(); + + try + { + var message = args.Request.Message; + if (!message.ContainsKey(_commandLabel) || !Enum.TryParse((string)message[_commandLabel], out var command)) return; + switch (command) + { + case CommandArgs.ReplaceFile: + var status = false; + status = ReplaceFile((string)message[_newFileLabel], (string)message[_oldFileLabel]); + message.Clear(); + message.Add(_failureLabel, true); + await args.Request.SendResponseAsync(message); + break; + case CommandArgs.CreateElevetedExtension: + CreateElevetedExtension(); + break; + } + } + catch (Exception) + { + MessageBox.Show("error"); + } + + messageDeferral.Complete(); + } + + public static bool ReplaceFile(string newPath, string oldPath) + { + try + { + if (File.Exists(oldPath)) File.Delete(oldPath); + File.Move(newPath, oldPath); + if (File.Exists(newPath)) File.Delete(newPath); + } + catch (Exception) + { + return false; + } + return true; + } + + private static void CreateElevetedExtension() + { + string result = Assembly.GetExecutingAssembly().Location; + int index = result.LastIndexOf("\\"); + string rootPath = $"{result.Substring(0, index)}\\..\\"; + string aliasPath = rootPath + @"\Notepads.DesktopExtension\Notepads.DesktopExtension.exe"; + + ProcessStartInfo info = new ProcessStartInfo(); + info.Verb = "runas"; + info.UseShellExecute = true; + info.FileName = aliasPath; + Process.Start(info); + } + } +} diff --git a/src/Notepads.DesktopExtension/Properties/AssemblyInfo.cs b/src/Notepads.DesktopExtension/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..433d83b97 --- /dev/null +++ b/src/Notepads.DesktopExtension/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Notepads.DesktopExtension")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Notepads.DesktopExtension")] +[assembly: AssemblyCopyright("Copyright © 2020")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("66937cd2-5d8c-42f6-88b9-c963d68acd08")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/Notepads.DesktopExtension/Properties/Resources.Designer.cs b/src/Notepads.DesktopExtension/Properties/Resources.Designer.cs new file mode 100644 index 000000000..7835f8a5c --- /dev/null +++ b/src/Notepads.DesktopExtension/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Notepads.DesktopExtension.Properties +{ + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Notepads.DesktopExtension.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/src/Notepads.DesktopExtension/Properties/Resources.resx b/src/Notepads.DesktopExtension/Properties/Resources.resx new file mode 100644 index 000000000..af7dbebba --- /dev/null +++ b/src/Notepads.DesktopExtension/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Properties/Settings.Designer.cs b/src/Notepads.DesktopExtension/Properties/Settings.Designer.cs new file mode 100644 index 000000000..8bc4955b4 --- /dev/null +++ b/src/Notepads.DesktopExtension/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Notepads.DesktopExtension.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/src/Notepads.DesktopExtension/Properties/Settings.settings b/src/Notepads.DesktopExtension/Properties/Settings.settings new file mode 100644 index 000000000..39645652a --- /dev/null +++ b/src/Notepads.DesktopExtension/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/Notepads.Package/Notepads.Package.wapproj b/src/Notepads.Package/Notepads.Package.wapproj new file mode 100644 index 000000000..4b7b027e8 --- /dev/null +++ b/src/Notepads.Package/Notepads.Package.wapproj @@ -0,0 +1,70 @@ + + + + 15.0 + + + + Debug + x86 + + + Release + x86 + + + Debug + x64 + + + Release + x64 + + + Debug + ARM + + + Release + ARM + + + Debug + ARM64 + + + Release + ARM64 + + + Debug + AnyCPU + + + Release + AnyCPU + + + + $(MSBuildExtensionsPath)\Microsoft\DesktopBridge\ + + + + f451c0eb-4f7f-47d4-bcce-b0e265909dd9 + 10.0.18362.0 + 10.0.17763.0 + en-US + false + ..\Notepads\Notepads.csproj + + + + Designer + + + + + + + + \ No newline at end of file diff --git a/src/Notepads.Package/Package.appxmanifest b/src/Notepads.Package/Package.appxmanifest new file mode 100644 index 000000000..89502acef --- /dev/null +++ b/src/Notepads.Package/Package.appxmanifest @@ -0,0 +1,560 @@ + + + + + + + + + + Notepads App + Jackie Liu + Assets\StoreLogo.png + + + + + + + + + + + + + + + + + + + + + + + + + + + Assets\appicon_w.png + Notepads URI Scheme + + + + + + .txt + + Text Document + + Assets\FileIcons\txt.png + + + + + + + + + + + + + + + + .cfg + .config + .cnf + .conf + + Configuration Settings + Assets\FileIcons\cfg.png + + + + + + + .ini + + Initialization File + Assets\FileIcons\ini.png + + + + + + + .md + .markdown + + Markdown File + Assets\FileIcons\md.png + + + + + + + .log + + Log File + Assets\FileIcons\log.png + + + + + + + .bib + + BibTeX File + Assets\FileIcons\bib.png + + + + + + + .json + + JSON File + Assets\FileIcons\json.png + + + + + + + .yml + .yaml + + YML File + Assets\FileIcons\yml.png + + + + + + + .xml + + XML File + Assets\FileIcons\xml.png + + + + + + + .html + .htm + + HTML File + Assets\FileIcons\html.png + + + + + + + .asp + .aspx + + ASP File + Assets\FileIcons\asp.png + + + + + + + .jsp + .jspx + + JSP File + Assets\FileIcons\jsp.png + + + + + + + .css + .scss + + CSS File + Assets\FileIcons\css.png + + + + + + + .sh + + Shell Script File + Assets\FileIcons\sh.png + + + + + + + .bashrc + .vimrc + .rc + + Runcom File + Assets\FileIcons\rc.png + + + + + + + .bash + + Bash Script File + Assets\FileIcons\bash.png + + + + + + + .js + + Javascript File + Assets\FileIcons\js.png + + + + + + + .ts + .lua + + Scripting Language File + Assets\FileIcons\file.png + + + + + + + .c + .m + + C File + Assets\FileIcons\c.png + + + + + + + .cc + .mm + .cpp + + C++ File + Assets\FileIcons\cpp.png + + + + + + + .h + .hpp + + Header File + Assets\FileIcons\h.png + + + + + + + .cmake + + Cmake File + Assets\FileIcons\file.png + + + + + + + .cs + + C# File + Assets\FileIcons\cs.png + + + + + + + .php + + PHP File + Assets\FileIcons\php.png + + + + + + + .py + + Python File + Assets\FileIcons\py.png + + + + + + + .rb + + Ruby File + + Assets\FileIcons\rb.png + + + + + + .java + + JAVA File + Assets\FileIcons\java.png + + + + + + + .vb + + Visual Basic File + Assets\FileIcons\vb.png + + + + + + + .go + + Go File + Assets\FileIcons\file.png + + + + + + + .srt + + Subtitle file + Assets\FileIcons\srt.png + + + + + + + .ass + + Aegisub Advanced Subtitle file + Assets\FileIcons\ass.png + + + + + + + .ssa + + Sub Station Alpha Subtitle File + Assets\FileIcons\ssa.png + + + + + + + .vue + + Vue File + Assets\FileIcons\vue.png + + + + + + + .vuerc + + Vue Config File + Assets\FileIcons\vue.png + + + + + + + .gitconfig + + Git Config File + Assets\FileIcons\file.png + + + + + + + .gitignore + + Git Ignore File + Assets\FileIcons\file.png + + + + + + + .gitattributes + + Git Attributes File + Assets\FileIcons\file.png + + + + + + + .project + + Project File + Assets\FileIcons\file.png + + + + + + + .prj + + Project File + Assets\FileIcons\file.png + + + + + + + .npmrc + + NPM Config File + Assets\FileIcons\file.png + + + + + + + .bash_history + + Bash History File + Assets\FileIcons\file.png + + + + + + + .cgi + + CGI File + Assets\FileIcons\file.png + + + + + + + .pl + + Perl File + Assets\FileIcons\perl.png + + + + + + + .buildpath + + Build Path File + Assets\FileIcons\file.png + + + + + + + .sql + + SQL File + Assets\FileIcons\sql.png + + + + + + + + + + + + + + diff --git a/src/Notepads.Services/InteropConnectionService.cs b/src/Notepads.Services/InteropConnectionService.cs index 96b1f57f8..e17756527 100644 --- a/src/Notepads.Services/InteropConnectionService.cs +++ b/src/Notepads.Services/InteropConnectionService.cs @@ -2,16 +2,31 @@ { using System; using System.Collections.Generic; + using System.Text; using Windows.ApplicationModel; using Windows.ApplicationModel.AppService; using Windows.ApplicationModel.Background; + using Windows.Foundation.Collections; + + public enum CommandArgs + { + SyncSettings, + SyncRecentList, + RegisterExtension, + CreateElevetedExtension, + ReplaceFile + } public sealed class InteropConnectionService : IBackgroundTask { private BackgroundTaskDeferral backgroundTaskDeferral; private AppServiceConnection appServiceConnection; + private static BackgroundTaskDeferral extensionBackgroundTaskDeferral; + private static AppServiceConnection extensionAppServiceConnection = null; private static IList appServiceConnections = new List(); + private static readonly string _commandLabel = "Command"; + public void Run(IBackgroundTaskInstance taskInstance) { // Get a deferral so that the service isn't terminated. @@ -36,11 +51,54 @@ public void Run(IBackgroundTaskInstance taskInstance) private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { - foreach(var serviceConnection in appServiceConnections) + // Get a deferral because we use an awaitable API below to respond to the message + // and we don't want this call to get canceled while we are waiting. + var messageDeferral = args.GetDeferral(); + + var message = args.Request.Message; + if (!message.ContainsKey(_commandLabel) || !Enum.TryParse(typeof(CommandArgs), (string)message[_commandLabel], out var result)) return; + var command = (CommandArgs)result; + + switch (command) { - if (serviceConnection != appServiceConnection) - await serviceConnection.SendMessageAsync(args.Request.Message); + case CommandArgs.SyncSettings: + foreach (var serviceConnection in appServiceConnections) + { + if (serviceConnection != appServiceConnection) + await serviceConnection.SendMessageAsync(args.Request.Message); + } + break; + case CommandArgs.SyncRecentList: + foreach (var serviceConnection in appServiceConnections) + { + if (serviceConnection != appServiceConnection) + await serviceConnection.SendMessageAsync(args.Request.Message); + } + break; + case CommandArgs.RegisterExtension: + if(extensionAppServiceConnection==null) + { + extensionAppServiceConnection = appServiceConnection; + extensionBackgroundTaskDeferral = this.backgroundTaskDeferral; + appServiceConnections.Remove(appServiceConnection); + } + else + { + appServiceConnections.Remove(appServiceConnection); + this.backgroundTaskDeferral.Complete(); + } + break; + case CommandArgs.CreateElevetedExtension: + await extensionAppServiceConnection.SendMessageAsync(message); + break; + case CommandArgs.ReplaceFile: + var response = await extensionAppServiceConnection.SendMessageAsync(message); + message = response.Message; + await args.Request.SendResponseAsync(message); + break; } + + messageDeferral.Complete(); } private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) diff --git a/src/Notepads.Services/Notepads.Services.csproj b/src/Notepads.Services/Notepads.Services.csproj index 6e17a1787..cfcfb9a82 100644 --- a/src/Notepads.Services/Notepads.Services.csproj +++ b/src/Notepads.Services/Notepads.Services.csproj @@ -129,6 +129,9 @@ 6.2.9 + + + 14.0 diff --git a/src/Notepads.sln b/src/Notepads.sln index cf7f8698f..7887fe1ad 100644 --- a/src/Notepads.sln +++ b/src/Notepads.sln @@ -17,6 +17,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Notepads.Services", "Notepads.Services\Notepads.Services.csproj", "{29DCAA68-1B6B-4290-8C05-691F52645D55}" EndProject +Project("{C7167F0D-BC9F-4E6E-AFE1-012C56B48DB5}") = "Notepads.Package", "Notepads.Package\Notepads.Package.wapproj", "{F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Notepads.DesktopExtension", "Notepads.DesktopExtension\Notepads.DesktopExtension.csproj", "{66937CD2-5D8C-42F6-88B9-C963D68ACD08}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -38,7 +42,6 @@ Global {99274932-9E86-480C-8142-38525F80007D}.Debug|ARM64.Deploy.0 = Debug|ARM64 {99274932-9E86-480C-8142-38525F80007D}.Debug|x64.ActiveCfg = Debug|x64 {99274932-9E86-480C-8142-38525F80007D}.Debug|x64.Build.0 = Debug|x64 - {99274932-9E86-480C-8142-38525F80007D}.Debug|x64.Deploy.0 = Debug|x64 {99274932-9E86-480C-8142-38525F80007D}.Debug|x86.ActiveCfg = Debug|x86 {99274932-9E86-480C-8142-38525F80007D}.Debug|x86.Build.0 = Debug|x86 {99274932-9E86-480C-8142-38525F80007D}.Debug|x86.Deploy.0 = Debug|x86 @@ -93,6 +96,56 @@ Global {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|x64.Build.0 = Release|x64 {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|x86.ActiveCfg = Release|x86 {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|x86.Build.0 = Release|x86 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|Any CPU.Deploy.0 = Debug|Any CPU + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|ARM.ActiveCfg = Debug|ARM + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|ARM.Build.0 = Debug|ARM + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|ARM.Deploy.0 = Debug|ARM + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|ARM64.Build.0 = Debug|ARM64 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|ARM64.Deploy.0 = Debug|ARM64 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|x64.ActiveCfg = Debug|x64 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|x64.Build.0 = Debug|x64 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|x64.Deploy.0 = Debug|x64 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|x86.ActiveCfg = Debug|x86 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|x86.Build.0 = Debug|x86 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|x86.Deploy.0 = Debug|x86 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|Any CPU.Build.0 = Release|Any CPU + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|Any CPU.Deploy.0 = Release|Any CPU + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|ARM.ActiveCfg = Release|ARM + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|ARM.Build.0 = Release|ARM + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|ARM.Deploy.0 = Release|ARM + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|ARM64.ActiveCfg = Release|ARM64 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|ARM64.Build.0 = Release|ARM64 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|ARM64.Deploy.0 = Release|ARM64 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|x64.ActiveCfg = Release|x64 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|x64.Build.0 = Release|x64 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|x64.Deploy.0 = Release|x64 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|x86.ActiveCfg = Release|x86 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|x86.Build.0 = Release|x86 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|x86.Deploy.0 = Release|x86 + {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Debug|Any CPU.Build.0 = Debug|Any CPU + {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Debug|ARM.ActiveCfg = Debug|Any CPU + {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Debug|ARM.Build.0 = Debug|Any CPU + {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Debug|ARM64.Build.0 = Debug|Any CPU + {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Debug|x64.ActiveCfg = Debug|Any CPU + {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Debug|x64.Build.0 = Debug|Any CPU + {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Debug|x86.ActiveCfg = Debug|Any CPU + {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Debug|x86.Build.0 = Debug|Any CPU + {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Release|Any CPU.ActiveCfg = Release|Any CPU + {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Release|Any CPU.Build.0 = Release|Any CPU + {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Release|ARM.ActiveCfg = Release|Any CPU + {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Release|ARM.Build.0 = Release|Any CPU + {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Release|ARM64.ActiveCfg = Release|Any CPU + {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Release|ARM64.Build.0 = Release|Any CPU + {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Release|x64.ActiveCfg = Release|Any CPU + {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Release|x64.Build.0 = Release|Any CPU + {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Release|x86.ActiveCfg = Release|Any CPU + {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/Notepads/Connected Services/ExtensionService/ExtensionService.disco b/src/Notepads/Connected Services/ExtensionService/ExtensionService.disco new file mode 100644 index 000000000..bd7d02c9a --- /dev/null +++ b/src/Notepads/Connected Services/ExtensionService/ExtensionService.disco @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/src/Notepads/Connected Services/ExtensionService/ExtensionService.wsdl b/src/Notepads/Connected Services/ExtensionService/ExtensionService.wsdl new file mode 100644 index 000000000..e55efcf10 --- /dev/null +++ b/src/Notepads/Connected Services/ExtensionService/ExtensionService.wsdl @@ -0,0 +1,76 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Notepads/Connected Services/ExtensionService/ExtensionService.xsd b/src/Notepads/Connected Services/ExtensionService/ExtensionService.xsd new file mode 100644 index 000000000..87353d604 --- /dev/null +++ b/src/Notepads/Connected Services/ExtensionService/ExtensionService.xsd @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Notepads/Connected Services/ExtensionService/ExtensionService1.xsd b/src/Notepads/Connected Services/ExtensionService/ExtensionService1.xsd new file mode 100644 index 000000000..d58e7f39c --- /dev/null +++ b/src/Notepads/Connected Services/ExtensionService/ExtensionService1.xsd @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Notepads/Connected Services/ExtensionService/Reference.cs b/src/Notepads/Connected Services/ExtensionService/Reference.cs new file mode 100644 index 000000000..24ed5461a --- /dev/null +++ b/src/Notepads/Connected Services/ExtensionService/Reference.cs @@ -0,0 +1,126 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +// +// This code was auto-generated by Microsoft.VisualStudio.ServiceReference.Platforms, version 16.0.30011.22 +// +namespace Notepads.ExtensionService { + + + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] + [System.ServiceModel.ServiceContractAttribute(ConfigurationName="ExtensionService.IExtensionService")] + public interface IExtensionService { + + [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IExtensionService/DoWork", ReplyAction="http://tempuri.org/IExtensionService/DoWorkResponse")] + System.Threading.Tasks.Task DoWorkAsync(); + + [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IExtensionService/ReplaceFile", ReplyAction="http://tempuri.org/IExtensionService/ReplaceFileResponse")] + System.Threading.Tasks.Task ReplaceFileAsync(string newPath, string oldPath); + + [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IExtensionService/Add", ReplyAction="http://tempuri.org/IExtensionService/AddResponse")] + System.Threading.Tasks.Task AddAsync(int a, int b); + } + + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] + public interface IExtensionServiceChannel : Notepads.ExtensionService.IExtensionService, System.ServiceModel.IClientChannel { + } + + [System.Diagnostics.DebuggerStepThroughAttribute()] + [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] + public partial class ExtensionServiceClient : System.ServiceModel.ClientBase, Notepads.ExtensionService.IExtensionService { + + /// + /// Implement this partial method to configure the service endpoint. + /// + /// The endpoint to configure + /// The client credentials + static partial void ConfigureEndpoint(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint, System.ServiceModel.Description.ClientCredentials clientCredentials); + + public ExtensionServiceClient() : + base(ExtensionServiceClient.GetDefaultBinding(), ExtensionServiceClient.GetDefaultEndpointAddress()) { + this.Endpoint.Name = EndpointConfiguration.BasicHttpBinding_IExtensionService.ToString(); + ConfigureEndpoint(this.Endpoint, this.ClientCredentials); + } + + public ExtensionServiceClient(EndpointConfiguration endpointConfiguration) : + base(ExtensionServiceClient.GetBindingForEndpoint(endpointConfiguration), ExtensionServiceClient.GetEndpointAddress(endpointConfiguration)) { + this.Endpoint.Name = endpointConfiguration.ToString(); + ConfigureEndpoint(this.Endpoint, this.ClientCredentials); + } + + public ExtensionServiceClient(EndpointConfiguration endpointConfiguration, string remoteAddress) : + base(ExtensionServiceClient.GetBindingForEndpoint(endpointConfiguration), new System.ServiceModel.EndpointAddress(remoteAddress)) { + this.Endpoint.Name = endpointConfiguration.ToString(); + ConfigureEndpoint(this.Endpoint, this.ClientCredentials); + } + + public ExtensionServiceClient(EndpointConfiguration endpointConfiguration, System.ServiceModel.EndpointAddress remoteAddress) : + base(ExtensionServiceClient.GetBindingForEndpoint(endpointConfiguration), remoteAddress) { + this.Endpoint.Name = endpointConfiguration.ToString(); + ConfigureEndpoint(this.Endpoint, this.ClientCredentials); + } + + public ExtensionServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : + base(binding, remoteAddress) { + } + + public System.Threading.Tasks.Task DoWorkAsync() { + return base.Channel.DoWorkAsync(); + } + + public System.Threading.Tasks.Task ReplaceFileAsync(string newPath, string oldPath) { + return base.Channel.ReplaceFileAsync(newPath, oldPath); + } + + public System.Threading.Tasks.Task AddAsync(int a, int b) { + return base.Channel.AddAsync(a, b); + } + + public virtual System.Threading.Tasks.Task OpenAsync() { + return System.Threading.Tasks.Task.Factory.FromAsync(((System.ServiceModel.ICommunicationObject)(this)).BeginOpen(null, null), new System.Action(((System.ServiceModel.ICommunicationObject)(this)).EndOpen)); + } + + public virtual System.Threading.Tasks.Task CloseAsync() { + return System.Threading.Tasks.Task.Factory.FromAsync(((System.ServiceModel.ICommunicationObject)(this)).BeginClose(null, null), new System.Action(((System.ServiceModel.ICommunicationObject)(this)).EndClose)); + } + + private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(EndpointConfiguration endpointConfiguration) { + if ((endpointConfiguration == EndpointConfiguration.BasicHttpBinding_IExtensionService)) { + System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding(); + result.MaxBufferSize = int.MaxValue; + result.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max; + result.MaxReceivedMessageSize = int.MaxValue; + result.AllowCookies = true; + return result; + } + throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration)); + } + + private static System.ServiceModel.EndpointAddress GetEndpointAddress(EndpointConfiguration endpointConfiguration) { + if ((endpointConfiguration == EndpointConfiguration.BasicHttpBinding_IExtensionService)) { + return new System.ServiceModel.EndpointAddress("http://localhost:8000/Notepads.DesktopExtension/ExtensionService"); + } + throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration)); + } + + private static System.ServiceModel.Channels.Binding GetDefaultBinding() { + return ExtensionServiceClient.GetBindingForEndpoint(EndpointConfiguration.BasicHttpBinding_IExtensionService); + } + + private static System.ServiceModel.EndpointAddress GetDefaultEndpointAddress() { + return ExtensionServiceClient.GetEndpointAddress(EndpointConfiguration.BasicHttpBinding_IExtensionService); + } + + public enum EndpointConfiguration { + + BasicHttpBinding_IExtensionService, + } + } +} diff --git a/src/Notepads/Connected Services/ExtensionService/Reference.svcmap b/src/Notepads/Connected Services/ExtensionService/Reference.svcmap new file mode 100644 index 000000000..34ca65556 --- /dev/null +++ b/src/Notepads/Connected Services/ExtensionService/Reference.svcmap @@ -0,0 +1,36 @@ + + + + false + true + true + + false + false + false + + + + + false + Auto + true + true + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Notepads/Connected Services/ExtensionService/configuration.svcinfo b/src/Notepads/Connected Services/ExtensionService/configuration.svcinfo new file mode 100644 index 000000000..d3da738a3 --- /dev/null +++ b/src/Notepads/Connected Services/ExtensionService/configuration.svcinfo @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/src/Notepads/Connected Services/ExtensionService/configuration91.svcinfo b/src/Notepads/Connected Services/ExtensionService/configuration91.svcinfo new file mode 100644 index 000000000..08bf21e68 --- /dev/null +++ b/src/Notepads/Connected Services/ExtensionService/configuration91.svcinfo @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/src/Notepads/Controls/Dialog/NotepadsDialogFactory.cs b/src/Notepads/Controls/Dialog/NotepadsDialogFactory.cs index b7b0a3250..ab7bee34b 100644 --- a/src/Notepads/Controls/Dialog/NotepadsDialogFactory.cs +++ b/src/Notepads/Controls/Dialog/NotepadsDialogFactory.cs @@ -84,6 +84,21 @@ public static NotepadsDialog GetRevertAllChangesConfirmationDialog(string fileNa return revertAllChangesConfirmationDialog; } + public static NotepadsDialog GetCreateElevatedExtensionDialog(Action confirmedAction, Action closeAction) + { + NotepadsDialog createElevatedExtensionDialog = new NotepadsDialog + { + Title = ResourceLoader.GetString("CreateElevatedExtensionDialog_Title"), + Content = ResourceLoader.GetString("CreateElevatedExtensionDialog_Content"), + PrimaryButtonText = ResourceLoader.GetString("RevertAllChangesConfirmationDialog_PrimaryButtonText"), + CloseButtonText = ResourceLoader.GetString("CreateElevatedExtensionDialog_CloseButtonText"), + RequestedTheme = ThemeSettingsService.ThemeMode, + }; + createElevatedExtensionDialog.PrimaryButtonClick += (dialog, args) => { confirmedAction(); }; + createElevatedExtensionDialog.CloseButtonClick += (dialog, args) => { closeAction(); }; + return createElevatedExtensionDialog; + } + private static Style GetButtonStyle(Color backgroundColor) { var buttonStyle = new Windows.UI.Xaml.Style(typeof(Button)); diff --git a/src/Notepads/Notepads.csproj b/src/Notepads/Notepads.csproj index cd678ba4e..9d1b2fc1c 100644 --- a/src/Notepads/Notepads.csproj +++ b/src/Notepads/Notepads.csproj @@ -108,6 +108,11 @@ + + True + True + Reference.svcmap + FindAndReplaceControl.xaml @@ -414,6 +419,13 @@ + + + + + WCF Proxy Generator + Reference.cs + @@ -473,6 +485,7 @@ + @@ -753,6 +766,21 @@ Windows Desktop Extensions for the UWP + + + + + + Designer + + + Designer + + + + + + 14.0 diff --git a/src/Notepads/Package.appxmanifest b/src/Notepads/Package.appxmanifest index 279f374d6..f989acb03 100644 --- a/src/Notepads/Package.appxmanifest +++ b/src/Notepads/Package.appxmanifest @@ -53,491 +53,6 @@ - - - - Assets\appicon_w.png - Notepads URI Scheme - - - - - - .txt - - Text Document - - Assets\FileIcons\txt.png - - - - - - - - - - - - - - .cfg - .config - .cnf - .conf - - Configuration Settings - Assets\FileIcons\cfg.png - - - - - - - .ini - - Initialization File - Assets\FileIcons\ini.png - - - - - - - .md - .markdown - - Markdown File - Assets\FileIcons\md.png - - - - - - - .log - - Log File - Assets\FileIcons\log.png - - - - - - - .bib - - BibTeX File - Assets\FileIcons\bib.png - - - - - - - .json - - JSON File - Assets\FileIcons\json.png - - - - - - - .yml - .yaml - - YML File - Assets\FileIcons\yml.png - - - - - - - .xml - - XML File - Assets\FileIcons\xml.png - - - - - - - .html - .htm - - HTML File - Assets\FileIcons\html.png - - - - - - - .asp - .aspx - - ASP File - Assets\FileIcons\asp.png - - - - - - - .jsp - .jspx - - JSP File - Assets\FileIcons\jsp.png - - - - - - - .css - .scss - - CSS File - Assets\FileIcons\css.png - - - - - - - .sh - - Shell Script File - Assets\FileIcons\sh.png - - - - - - - .bashrc - .vimrc - .rc - - Runcom File - Assets\FileIcons\rc.png - - - - - - - .bash - - Bash Script File - Assets\FileIcons\bash.png - - - - - - - .js - - Javascript File - Assets\FileIcons\js.png - - - - - - - .ts - .lua - - Scripting Language File - Assets\FileIcons\file.png - - - - - - - .c - .m - - C File - Assets\FileIcons\c.png - - - - - - - .cc - .mm - .cpp - - C++ File - Assets\FileIcons\cpp.png - - - - - - - .h - .hpp - - Header File - Assets\FileIcons\h.png - - - - - - - .cmake - - Cmake File - Assets\FileIcons\file.png - - - - - - - .cs - - C# File - Assets\FileIcons\cs.png - - - - - - - .php - - PHP File - Assets\FileIcons\php.png - - - - - - - .py - - Python File - Assets\FileIcons\py.png - - - - - - - .rb - - Ruby File - - Assets\FileIcons\rb.png - - - - - - .java - - JAVA File - Assets\FileIcons\java.png - - - - - - - .vb - - Visual Basic File - Assets\FileIcons\vb.png - - - - - - - .go - - Go File - Assets\FileIcons\file.png - - - - - - - .srt - - Subtitle file - Assets\FileIcons\srt.png - - - - - - - .ass - - Aegisub Advanced Subtitle file - Assets\FileIcons\ass.png - - - - - - - .ssa - - Sub Station Alpha Subtitle File - Assets\FileIcons\ssa.png - - - - - - - .vue - - Vue File - Assets\FileIcons\vue.png - - - - - - - .vuerc - - Vue Config File - Assets\FileIcons\vue.png - - - - - - - .gitconfig - - Git Config File - Assets\FileIcons\file.png - - - - - - - .gitignore - - Git Ignore File - Assets\FileIcons\file.png - - - - - - - .gitattributes - - Git Attributes File - Assets\FileIcons\file.png - - - - - - - .project - - Project File - Assets\FileIcons\file.png - - - - - - - .prj - - Project File - Assets\FileIcons\file.png - - - - - - - .npmrc - - NPM Config File - Assets\FileIcons\file.png - - - - - - - .bash_history - - Bash History File - Assets\FileIcons\file.png - - - - - - - .cgi - - CGI File - Assets\FileIcons\file.png - - - - - - - .pl - - Perl File - Assets\FileIcons\perl.png - - - - - - - .buildpath - - Build Path File - Assets\FileIcons\file.png - - - - - - - .sql - - SQL File - Assets\FileIcons\sql.png - - - - diff --git a/src/Notepads/Program.cs b/src/Notepads/Program.cs index dc6af3023..17f910064 100644 --- a/src/Notepads/Program.cs +++ b/src/Notepads/Program.cs @@ -35,6 +35,7 @@ static void Main(string[] args) { IsFirstInstance = true; ApplicationSettingsStore.Write(SettingsKey.ActiveInstanceIdStr, null); + OpenExtension(); } if (activatedArgs is FileActivatedEventArgs) @@ -144,5 +145,11 @@ private static AppInstance GetLastActiveInstance() // activeInstance might be closed already, let's return the first instance in this case return instances.FirstOrDefault(); } + + private static async void OpenExtension() + { + + await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); + } } } \ No newline at end of file diff --git a/src/Notepads/Properties/ServiceReferences.Designer.ClientConfig b/src/Notepads/Properties/ServiceReferences.Designer.ClientConfig new file mode 100644 index 000000000..337de15db --- /dev/null +++ b/src/Notepads/Properties/ServiceReferences.Designer.ClientConfig @@ -0,0 +1,4 @@ + + + + diff --git a/src/Notepads/Services/InteropService.cs b/src/Notepads/Services/InteropService.cs index bc7ca1162..5a210d48f 100644 --- a/src/Notepads/Services/InteropService.cs +++ b/src/Notepads/Services/InteropService.cs @@ -1,8 +1,10 @@ namespace Notepads.Services { + using Notepads.ExtensionService; using Notepads.Settings; using System; using System.Collections.Generic; + using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.AppService; using Windows.Foundation.Collections; @@ -11,13 +13,19 @@ public static class InteropService { public static EventHandler HideSettingsPane; + public static EventHandler UpdateRecentList; public static bool EnableSettingsLogging = true; public static AppServiceConnection InteropServiceConnection = null; + private static ExtensionServiceClient adminExtensionServiceClient = new ExtensionServiceClient(); + private static readonly string _commandLabel = "Command"; private static readonly string _appIdLabel = "Instance"; private static readonly string _settingsKeyLabel = "Settings"; private static readonly string _valueLabel = "Value"; + private static readonly string _newFileLabel = "From"; + private static readonly string _oldFileLabel = "To"; + private static readonly string _failureLabel = "Failed"; private static IReadOnlyDictionary SettingsManager = new Dictionary { @@ -59,14 +67,24 @@ public static async void Initialize() private static void InteropServiceConnection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { var message = args.Request.Message; - if (message.ContainsKey(_appIdLabel) && message[_appIdLabel] is Guid appID && appID != App.Id) + if (!message.ContainsKey(_commandLabel) || !Enum.TryParse(typeof(CommandArgs), (string)message[_commandLabel], out var result)) return; + var command = (CommandArgs)result; + switch(command) { - EnableSettingsLogging = false; - HideSettingsPane?.Invoke(null, true); - var settingsKey = message[_settingsKeyLabel] as string; - var value = message[_valueLabel] as object; - SettingsManager[settingsKey](value); - EnableSettingsLogging = true; + case CommandArgs.SyncSettings: + if (message.ContainsKey(_appIdLabel) && message[_appIdLabel] is Guid appID && appID != App.Id) + { + EnableSettingsLogging = false; + HideSettingsPane?.Invoke(null, true); + var settingsKey = message[_settingsKeyLabel] as string; + var value = message[_valueLabel] as object; + SettingsManager[settingsKey](value); + EnableSettingsLogging = true; + } + break; + case CommandArgs.SyncRecentList: + UpdateRecentList?.Invoke(null, false); + break; } } @@ -77,7 +95,10 @@ private static void InteropServiceConnection_ServiceClosed(AppServiceConnection public static async void SyncSettings(string settingsKey, object value) { + if (InteropServiceConnection == null) return; + var message = new ValueSet(); + message.Add(_commandLabel, CommandArgs.SyncSettings.ToString()); message.Add(_appIdLabel, App.Id); message.Add(_settingsKeyLabel, settingsKey); try @@ -90,5 +111,69 @@ public static async void SyncSettings(string settingsKey, object value) } await InteropServiceConnection.SendMessageAsync(message); } + + public static async void SyncRecentList() + { + if (InteropServiceConnection == null) return; + + var message = new ValueSet(); + message.Add(_commandLabel, CommandArgs.SyncRecentList.ToString()); + await InteropServiceConnection.SendMessageAsync(message); + } + + public static async Task ReplaceFile(string newFilePath, string oldFilePath, bool isElevationRequired) + { + if (InteropServiceConnection == null) return; + + bool failedFromDesktopExtension = false; + bool failedFromAdminExtension = false; + if (isElevationRequired) + { + try + { + if (!await adminExtensionServiceClient.ReplaceFileAsync(newFilePath, oldFilePath)) + { + failedFromAdminExtension = true; + } + } + catch + { + failedFromAdminExtension = true; + } + } + else + { + var message = new ValueSet(); + message.Add(_commandLabel, CommandArgs.ReplaceFile.ToString()); + message.Add(_newFileLabel, newFilePath); + message.Add(_oldFileLabel, oldFilePath); + + var response = await InteropServiceConnection.SendMessageAsync(message); + var responseMessage = response.Message; + if (responseMessage.ContainsKey(_failureLabel) && (bool)responseMessage[_failureLabel]) + { + failedFromDesktopExtension = true; + } + } + + if (failedFromDesktopExtension) + { + throw new Exception("Failed to save due to no Extension access"); + } + + if (failedFromAdminExtension) + { + throw new Exception("Failed to save due to no Adminstration access"); + } + } + + public static async Task CreateElevetedExtension() + { + if (InteropServiceConnection == null) return; + + var message = new ValueSet(); + message.Add(_commandLabel, CommandArgs.CreateElevetedExtension.ToString()); + var response = await InteropServiceConnection.SendMessageAsync(message); + } } } diff --git a/src/Notepads/Strings/en-US/Resources.resw b/src/Notepads/Strings/en-US/Resources.resw index a65a265b2..52557e405 100644 --- a/src/Notepads/Strings/en-US/Resources.resw +++ b/src/Notepads/Strings/en-US/Resources.resw @@ -585,4 +585,16 @@ Right-to-Left Reading order TextEditor: ContextFlyout "Right-to-Left Reading order" toggle button display text. + + No + CreateElevatedExtensionDialog: CloseButtonText. + + + The file cannot be saved, it may be protected. Do you want to give Notepads Adminstrator permission? + CreateElevatedExtensionDialog: "Content" display text. + + + Save Failed + CreateElevatedExtensionDialog: "Title" display text. + \ No newline at end of file diff --git a/src/Notepads/Utilities/FileSystemUtility.cs b/src/Notepads/Utilities/FileSystemUtility.cs index 45e51d991..5b8c762d6 100644 --- a/src/Notepads/Utilities/FileSystemUtility.cs +++ b/src/Notepads/Utilities/FileSystemUtility.cs @@ -21,6 +21,7 @@ public static class FileSystemUtility private static readonly ResourceLoader ResourceLoader = ResourceLoader.GetForCurrentView(); private const string WslRootPath = "\\\\wsl$\\"; + private const string TempSaveFolderDefaultName = "TempSave"; public static bool IsFullPath(string path) { @@ -457,6 +458,13 @@ public static async Task WriteToFile(string text, Encoding encoding, StorageFile // Write to file Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + StorageFile oldFile = null; + if (IsFileReadOnly(file) || !await FileIsWritable(file)) + { + oldFile = file; + file = await SessionUtility.CreateNewFileInBackupFolderAsync(Guid.NewGuid().ToString(), CreationCollisionOption.ReplaceExisting, TempSaveFolderDefaultName); + } + using (var stream = await file.OpenStreamForWriteAsync()) using (var writer = new StreamWriter(stream, encoding)) { @@ -467,6 +475,11 @@ public static async Task WriteToFile(string text, Encoding encoding, StorageFile stream.SetLength(stream.Position); } + if (oldFile != null) + { + await InteropService.ReplaceFile(file.Path, oldFile.Path, IsFileReadOnly(file) ? false : true); + } + if (usedDeferUpdates) { // Let Windows know that we're finished changing the file so the diff --git a/src/Notepads/Views/NotepadsMainPage.IO.cs b/src/Notepads/Views/NotepadsMainPage.IO.cs index 556f8ca62..a5d351f9f 100644 --- a/src/Notepads/Views/NotepadsMainPage.IO.cs +++ b/src/Notepads/Views/NotepadsMainPage.IO.cs @@ -120,9 +120,7 @@ private async Task Save(ITextEditor textEditor, bool saveAs, bool ignoreUn StorageFile file = null; try { - if (textEditor.EditingFile == null || saveAs || - FileSystemUtility.IsFileReadOnly(textEditor.EditingFile) || - !await FileSystemUtility.FileIsWritable(textEditor.EditingFile)) + if (textEditor.EditingFile == null || saveAs) { NotepadsCore.SwitchTo(textEditor); file = await FilePickerFactory.GetFileSavePicker(textEditor, saveAs).PickSaveFileAsync(); @@ -147,13 +145,45 @@ private async Task Save(ITextEditor textEditor, bool saveAs, bool ignoreUn } catch (Exception ex) { - var fileSaveErrorDialog = NotepadsDialogFactory.GetFileSaveErrorDialog((file == null) ? string.Empty : file.Path, ex.Message); - await DialogManager.OpenDialogAsync(fileSaveErrorDialog, awaitPreviousDialog: false); - if (!fileSaveErrorDialog.IsAborted) + if(ex.Message.Equals("Failed to save due to no Adminstration access")) { - NotepadsCore.FocusOnSelectedTextEditor(); + bool result = false; + + var createElevatedExtensionDialog = NotepadsDialogFactory.GetCreateElevatedExtensionDialog( + async () => + { + await InteropService.CreateElevetedExtension(); + }, + async () => + { + if (!saveAs) result = await Save(textEditor, true, ignoreUnmodifiedDocument, rebuildOpenRecentItems); + }); + + var dialogResult= await DialogManager.OpenDialogAsync(createElevatedExtensionDialog, awaitPreviousDialog: false); + + if (dialogResult == null || createElevatedExtensionDialog.IsAborted) + { + if (!saveAs) result = await Save(textEditor, true, ignoreUnmodifiedDocument, rebuildOpenRecentItems); + } + + return result; + } + else if(ex.Message.Equals("Failed to save due to no Extension access")) + { + bool result = false; + if (!saveAs) result = await Save(textEditor, true, ignoreUnmodifiedDocument, rebuildOpenRecentItems); + return result; + } + else + { + var fileSaveErrorDialog = NotepadsDialogFactory.GetFileSaveErrorDialog((file == null) ? string.Empty : file.Path, ex.Message); + await DialogManager.OpenDialogAsync(fileSaveErrorDialog, awaitPreviousDialog: false); + if (!fileSaveErrorDialog.IsAborted) + { + NotepadsCore.FocusOnSelectedTextEditor(); + } + return false; } - return false; } } diff --git a/src/Notepads/Views/NotepadsMainPage.MainMenu.cs b/src/Notepads/Views/NotepadsMainPage.MainMenu.cs index 45c2d0842..cfd8b4c87 100644 --- a/src/Notepads/Views/NotepadsMainPage.MainMenu.cs +++ b/src/Notepads/Views/NotepadsMainPage.MainMenu.cs @@ -105,7 +105,7 @@ private void MainMenuButtonFlyout_Opening(object sender, object e) MenuSaveAllButton.IsEnabled = NotepadsCore.HaveUnsavedTextEditor(); } - private async Task BuildOpenRecentButtonSubItems() + private async Task BuildOpenRecentButtonSubItems(bool updateForOtherInstane = true) { var openRecentSubItem = new MenuFlyoutSubItem { @@ -167,6 +167,8 @@ private async Task BuildOpenRecentButtonSubItems() var indexToInsert = MainMenuButtonFlyout.Items.IndexOf(MenuOpenFileButton) + 1; MainMenuButtonFlyout.Items.Insert(indexToInsert, openRecentSubItem); } + + if (updateForOtherInstane) InteropService.SyncRecentList(); } } } \ No newline at end of file diff --git a/src/Notepads/Views/NotepadsMainPage.xaml.cs b/src/Notepads/Views/NotepadsMainPage.xaml.cs index f10a540db..15d378ce5 100644 --- a/src/Notepads/Views/NotepadsMainPage.xaml.cs +++ b/src/Notepads/Views/NotepadsMainPage.xaml.cs @@ -280,6 +280,10 @@ private async void Sets_Loaded(object sender, RoutedEventArgs e) InteropService.Initialize(); InteropService.HideSettingsPane += HideSettingsPane_OnSettingsChanged; + InteropService.UpdateRecentList += async (_, updateForOtherInstaneArgs) => await Dispatcher.CallOnUIThreadAsync(async () => + { + await BuildOpenRecentButtonSubItems(updateForOtherInstaneArgs); + }); SettingsDelegate.Dispatcher = Dispatcher; } @@ -296,10 +300,11 @@ private async void App_EnteredBackground(object sender, Windows.ApplicationModel deferral.Complete(); } - private void App_LeavingBackground(object sender, LeavingBackgroundEventArgs e) + private async void App_LeavingBackground(object sender, LeavingBackgroundEventArgs e) { ThemeSettingsService.UpdateAllSettings(); EditorSettingsService.UpdateAllSettings(); + await BuildOpenRecentButtonSubItems(false); InteropService.Initialize(); } From 6474d6c70a387dd8b0e7da319e1b247af3f5a7f2 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 9 May 2020 00:37:30 +0530 Subject: [PATCH 010/181] fix --- .../ExtensionService.cs | 4 +-- src/Notepads.DesktopExtension/Program.cs | 14 ++++------ .../InteropConnectionService.cs | 11 +++++++- src/Notepads/Program.cs | 7 +++-- src/Notepads/Services/InteropService.cs | 28 +++++++++++++------ src/Notepads/Utilities/FileSystemUtility.cs | 8 +++++- src/Notepads/Views/NotepadsMainPage.IO.cs | 4 +-- 7 files changed, 50 insertions(+), 26 deletions(-) diff --git a/src/Notepads.DesktopExtension/ExtensionService.cs b/src/Notepads.DesktopExtension/ExtensionService.cs index 5bc257faa..5a5872535 100644 --- a/src/Notepads.DesktopExtension/ExtensionService.cs +++ b/src/Notepads.DesktopExtension/ExtensionService.cs @@ -15,9 +15,7 @@ public bool ReplaceFile(string newPath, string oldPath) { try { - if (File.Exists(oldPath)) File.Delete(oldPath); - File.Move(newPath, oldPath); - if (File.Exists(newPath)) File.Delete(newPath); + File.Copy(newPath, oldPath, true); } catch (Exception) { diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs index 2406f1089..6892a1ed2 100644 --- a/src/Notepads.DesktopExtension/Program.cs +++ b/src/Notepads.DesktopExtension/Program.cs @@ -101,10 +101,10 @@ private static async void Connection_RequestReceived(AppServiceConnection sender switch (command) { case CommandArgs.ReplaceFile: - var status = false; - status = ReplaceFile((string)message[_newFileLabel], (string)message[_oldFileLabel]); + var failed = false; + failed = ReplaceFile((string)message[_newFileLabel], (string)message[_oldFileLabel]); message.Clear(); - message.Add(_failureLabel, true); + if (failed) message.Add(_failureLabel, true); await args.Request.SendResponseAsync(message); break; case CommandArgs.CreateElevetedExtension: @@ -124,15 +124,13 @@ public static bool ReplaceFile(string newPath, string oldPath) { try { - if (File.Exists(oldPath)) File.Delete(oldPath); - File.Move(newPath, oldPath); - if (File.Exists(newPath)) File.Delete(newPath); + File.Copy(newPath, oldPath, true); } catch (Exception) { - return false; + return true; } - return true; + return false; } private static void CreateElevetedExtension() diff --git a/src/Notepads.Services/InteropConnectionService.cs b/src/Notepads.Services/InteropConnectionService.cs index e17756527..e3f0fce77 100644 --- a/src/Notepads.Services/InteropConnectionService.cs +++ b/src/Notepads.Services/InteropConnectionService.cs @@ -26,6 +26,7 @@ public sealed class InteropConnectionService : IBackgroundTask private static IList appServiceConnections = new List(); private static readonly string _commandLabel = "Command"; + private static readonly string _failureLabel = "Failed"; public void Run(IBackgroundTaskInstance taskInstance) { @@ -93,7 +94,15 @@ private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequ break; case CommandArgs.ReplaceFile: var response = await extensionAppServiceConnection.SendMessageAsync(message); - message = response.Message; + if (response.Status != AppServiceResponseStatus.Success) + { + message.Clear(); + message.Add(_failureLabel, true); + } + else + { + message = response.Message; + } await args.Request.SendResponseAsync(message); break; } diff --git a/src/Notepads/Program.cs b/src/Notepads/Program.cs index 17f910064..7f133ea86 100644 --- a/src/Notepads/Program.cs +++ b/src/Notepads/Program.cs @@ -7,6 +7,7 @@ using Notepads.Settings; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; + using Windows.Foundation.Metadata; public static class Program { @@ -148,8 +149,10 @@ private static AppInstance GetLastActiveInstance() private static async void OpenExtension() { - - await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); + if (ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0)) + { + await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); + } } } } \ No newline at end of file diff --git a/src/Notepads/Services/InteropService.cs b/src/Notepads/Services/InteropService.cs index 5a210d48f..51185381f 100644 --- a/src/Notepads/Services/InteropService.cs +++ b/src/Notepads/Services/InteropService.cs @@ -2,12 +2,14 @@ { using Notepads.ExtensionService; using Notepads.Settings; + using Notepads.Utilities; using System; using System.Collections.Generic; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.AppService; using Windows.Foundation.Collections; + using Windows.Storage; using Windows.UI.Xaml; public static class InteropService @@ -19,6 +21,9 @@ public static class InteropService public static AppServiceConnection InteropServiceConnection = null; private static ExtensionServiceClient adminExtensionServiceClient = new ExtensionServiceClient(); + public const string ExtensionAccessErrorMessage = "Failed to save due to no Extension access"; + public const string AdminAccessErrorMessage = "Failed to save due to no Adminstration access"; + private static readonly string _commandLabel = "Command"; private static readonly string _appIdLabel = "Instance"; private static readonly string _settingsKeyLabel = "Settings"; @@ -121,20 +126,19 @@ public static async void SyncRecentList() await InteropServiceConnection.SendMessageAsync(message); } - public static async Task ReplaceFile(string newFilePath, string oldFilePath, bool isElevationRequired) + public static async Task ReplaceFile(StorageFile newFile, StorageFile oldFile, bool isElevationRequired) { if (InteropServiceConnection == null) return; + var newFilePath = newFile.Path; + var oldFilePath = oldFile.Path; bool failedFromDesktopExtension = false; bool failedFromAdminExtension = false; if (isElevationRequired) { try { - if (!await adminExtensionServiceClient.ReplaceFileAsync(newFilePath, oldFilePath)) - { - failedFromAdminExtension = true; - } + failedFromAdminExtension = !await adminExtensionServiceClient.ReplaceFileAsync(newFilePath, oldFilePath); } catch { @@ -149,21 +153,27 @@ public static async Task ReplaceFile(string newFilePath, string oldFilePath, boo message.Add(_oldFileLabel, oldFilePath); var response = await InteropServiceConnection.SendMessageAsync(message); - var responseMessage = response.Message; - if (responseMessage.ContainsKey(_failureLabel) && (bool)responseMessage[_failureLabel]) + if (response.Status != AppServiceResponseStatus.Success || + (response.Message.ContainsKey(_failureLabel) && (bool)response.Message[_failureLabel])) { + await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); failedFromDesktopExtension = true; } } + if (await FileSystemUtility.FileExists(newFile)) + { + await newFile.DeleteAsync(StorageDeleteOption.PermanentDelete); + } + if (failedFromDesktopExtension) { - throw new Exception("Failed to save due to no Extension access"); + throw new Exception(ExtensionAccessErrorMessage); } if (failedFromAdminExtension) { - throw new Exception("Failed to save due to no Adminstration access"); + throw new Exception(AdminAccessErrorMessage); } } diff --git a/src/Notepads/Utilities/FileSystemUtility.cs b/src/Notepads/Utilities/FileSystemUtility.cs index 5b8c762d6..c7dac59e5 100644 --- a/src/Notepads/Utilities/FileSystemUtility.cs +++ b/src/Notepads/Utilities/FileSystemUtility.cs @@ -15,6 +15,8 @@ using Windows.Storage.FileProperties; using Windows.Storage.Provider; using UtfUnknown; + using Windows.Foundation.Metadata; + using Windows.ApplicationModel; public static class FileSystemUtility { @@ -461,6 +463,10 @@ public static async Task WriteToFile(string text, Encoding encoding, StorageFile StorageFile oldFile = null; if (IsFileReadOnly(file) || !await FileIsWritable(file)) { + if (!ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0)) + { + throw new Exception(InteropService.ExtensionAccessErrorMessage); + } oldFile = file; file = await SessionUtility.CreateNewFileInBackupFolderAsync(Guid.NewGuid().ToString(), CreationCollisionOption.ReplaceExisting, TempSaveFolderDefaultName); } @@ -477,7 +483,7 @@ public static async Task WriteToFile(string text, Encoding encoding, StorageFile if (oldFile != null) { - await InteropService.ReplaceFile(file.Path, oldFile.Path, IsFileReadOnly(file) ? false : true); + await InteropService.ReplaceFile(file, oldFile, IsFileReadOnly(oldFile) ? false : true); } if (usedDeferUpdates) diff --git a/src/Notepads/Views/NotepadsMainPage.IO.cs b/src/Notepads/Views/NotepadsMainPage.IO.cs index a5d351f9f..f466990d2 100644 --- a/src/Notepads/Views/NotepadsMainPage.IO.cs +++ b/src/Notepads/Views/NotepadsMainPage.IO.cs @@ -145,7 +145,7 @@ private async Task Save(ITextEditor textEditor, bool saveAs, bool ignoreUn } catch (Exception ex) { - if(ex.Message.Equals("Failed to save due to no Adminstration access")) + if(ex.Message.Equals(InteropService.AdminAccessErrorMessage)) { bool result = false; @@ -168,7 +168,7 @@ private async Task Save(ITextEditor textEditor, bool saveAs, bool ignoreUn return result; } - else if(ex.Message.Equals("Failed to save due to no Extension access")) + else if(ex.Message.Equals(InteropService.ExtensionAccessErrorMessage)) { bool result = false; if (!saveAs) result = await Save(textEditor, true, ignoreUnmodifiedDocument, rebuildOpenRecentItems); From bd5392e3b4390030e9a4ab4b31235412a39f053b Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 9 May 2020 01:20:29 +0530 Subject: [PATCH 011/181] fix. --- src/Notepads.DesktopExtension/Program.cs | 36 +++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs index 6892a1ed2..effeffdbf 100644 --- a/src/Notepads.DesktopExtension/Program.cs +++ b/src/Notepads.DesktopExtension/Program.cs @@ -7,6 +7,7 @@ using System.Security.Principal; using System.ServiceModel; using System.Text; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Windows.ApplicationModel; @@ -28,6 +29,10 @@ namespace Notepads.DesktopExtension { static class Program { + private static string DesktopExtensionMutexIdStr = "DesktopExtensionMutexIdStr"; + private static string AdminExtensionMutexIdStr = "AdminExtensionMutexIdStr"; + private static Mutex mutex; + private static AppServiceConnection connection = null; private static readonly string _commandLabel = "Command"; private static readonly string _newFileLabel = "From"; @@ -43,10 +48,12 @@ static void Main(string[] args) { if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) { + CheckInstance(AdminExtensionMutexIdStr); InitializeExtensionService(); } else { + CheckInstance(DesktopExtensionMutexIdStr); InitializeAppServiceConnection(); } @@ -82,6 +89,16 @@ private static void InitializeExtensionService() selfHost.Open(); } + private static void CheckInstance(string key) + { + mutex = new Mutex(true, ReadOrInitializeMutexId(key), out var isFirstInstance); + if (!isFirstInstance) + { + mutex.ReleaseMutex(); + Application.Exit(); + } + } + private static void Connection_ServiceClosed(AppServiceConnection sender, AppServiceClosedEventArgs args) { // connection to the UWP lost, so we shut down the desktop process @@ -120,7 +137,7 @@ private static async void Connection_RequestReceived(AppServiceConnection sender messageDeferral.Complete(); } - public static bool ReplaceFile(string newPath, string oldPath) + private static bool ReplaceFile(string newPath, string oldPath) { try { @@ -146,5 +163,22 @@ private static void CreateElevetedExtension() info.FileName = aliasPath; Process.Start(info); } + + private static string ReadOrInitializeMutexId(string key) + { + ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; + if (!localSettings.Values.ContainsKey(key) || !(localSettings.Values[key] is string mutexId) || string.IsNullOrEmpty(mutexId)) + { + mutexId = Guid.NewGuid().ToString(); + WriteMutexId(key, mutexId); + } + return mutexId; + } + + private static void WriteMutexId(string key, object obj) + { + ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; + localSettings.Values[key] = obj; + } } } From f2fcf77dde213fbeeda3516451ea270037cbb3e7 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sun, 10 May 2020 23:53:45 +0530 Subject: [PATCH 012/181] Exit extensions when app closed. --- src/Notepads.DesktopExtension/AdminService.cs | 5 ----- .../IAdminService.cs | 3 --- src/Notepads.DesktopExtension/Program.cs | 3 ++- .../InteropConnectionService.cs | 2 +- .../AdminService/AdminService.wsdl | 19 ------------------- .../AdminService/AdminService1.xsd | 15 --------------- .../AdminService/Reference.cs | 7 ------- 7 files changed, 3 insertions(+), 51 deletions(-) diff --git a/src/Notepads.DesktopExtension/AdminService.cs b/src/Notepads.DesktopExtension/AdminService.cs index 36fe07bdd..cab9ce369 100644 --- a/src/Notepads.DesktopExtension/AdminService.cs +++ b/src/Notepads.DesktopExtension/AdminService.cs @@ -33,11 +33,6 @@ public bool SaveFile(string filePath, byte[] data) } } - public void Exit() - { - Application.Exit(); - } - private async void WriteToFile(string filePath, byte[] data) { await PathIO.WriteBytesAsync(filePath, data); diff --git a/src/Notepads.DesktopExtension/IAdminService.cs b/src/Notepads.DesktopExtension/IAdminService.cs index 776abc86f..96d76cce4 100644 --- a/src/Notepads.DesktopExtension/IAdminService.cs +++ b/src/Notepads.DesktopExtension/IAdminService.cs @@ -13,8 +13,5 @@ public interface IAdminService { [OperationContract] bool SaveFile(string filePath, byte[] data); - - [OperationContract] - void Exit(); } } diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs index 21b8cbfa3..c046ebc10 100644 --- a/src/Notepads.DesktopExtension/Program.cs +++ b/src/Notepads.DesktopExtension/Program.cs @@ -145,7 +145,8 @@ private static async void CreateElevetedExtension() info.Verb = "runas"; info.UseShellExecute = true; info.FileName = aliasPath; - Process.Start(info); + var process = Process.Start(info); + AppDomain.CurrentDomain.ProcessExit += (a, b) => process.Kill(); message.Add(_adminCreatedLabel, true); } catch diff --git a/src/Notepads.Services/InteropConnectionService.cs b/src/Notepads.Services/InteropConnectionService.cs index a092a1fb1..67ee5c1ce 100644 --- a/src/Notepads.Services/InteropConnectionService.cs +++ b/src/Notepads.Services/InteropConnectionService.cs @@ -134,7 +134,7 @@ private async void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTask this.backgroundTaskDeferral.Complete(); var details = sender.TriggerDetails as AppServiceTriggerDetails; appServiceConnections.Remove(details.AppServiceConnection); - if (appServiceConnections.Count == 0) + if (appServiceConnections.Count == 0 && extensionAppServiceConnection != null) { var message = new ValueSet(); message.Add(_commandLabel, CommandArgs.ExitApp); diff --git a/src/Notepads/Connected Services/AdminService/AdminService.wsdl b/src/Notepads/Connected Services/AdminService/AdminService.wsdl index f0a3d0e77..a08f960ec 100644 --- a/src/Notepads/Connected Services/AdminService/AdminService.wsdl +++ b/src/Notepads/Connected Services/AdminService/AdminService.wsdl @@ -6,12 +6,6 @@ - - - - - - @@ -19,10 +13,6 @@ - - - - @@ -30,15 +20,6 @@ - - - - - - - - - diff --git a/src/Notepads/Connected Services/AdminService/AdminService1.xsd b/src/Notepads/Connected Services/AdminService/AdminService1.xsd index 6c32e6075..58a2bc7a2 100644 --- a/src/Notepads/Connected Services/AdminService/AdminService1.xsd +++ b/src/Notepads/Connected Services/AdminService/AdminService1.xsd @@ -1,20 +1,5 @@ - - - - - - - - - - - - - - - diff --git a/src/Notepads/Connected Services/AdminService/Reference.cs b/src/Notepads/Connected Services/AdminService/Reference.cs index 202c387f0..960f0a68c 100644 --- a/src/Notepads/Connected Services/AdminService/Reference.cs +++ b/src/Notepads/Connected Services/AdminService/Reference.cs @@ -18,9 +18,6 @@ namespace Notepads.AdminService { [System.ServiceModel.ServiceContractAttribute(ConfigurationName="AdminService.IAdminService")] public interface IAdminService { - [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IAdminService/ReplaceFile", ReplyAction="http://tempuri.org/IAdminService/ReplaceFileResponse")] - System.Threading.Tasks.Task ReplaceFileAsync(string newPath, string oldPath); - [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IAdminService/SaveFile", ReplyAction="http://tempuri.org/IAdminService/SaveFileResponse")] System.Threading.Tasks.Task SaveFileAsync(string filePath, byte[] data); } @@ -68,10 +65,6 @@ public AdminServiceClient(System.ServiceModel.Channels.Binding binding, System.S base(binding, remoteAddress) { } - public System.Threading.Tasks.Task ReplaceFileAsync(string newPath, string oldPath) { - return base.Channel.ReplaceFileAsync(newPath, oldPath); - } - public System.Threading.Tasks.Task SaveFileAsync(string filePath, byte[] data) { return base.Channel.SaveFileAsync(filePath, data); } From 4a022c97b517b94b4ade6bb1252756fe48c87fdf Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Mon, 11 May 2020 14:41:33 +0530 Subject: [PATCH 013/181] Fully implemented saving system file as admin. --- src/Notepads.DesktopExtension/AdminService.cs | 9 ++------- src/Notepads.DesktopExtension/IAdminService.cs | 3 ++- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/src/Notepads.DesktopExtension/AdminService.cs b/src/Notepads.DesktopExtension/AdminService.cs index cab9ce369..2e62d45f9 100644 --- a/src/Notepads.DesktopExtension/AdminService.cs +++ b/src/Notepads.DesktopExtension/AdminService.cs @@ -16,7 +16,7 @@ public class AdminService : IAdminService { internal static string AdminAuthenticationTokenStr = "AdminAuthenticationTokenStr"; - public bool SaveFile(string filePath, byte[] data) + public async Task SaveFile(string filePath, byte[] data) { try { @@ -24,7 +24,7 @@ public bool SaveFile(string filePath, byte[] data) if (!localSettings.Values.ContainsKey(AdminAuthenticationTokenStr) || !(localSettings.Values[AdminAuthenticationTokenStr] is string token)) return false; localSettings.Values.Remove(AdminAuthenticationTokenStr); - WriteToFile(filePath, data); + await PathIO.WriteBytesAsync(filePath, data); return true; } catch (Exception) @@ -32,10 +32,5 @@ public bool SaveFile(string filePath, byte[] data) return false; } } - - private async void WriteToFile(string filePath, byte[] data) - { - await PathIO.WriteBytesAsync(filePath, data); - } } } diff --git a/src/Notepads.DesktopExtension/IAdminService.cs b/src/Notepads.DesktopExtension/IAdminService.cs index 96d76cce4..7428a5a80 100644 --- a/src/Notepads.DesktopExtension/IAdminService.cs +++ b/src/Notepads.DesktopExtension/IAdminService.cs @@ -4,6 +4,7 @@ using System.Runtime.Serialization; using System.ServiceModel; using System.Text; +using System.Threading.Tasks; namespace Notepads.DesktopExtension { @@ -12,6 +13,6 @@ namespace Notepads.DesktopExtension public interface IAdminService { [OperationContract] - bool SaveFile(string filePath, byte[] data); + Task SaveFile(string filePath, byte[] data); } } From b023c5859887d899a9a838acdf1ff724f7207e2a Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Mon, 11 May 2020 15:14:08 +0530 Subject: [PATCH 014/181] Made code more readable. --- src/Notepads.DesktopExtension/AdminService.cs | 17 ++----- .../IAdminService.cs | 14 ++---- src/Notepads.DesktopExtension/Program.cs | 48 ++++++++----------- .../InteropConnectionService.cs | 3 -- src/Notepads/Services/InteropService.cs | 2 - src/Notepads/Utilities/FileSystemUtility.cs | 1 - 6 files changed, 31 insertions(+), 54 deletions(-) diff --git a/src/Notepads.DesktopExtension/AdminService.cs b/src/Notepads.DesktopExtension/AdminService.cs index 2e62d45f9..137604fc1 100644 --- a/src/Notepads.DesktopExtension/AdminService.cs +++ b/src/Notepads.DesktopExtension/AdminService.cs @@ -1,16 +1,9 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Runtime.Serialization; -using System.ServiceModel; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; -using Windows.Storage; - -namespace Notepads.DesktopExtension +namespace Notepads.DesktopExtension { + using System; + using System.Threading.Tasks; + using Windows.Storage; + // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "AdminService" in both code and config file together. public class AdminService : IAdminService { diff --git a/src/Notepads.DesktopExtension/IAdminService.cs b/src/Notepads.DesktopExtension/IAdminService.cs index 7428a5a80..a1e69b306 100644 --- a/src/Notepads.DesktopExtension/IAdminService.cs +++ b/src/Notepads.DesktopExtension/IAdminService.cs @@ -1,13 +1,9 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.Serialization; -using System.ServiceModel; -using System.Text; -using System.Threading.Tasks; - -namespace Notepads.DesktopExtension +namespace Notepads.DesktopExtension { + using System.Runtime.Serialization; + using System.ServiceModel; + using System.Threading.Tasks; + // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IAdminService" in both code and config file together. [ServiceContract] public interface IAdminService diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs index c046ebc10..72aeda674 100644 --- a/src/Notepads.DesktopExtension/Program.cs +++ b/src/Notepads.DesktopExtension/Program.cs @@ -1,32 +1,26 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Security.Principal; -using System.ServiceModel; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using System.Windows.Forms; -using Windows.ApplicationModel; -using Windows.ApplicationModel.Activation; -using Windows.ApplicationModel.AppService; -using Windows.Foundation.Collections; -using Windows.Storage; - -public enum CommandArgs +namespace Notepads.DesktopExtension { - SyncSettings, - SyncRecentList, - RegisterExtension, - CreateElevetedExtension, - ExitApp -} + using System; + using System.Diagnostics; + using System.Reflection; + using System.Security.Principal; + using System.ServiceModel; + using System.Threading; + using System.Windows.Forms; + using Windows.ApplicationModel; + using Windows.ApplicationModel.AppService; + using Windows.Foundation.Collections; + using Windows.Storage; + + public enum CommandArgs + { + SyncSettings, + SyncRecentList, + RegisterExtension, + CreateElevetedExtension, + ExitApp + } -namespace Notepads.DesktopExtension -{ static class Program { private static string DesktopExtensionMutexIdStr = "DesktopExtensionMutexIdStr"; diff --git a/src/Notepads.Services/InteropConnectionService.cs b/src/Notepads.Services/InteropConnectionService.cs index 67ee5c1ce..26d36077c 100644 --- a/src/Notepads.Services/InteropConnectionService.cs +++ b/src/Notepads.Services/InteropConnectionService.cs @@ -2,7 +2,6 @@ { using System; using System.Collections.Generic; - using System.Text; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.AppService; @@ -22,7 +21,6 @@ public sealed class InteropConnectionService : IBackgroundTask { private BackgroundTaskDeferral backgroundTaskDeferral; private AppServiceConnection appServiceConnection; - private static BackgroundTaskDeferral extensionBackgroundTaskDeferral; private static AppServiceConnection extensionAppServiceConnection = null; private static IList appServiceConnections = new List(); @@ -82,7 +80,6 @@ private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequ if (extensionAppServiceConnection == null) { extensionAppServiceConnection = appServiceConnection; - extensionBackgroundTaskDeferral = this.backgroundTaskDeferral; } else { diff --git a/src/Notepads/Services/InteropService.cs b/src/Notepads/Services/InteropService.cs index 5d665349d..a72caac6b 100644 --- a/src/Notepads/Services/InteropService.cs +++ b/src/Notepads/Services/InteropService.cs @@ -3,7 +3,6 @@ using Notepads.AdminService; using Notepads.Extensions; using Notepads.Settings; - using Notepads.Utilities; using System; using System.Collections.Generic; using System.Threading.Tasks; @@ -11,7 +10,6 @@ using Windows.ApplicationModel.AppService; using Windows.ApplicationModel.Resources; using Windows.Foundation.Collections; - using Windows.Storage; using Windows.UI.Xaml; public static class InteropService diff --git a/src/Notepads/Utilities/FileSystemUtility.cs b/src/Notepads/Utilities/FileSystemUtility.cs index 078154a4e..152bb7deb 100644 --- a/src/Notepads/Utilities/FileSystemUtility.cs +++ b/src/Notepads/Utilities/FileSystemUtility.cs @@ -16,7 +16,6 @@ using Windows.Storage.Provider; using UtfUnknown; using Windows.Foundation.Metadata; - using Windows.ApplicationModel; public static class FileSystemUtility { From 2ddfbcf9f06a2e38bcde6648a106fc854a5b1f5e Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Mon, 11 May 2020 17:04:49 +0530 Subject: [PATCH 015/181] fix. --- src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs index fd22ff3bd..a122db7ae 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs @@ -305,7 +305,6 @@ private async void App_LeavingBackground(object sender, LeavingBackgroundEventAr { ThemeSettingsService.UpdateAllSettings(); AppSettingsService.UpdateAllSettings(); - EditorSettingsService.UpdateAllSettings(); await BuildOpenRecentButtonSubItems(false); InteropService.Initialize(); } From 368eda716184dfdb4886acd88b8727e61577bb7a Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Mon, 11 May 2020 18:57:46 +0530 Subject: [PATCH 016/181] Updated branch. --- src/Notepads.DesktopExtension/Program.cs | 2 +- src/Notepads.Package/Package.appxmanifest | 14 +- .../InteropConnectionService.cs | 14 +- .../Notepads.Services.csproj | 2 +- src/Notepads/Notepads.csproj | 2 - src/Notepads/Package.appxmanifest | 529 ------------------ src/Notepads/Program.cs | 2 +- src/Notepads/Services/InteropService.cs | 16 +- 8 files changed, 27 insertions(+), 554 deletions(-) diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs index 72aeda674..7c586d884 100644 --- a/src/Notepads.DesktopExtension/Program.cs +++ b/src/Notepads.DesktopExtension/Program.cs @@ -46,7 +46,7 @@ static void Main(string[] args) { CheckInstance(DesktopExtensionMutexIdStr); InitializeAppServiceConnection(); - if (args[2] == "/admin") CreateElevetedExtension(); + if (args.Length > 2 && args[2] == "/admin") CreateElevetedExtension(); } Application.Run(); diff --git a/src/Notepads.Package/Package.appxmanifest b/src/Notepads.Package/Package.appxmanifest index c1581bd3b..ed2e3e39b 100644 --- a/src/Notepads.Package/Package.appxmanifest +++ b/src/Notepads.Package/Package.appxmanifest @@ -15,7 +15,7 @@ + Version="1.3.3.0" /> @@ -565,7 +565,7 @@ - + .zshrc @@ -595,6 +595,16 @@ + + + + .v + + ms-resource:Manifest/VerilogFileDisplayName + Assets\FileIcons\file.png + + + diff --git a/src/Notepads.Services/InteropConnectionService.cs b/src/Notepads.Services/InteropConnectionService.cs index 26d36077c..86f9cbed5 100644 --- a/src/Notepads.Services/InteropConnectionService.cs +++ b/src/Notepads.Services/InteropConnectionService.cs @@ -62,18 +62,16 @@ private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequ switch (command) { case CommandArgs.SyncSettings: - foreach (var serviceConnection in appServiceConnections) + Parallel.ForEach(appServiceConnections, async (serviceConnection) => { - if (serviceConnection != appServiceConnection) - await serviceConnection.SendMessageAsync(args.Request.Message); - } + if (serviceConnection != appServiceConnection) await serviceConnection.SendMessageAsync(args.Request.Message); + }); break; case CommandArgs.SyncRecentList: - foreach (var serviceConnection in appServiceConnections) + Parallel.ForEach(appServiceConnections, async (serviceConnection) => { - if (serviceConnection != appServiceConnection) - await serviceConnection.SendMessageAsync(args.Request.Message); - } + if (serviceConnection != appServiceConnection) await serviceConnection.SendMessageAsync(args.Request.Message); + }); break; case CommandArgs.RegisterExtension: appServiceConnections.Remove(appServiceConnection); diff --git a/src/Notepads.Services/Notepads.Services.csproj b/src/Notepads.Services/Notepads.Services.csproj index cfcfb9a82..1c6074764 100644 --- a/src/Notepads.Services/Notepads.Services.csproj +++ b/src/Notepads.Services/Notepads.Services.csproj @@ -126,7 +126,7 @@ - 6.2.9 + 6.2.10 diff --git a/src/Notepads/Notepads.csproj b/src/Notepads/Notepads.csproj index 688ad837d..c5ac5e7a5 100644 --- a/src/Notepads/Notepads.csproj +++ b/src/Notepads/Notepads.csproj @@ -139,8 +139,6 @@ AboutPage.xaml - - AdvancedSettingsPage.xaml diff --git a/src/Notepads/Package.appxmanifest b/src/Notepads/Package.appxmanifest index 8cfa114df..85c500937 100644 --- a/src/Notepads/Package.appxmanifest +++ b/src/Notepads/Package.appxmanifest @@ -68,535 +68,6 @@ - - - - .txt - - ms-resource:Manifest/TextFileDisplayName - - Assets\FileIcons\txt.png - - - - - - - - - .cfg - .config - .cnf - .conf - - ms-resource:Manifest/ConfigFileDisplayName - Assets\FileIcons\cfg.png - - - - - - - .ini - - ms-resource:Manifest/InitializationFileDisplayName - Assets\FileIcons\ini.png - - - - - - - .md - .markdown - - ms-resource:Manifest/MarkdownFileDisplayName - Assets\FileIcons\md.png - - - - - - - .log - - ms-resource:Manifest/LogFileDisplayName - Assets\FileIcons\log.png - - - - - - - .bib - - ms-resource:Manifest/BibTeXFileDisplayName - Assets\FileIcons\bib.png - - - - - - - .json - - ms-resource:Manifest/JsonFileDisplayName - Assets\FileIcons\json.png - - - - - - - .yml - .yaml - - ms-resource:Manifest/YamlFileDisplayName - Assets\FileIcons\yml.png - - - - - - - .xml - - ms-resource:Manifest/XmlFileDisplayName - Assets\FileIcons\xml.png - - - - - - - .html - .htm - - ms-resource:Manifest/HtmlFileDisplayName - Assets\FileIcons\html.png - - - - - - - .asp - .aspx - - ms-resource:Manifest/AspFileDisplayName - Assets\FileIcons\asp.png - - - - - - - .jsp - .jspx - - ms-resource:Manifest/JspFileDisplayName - Assets\FileIcons\jsp.png - - - - - - - .css - .scss - - ms-resource:Manifest/CssFileDisplayName - Assets\FileIcons\css.png - - - - - - - .sh - - ms-resource:Manifest/ShellScriptFileDisplayName - Assets\FileIcons\sh.png - - - - - - - .bashrc - .vimrc - .rc - - ms-resource:Manifest/RunCommandsFileDisplayName - Assets\FileIcons\rc.png - - - - - - - .bash - - ms-resource:Manifest/BashScriptFileDisplayName - Assets\FileIcons\bash.png - - - - - - - .js - - ms-resource:Manifest/JavascriptFileDisplayName - Assets\FileIcons\js.png - - - - - - - .ts - - ms-resource:Manifest/TypeScriptFileDisplayName - Assets\FileIcons\file.png - - - - - - - .lua - - ms-resource:Manifest/LuaFileDisplayName - Assets\FileIcons\file.png - - - - - - - .c - .m - - ms-resource:Manifest/CFileDisplayName - Assets\FileIcons\c.png - - - - - - - .cc - .mm - .cpp - - ms-resource:Manifest/CppFileDisplayName - Assets\FileIcons\cpp.png - - - - - - - .h - .hpp - - ms-resource:Manifest/HeaderFileDisplayName - Assets\FileIcons\h.png - - - - - - - .cmake - - ms-resource:Manifest/CmakeFileDisplayName - Assets\FileIcons\file.png - - - - - - - .cs - - ms-resource:Manifest/CSharpFileDisplayName - Assets\FileIcons\cs.png - - - - - - - .php - - ms-resource:Manifest/PhpFileDisplayName - Assets\FileIcons\php.png - - - - - - - .py - - ms-resource:Manifest/PythonFileDisplayName - Assets\FileIcons\py.png - - - - - - - .rb - - ms-resource:Manifest/RubyFileDisplayName - - Assets\FileIcons\rb.png - - - - - - .java - - ms-resource:Manifest/JavaFileDisplayName - Assets\FileIcons\java.png - - - - - - - .vb - - ms-resource:Manifest/VisualBasicFileDisplayName - Assets\FileIcons\vb.png - - - - - - - .go - - ms-resource:Manifest/GoFileDisplayName - Assets\FileIcons\file.png - - - - - - - .srt - - ms-resource:Manifest/SubtitleFileDisplayName - Assets\FileIcons\srt.png - - - - - - - .ass - - ms-resource:Manifest/AegisubAdvancedSubtitleFileDisplayName - Assets\FileIcons\ass.png - - - - - - - .ssa - - ms-resource:Manifest/SubStationAlphaSubtitleFileDisplayName - Assets\FileIcons\ssa.png - - - - - - - .vue - - ms-resource:Manifest/VueFileDisplayName - Assets\FileIcons\vue.png - - - - - - - .vuerc - - ms-resource:Manifest/VueConfigFileDisplayName - Assets\FileIcons\vue.png - - - - - - - .gitconfig - - ms-resource:Manifest/GitConfigFileDisplayName - Assets\FileIcons\file.png - - - - - - - .gitignore - - ms-resource:Manifest/GitIgnoreFileDisplayName - Assets\FileIcons\file.png - - - - - - - .gitattributes - - ms-resource:Manifest/GitAttributesFileDisplayName - Assets\FileIcons\file.png - - - - - - - .project - .prj - - ms-resource:Manifest/ProjectFileDisplayName - Assets\FileIcons\file.png - - - - - - - .npmrc - - ms-resource:Manifest/NpmConfigFileDisplayName - Assets\FileIcons\file.png - - - - - - - .bash_history - - ms-resource:Manifest/BashHistoryFileDisplayName - Assets\FileIcons\file.png - - - - - - - .cgi - - ms-resource:Manifest/CgiFileDisplayName - Assets\FileIcons\file.png - - - - - - - .pl - - ms-resource:Manifest/PerlFileDisplayName - Assets\FileIcons\perl.png - - - - - - - .buildpath - - ms-resource:Manifest/BuildPathFileDisplayName - Assets\FileIcons\file.png - - - - - - - .sql - - ms-resource:Manifest/SqlFileDisplayName - Assets\FileIcons\sql.png - - - - - - - .nfo - - ms-resource:Manifest/NfoFileDisplayName - Assets\FileIcons\file.png - - - - - - - .ahk - - ms-resource:Manifest/AutoHotkeyScriptFileDisplayName - Assets\FileIcons\file.png - - - - - - - .zshrc - - ms-resource:Manifest/ZshellConfigFileDisplayName - Assets\FileIcons\file.png - - - - - - - .zsh_history - - ms-resource:Manifest/ZshellHistoryFileDisplayName - Assets\FileIcons\file.png - - - - - - - .lrc - - ms-resource:Manifest/LrcFileDisplayName - Assets\FileIcons\file.png - - - - - - - .v - - ms-resource:Manifest/VerilogFileDisplayName - Assets\FileIcons\file.png - - - diff --git a/src/Notepads/Program.cs b/src/Notepads/Program.cs index 94f675513..0a5c30e2e 100644 --- a/src/Notepads/Program.cs +++ b/src/Notepads/Program.cs @@ -151,7 +151,7 @@ private static async void OpenExtension() { if (ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0)) { - await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync("Launch"); + await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); } } } diff --git a/src/Notepads/Services/InteropService.cs b/src/Notepads/Services/InteropService.cs index 3814ab03b..592658970 100644 --- a/src/Notepads/Services/InteropService.cs +++ b/src/Notepads/Services/InteropService.cs @@ -25,7 +25,6 @@ public static class InteropService private static readonly string _commandLabel = "Command"; private static readonly string _failedLabel = "Failed"; - private static readonly string _appIdLabel = "Instance"; private static readonly string _settingsKeyLabel = "Settings"; private static readonly string _valueLabel = "Value"; private static readonly string _adminCreatedLabel = "AdminCreated"; @@ -78,15 +77,12 @@ private static async void InteropServiceConnection_RequestReceived(AppServiceCon switch(command) { case CommandArgs.SyncSettings: - if (message.ContainsKey(_appIdLabel) && message[_appIdLabel] is Guid appID && appID != App.Id) - { - EnableSettingsLogging = false; - HideSettingsPane?.Invoke(null, true); - var settingsKey = message[_settingsKeyLabel] as string; - var value = message[_valueLabel] as object; - SettingsManager[settingsKey](value); - EnableSettingsLogging = true; - } + EnableSettingsLogging = false; + HideSettingsPane?.Invoke(null, true); + var settingsKey = message[_settingsKeyLabel] as string; + var value = message[_valueLabel] as object; + SettingsManager[settingsKey](value); + EnableSettingsLogging = true; break; case CommandArgs.SyncRecentList: UpdateRecentList?.Invoke(null, false); From e8158f43acaa1e4da6bac12ea017e0ea118b4168 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Mon, 11 May 2020 19:22:00 +0530 Subject: [PATCH 017/181] fix --- .github/workflows/Build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 2da93f80a..5a1b1d3e3 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -11,7 +11,7 @@ jobs: configuration: [Debug, Release] env: Solution_Name: src\Notepads.sln - Project_Path: src\Notepads\Notepads.csproj + Project_Path: src\Notepads.Package\Notepads.Package.wapproj runs-on: windows-latest steps: From 6339e8a873b634140288130276c387ef4e115bb3 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Mon, 11 May 2020 23:59:08 +0530 Subject: [PATCH 018/181] fix. --- src/Notepads.Services/InteropConnectionService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Notepads.Services/InteropConnectionService.cs b/src/Notepads.Services/InteropConnectionService.cs index 86f9cbed5..1270d200c 100644 --- a/src/Notepads.Services/InteropConnectionService.cs +++ b/src/Notepads.Services/InteropConnectionService.cs @@ -132,7 +132,7 @@ private async void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTask if (appServiceConnections.Count == 0 && extensionAppServiceConnection != null) { var message = new ValueSet(); - message.Add(_commandLabel, CommandArgs.ExitApp); + message.Add(_commandLabel, CommandArgs.ExitApp.ToString()); await extensionAppServiceConnection.SendMessageAsync(message); } } From 860d86663945d41958b90ec6ba4ea091b0a16f9c Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Tue, 12 May 2020 00:13:25 +0530 Subject: [PATCH 019/181] fix. --- .../InteropConnectionService.cs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/Notepads.Services/InteropConnectionService.cs b/src/Notepads.Services/InteropConnectionService.cs index 1270d200c..f53ba23a2 100644 --- a/src/Notepads.Services/InteropConnectionService.cs +++ b/src/Notepads.Services/InteropConnectionService.cs @@ -128,12 +128,20 @@ private async void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTask // Complete the service deferral. this.backgroundTaskDeferral.Complete(); var details = sender.TriggerDetails as AppServiceTriggerDetails; - appServiceConnections.Remove(details.AppServiceConnection); - if (appServiceConnections.Count == 0 && extensionAppServiceConnection != null) + var serviceConnection = details.AppServiceConnection; + if (serviceConnection == extensionAppServiceConnection) { - var message = new ValueSet(); - message.Add(_commandLabel, CommandArgs.ExitApp.ToString()); - await extensionAppServiceConnection.SendMessageAsync(message); + extensionAppServiceConnection = null; + } + else + { + appServiceConnections.Remove(serviceConnection); + if (appServiceConnections.Count == 0 && extensionAppServiceConnection != null) + { + var message = new ValueSet(); + message.Add(_commandLabel, CommandArgs.ExitApp.ToString()); + await extensionAppServiceConnection.SendMessageAsync(message); + } } } } From 122655cda8a07f7165d8bff117faf77deba727ec Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Tue, 12 May 2020 12:10:49 +0530 Subject: [PATCH 020/181] fix. --- src/Notepads.DesktopExtension/AdminService.cs | 5 +++++ .../IAdminService.cs | 3 +++ .../AdminService/AdminService.wsdl | 19 +++++++++++++++++++ .../AdminService/AdminService1.xsd | 12 ++++++++++++ .../AdminService/Reference.cs | 7 +++++++ src/Notepads/Services/InteropService.cs | 7 +++++-- 6 files changed, 51 insertions(+), 2 deletions(-) diff --git a/src/Notepads.DesktopExtension/AdminService.cs b/src/Notepads.DesktopExtension/AdminService.cs index 137604fc1..8a2b0740b 100644 --- a/src/Notepads.DesktopExtension/AdminService.cs +++ b/src/Notepads.DesktopExtension/AdminService.cs @@ -25,5 +25,10 @@ public async Task SaveFile(string filePath, byte[] data) return false; } } + + public bool IsLive() + { + return true; + } } } diff --git a/src/Notepads.DesktopExtension/IAdminService.cs b/src/Notepads.DesktopExtension/IAdminService.cs index a1e69b306..b6d6a499e 100644 --- a/src/Notepads.DesktopExtension/IAdminService.cs +++ b/src/Notepads.DesktopExtension/IAdminService.cs @@ -10,5 +10,8 @@ public interface IAdminService { [OperationContract] Task SaveFile(string filePath, byte[] data); + + [OperationContract] + bool IsLive(); } } diff --git a/src/Notepads/Connected Services/AdminService/AdminService.wsdl b/src/Notepads/Connected Services/AdminService/AdminService.wsdl index a08f960ec..d255bdfd0 100644 --- a/src/Notepads/Connected Services/AdminService/AdminService.wsdl +++ b/src/Notepads/Connected Services/AdminService/AdminService.wsdl @@ -12,11 +12,21 @@ + + + + + + + + + + @@ -29,6 +39,15 @@ + + + + + + + + + diff --git a/src/Notepads/Connected Services/AdminService/AdminService1.xsd b/src/Notepads/Connected Services/AdminService/AdminService1.xsd index 58a2bc7a2..22381e294 100644 --- a/src/Notepads/Connected Services/AdminService/AdminService1.xsd +++ b/src/Notepads/Connected Services/AdminService/AdminService1.xsd @@ -15,4 +15,16 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Notepads/Connected Services/AdminService/Reference.cs b/src/Notepads/Connected Services/AdminService/Reference.cs index 960f0a68c..7088f8148 100644 --- a/src/Notepads/Connected Services/AdminService/Reference.cs +++ b/src/Notepads/Connected Services/AdminService/Reference.cs @@ -20,6 +20,9 @@ public interface IAdminService { [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IAdminService/SaveFile", ReplyAction="http://tempuri.org/IAdminService/SaveFileResponse")] System.Threading.Tasks.Task SaveFileAsync(string filePath, byte[] data); + + [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IAdminService/IsLive", ReplyAction="http://tempuri.org/IAdminService/IsLiveResponse")] + System.Threading.Tasks.Task IsLiveAsync(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] @@ -69,6 +72,10 @@ public System.Threading.Tasks.Task SaveFileAsync(string filePath, byte[] d return base.Channel.SaveFileAsync(filePath, data); } + public System.Threading.Tasks.Task IsLiveAsync() { + return base.Channel.IsLiveAsync(); + } + public virtual System.Threading.Tasks.Task OpenAsync() { return System.Threading.Tasks.Task.Factory.FromAsync(((System.ServiceModel.ICommunicationObject)(this)).BeginOpen(null, null), new System.Action(((System.ServiceModel.ICommunicationObject)(this)).EndOpen)); } diff --git a/src/Notepads/Services/InteropService.cs b/src/Notepads/Services/InteropService.cs index 592658970..df23dfe2a 100644 --- a/src/Notepads/Services/InteropService.cs +++ b/src/Notepads/Services/InteropService.cs @@ -144,8 +144,11 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) try { - ApplicationSettingsStore.Write(SettingsKey.AdminAuthenticationTokenStr, Guid.NewGuid().ToString()); - failedFromAdminExtension = !await AdminServiceClient.SaveFileAsync(filePath, data); + if (await AdminServiceClient.IsLiveAsync()) + { + ApplicationSettingsStore.Write(SettingsKey.AdminAuthenticationTokenStr, Guid.NewGuid().ToString()); + failedFromAdminExtension = !await AdminServiceClient.SaveFileAsync(filePath, data); + } } catch { From 894fcb2a3ea84cc79196684f65617022f7824409 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Tue, 12 May 2020 16:30:41 +0530 Subject: [PATCH 021/181] fix. --- src/Notepads.DesktopExtension/Properties/AssemblyInfo.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Notepads.DesktopExtension/Properties/AssemblyInfo.cs b/src/Notepads.DesktopExtension/Properties/AssemblyInfo.cs index 433d83b97..9bb66f976 100644 --- a/src/Notepads.DesktopExtension/Properties/AssemblyInfo.cs +++ b/src/Notepads.DesktopExtension/Properties/AssemblyInfo.cs @@ -5,12 +5,12 @@ // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("Notepads.DesktopExtension")] -[assembly: AssemblyDescription("")] +[assembly: AssemblyTitle("Notepads")] +[assembly: AssemblyDescription("Notepads")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Notepads.DesktopExtension")] -[assembly: AssemblyCopyright("Copyright © 2020")] +[assembly: AssemblyProduct("Notepads")] +[assembly: AssemblyCopyright("Copyright © 2020 Jackie Liu")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] From 6abfdb9609c206790f6fe057b6220d92aca452c1 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 15 May 2020 10:18:44 +0530 Subject: [PATCH 022/181] refinement. --- src/Notepads/Notepads.csproj | 2 +- src/Notepads/Services/InteropService.cs | 46 +++--- src/Notepads/Services/SettingsSyncService.cs | 130 +++++++++++++++ src/Notepads/Settings/SettingsDelegate.cs | 156 ------------------ .../Views/MainPage/NotepadsMainPage.xaml.cs | 2 +- 5 files changed, 155 insertions(+), 181 deletions(-) create mode 100644 src/Notepads/Services/SettingsSyncService.cs delete mode 100644 src/Notepads/Settings/SettingsDelegate.cs diff --git a/src/Notepads/Notepads.csproj b/src/Notepads/Notepads.csproj index c5ac5e7a5..0006e9cb1 100644 --- a/src/Notepads/Notepads.csproj +++ b/src/Notepads/Notepads.csproj @@ -134,7 +134,7 @@ - + AboutPage.xaml diff --git a/src/Notepads/Services/InteropService.cs b/src/Notepads/Services/InteropService.cs index df23dfe2a..5942928d8 100644 --- a/src/Notepads/Services/InteropService.cs +++ b/src/Notepads/Services/InteropService.cs @@ -29,29 +29,29 @@ public static class InteropService private static readonly string _valueLabel = "Value"; private static readonly string _adminCreatedLabel = "AdminCreated"; - private static IReadOnlyDictionary SettingsManager = new Dictionary + private static IReadOnlyDictionary> SettingsManager = new Dictionary> { - {SettingsKey.AlwaysOpenNewWindowBool, SettingsDelegate.AlwaysOpenNewWindow}, - {SettingsKey.AppAccentColorHexStr, SettingsDelegate.AppAccentColor}, - {SettingsKey.AppBackgroundTintOpacityDouble, SettingsDelegate.AppBackgroundPanelTintOpacity}, - {SettingsKey.CustomAccentColorHexStr, SettingsDelegate.CustomAccentColor}, - {SettingsKey.EditorCustomMadeSearchUrlStr, SettingsDelegate.EditorCustomMadeSearchUrl}, - {SettingsKey.EditorDefaultDecodingCodePageInt, SettingsDelegate.EditorDefaultDecoding}, - {SettingsKey.EditorDefaultEncodingCodePageInt, SettingsDelegate.EditorDefaultEncoding}, - {SettingsKey.EditorDefaultLineEndingStr, SettingsDelegate.EditorDefaultLineEnding}, - {SettingsKey.EditorDefaultLineHighlighterViewStateBool, SettingsDelegate.EditorDisplayLineHighlighter}, - {SettingsKey.EditorDefaultDisplayLineNumbersBool, SettingsDelegate.EditorDisplayLineNumbers}, - {SettingsKey.EditorDefaultSearchEngineStr, SettingsDelegate.EditorDefaultSearchEngine}, - {SettingsKey.EditorDefaultTabIndentsInt, SettingsDelegate.EditorDefaultTabIndents}, - {SettingsKey.EditorDefaultTextWrappingStr, SettingsDelegate.EditorDefaultTextWrapping}, - {SettingsKey.EditorFontFamilyStr, SettingsDelegate.EditorFontFamily}, - {SettingsKey.EditorFontSizeInt, SettingsDelegate.EditorFontSize}, - {SettingsKey.EditorFontStyleStr, SettingsDelegate.EditorFontStyle}, - {SettingsKey.EditorFontWeightUshort, SettingsDelegate.EditorFontWeight}, - {SettingsKey.EditorHighlightMisspelledWordsBool, SettingsDelegate.IsHighlightMisspelledWordsEnabled}, - {SettingsKey.EditorShowStatusBarBool, SettingsDelegate.ShowStatusBar}, - {SettingsKey.UseWindowsAccentColorBool, SettingsDelegate.UseWindowsAccentColor}, - {SettingsKey.RequestedThemeStr, SettingsDelegate.ThemeMode} + {SettingsKey.AlwaysOpenNewWindowBool, SettingsSyncService.AlwaysOpenNewWindow}, + {SettingsKey.AppAccentColorHexStr, SettingsSyncService.AppAccentColor}, + {SettingsKey.AppBackgroundTintOpacityDouble, SettingsSyncService.AppBackgroundPanelTintOpacity}, + {SettingsKey.CustomAccentColorHexStr, SettingsSyncService.CustomAccentColor}, + {SettingsKey.EditorCustomMadeSearchUrlStr, SettingsSyncService.EditorCustomMadeSearchUrl}, + {SettingsKey.EditorDefaultDecodingCodePageInt, SettingsSyncService.EditorDefaultDecoding}, + {SettingsKey.EditorDefaultEncodingCodePageInt, SettingsSyncService.EditorDefaultEncoding}, + {SettingsKey.EditorDefaultLineEndingStr, SettingsSyncService.EditorDefaultLineEnding}, + {SettingsKey.EditorDefaultLineHighlighterViewStateBool, SettingsSyncService.EditorDisplayLineHighlighter}, + {SettingsKey.EditorDefaultDisplayLineNumbersBool, SettingsSyncService.EditorDisplayLineNumbers}, + {SettingsKey.EditorDefaultSearchEngineStr, SettingsSyncService.EditorDefaultSearchEngine}, + {SettingsKey.EditorDefaultTabIndentsInt, SettingsSyncService.EditorDefaultTabIndents}, + {SettingsKey.EditorDefaultTextWrappingStr, SettingsSyncService.EditorDefaultTextWrapping}, + {SettingsKey.EditorFontFamilyStr, SettingsSyncService.EditorFontFamily}, + {SettingsKey.EditorFontSizeInt, SettingsSyncService.EditorFontSize}, + {SettingsKey.EditorFontStyleStr, SettingsSyncService.EditorFontStyle}, + {SettingsKey.EditorFontWeightUshort, SettingsSyncService.EditorFontWeight}, + {SettingsKey.EditorHighlightMisspelledWordsBool, SettingsSyncService.IsHighlightMisspelledWordsEnabled}, + {SettingsKey.EditorShowStatusBarBool, SettingsSyncService.ShowStatusBar}, + {SettingsKey.UseWindowsAccentColorBool, SettingsSyncService.UseWindowsAccentColor}, + {SettingsKey.RequestedThemeStr, SettingsSyncService.ThemeMode} }; public static async void Initialize() @@ -88,7 +88,7 @@ private static async void InteropServiceConnection_RequestReceived(AppServiceCon UpdateRecentList?.Invoke(null, false); break; case CommandArgs.CreateElevetedExtension: - await DispatcherExtensions.CallOnUIThreadAsync(SettingsDelegate.Dispatcher, () => + await DispatcherExtensions.CallOnUIThreadAsync(SettingsSyncService.Dispatcher, () => { if (message.ContainsKey(_adminCreatedLabel) && (bool)message[_adminCreatedLabel]) { diff --git a/src/Notepads/Services/SettingsSyncService.cs b/src/Notepads/Services/SettingsSyncService.cs new file mode 100644 index 000000000..51c3d7085 --- /dev/null +++ b/src/Notepads/Services/SettingsSyncService.cs @@ -0,0 +1,130 @@ +namespace Notepads.Services +{ + using Microsoft.Toolkit.Uwp.Helpers; + using Notepads.Utilities; + using System; + using Windows.UI.Core; + using Windows.UI.Text; + using Windows.UI.Xaml; + + public static class SettingsSyncService + { + public static CoreDispatcher Dispatcher; + + public static Action EditorFontFamily = (value) => + { + AppSettingsService.EditorFontFamily = (string)value; + }; + + public static Action EditorFontSize = (value) => + { + AppSettingsService.EditorFontSize = (int)value; + }; + + public static Action EditorFontStyle = (value) => + { + Enum.TryParse(typeof(FontStyle), (string)value, out var result); + AppSettingsService.EditorFontStyle = (FontStyle)result; + }; + + public static Action EditorFontWeight = (value) => + { + AppSettingsService.EditorFontWeight = new FontWeight() + { + Weight = (ushort)value + }; + }; + + public static Action EditorDefaultTextWrapping = (value) => + { + Enum.TryParse(typeof(TextWrapping), (string)value, out var result); + AppSettingsService.EditorDefaultTextWrapping = (TextWrapping)result; + }; + + public static Action EditorDisplayLineHighlighter = (value) => + { + AppSettingsService.EditorDisplayLineHighlighter = (bool)value; + }; + + public static Action EditorDisplayLineNumbers = (value) => + { + AppSettingsService.EditorDisplayLineNumbers = (bool)value; + }; + + public static Action EditorDefaultLineEnding = (value) => + { + Enum.TryParse(typeof(LineEnding), (string)value, out var result); + AppSettingsService.EditorDefaultLineEnding = (LineEnding)result; + }; + + public static Action EditorDefaultEncoding = (value) => + { + AppSettingsService.InitializeEncodingSettings(); + }; + + public static Action EditorDefaultDecoding = (value) => + { + AppSettingsService.InitializeDecodingSettings(); + }; + + public static Action EditorDefaultTabIndents = (value) => + { + AppSettingsService.EditorDefaultTabIndents = (int)value; + }; + + public static Action EditorDefaultSearchEngine = (value) => + { + Enum.TryParse(typeof(SearchEngine), (string)value, out var result); + AppSettingsService.EditorDefaultSearchEngine = (SearchEngine)result; + }; + + public static Action EditorCustomMadeSearchUrl = (value) => + { + AppSettingsService.EditorCustomMadeSearchUrl = (string)value; + }; + + public static Action ShowStatusBar = (value) => + { + AppSettingsService.ShowStatusBar = (bool)value; + }; + + public static Action IsHighlightMisspelledWordsEnabled = (value) => + { + AppSettingsService.IsHighlightMisspelledWordsEnabled = (bool)value; + }; + + public static Action AlwaysOpenNewWindow = (value) => + { + AppSettingsService.AlwaysOpenNewWindow = (bool)value; + }; + + public static Action UseWindowsAccentColor = (value) => + { + ThemeSettingsService.UseWindowsAccentColor = (bool)value; + }; + + public static Action AppBackgroundPanelTintOpacity = async (value) => + { + await Dispatcher.RunAsync(CoreDispatcherPriority.High, () => + { + ThemeSettingsService.AppBackgroundPanelTintOpacity = (double)value; + }); + }; + + public static Action AppAccentColor = (value) => + { + ThemeSettingsService.AppAccentColor = ((string)value).ToColor(); + }; + + public static Action CustomAccentColor = (value) => + { + ThemeSettingsService.CustomAccentColor = ((string)value).ToColor(); + }; + + public static Action ThemeMode = (value) => + { + Enum.TryParse(typeof(ElementTheme), (string)value, out var result); + ThemeSettingsService.ThemeMode = (ElementTheme)result; + }; + } +} diff --git a/src/Notepads/Settings/SettingsDelegate.cs b/src/Notepads/Settings/SettingsDelegate.cs deleted file mode 100644 index 5ba710c81..000000000 --- a/src/Notepads/Settings/SettingsDelegate.cs +++ /dev/null @@ -1,156 +0,0 @@ -namespace Notepads.Settings -{ - using Microsoft.Toolkit.Uwp.Helpers; - using Notepads.Services; - using Notepads.Utilities; - using System; - using Windows.UI.Core; - using Windows.UI.Text; - using Windows.UI.Xaml; - - public delegate void Settings(object value); - - public static class SettingsDelegate - { - public static CoreDispatcher Dispatcher; - - public static Settings EditorFontFamily = SetEditorFontFamily; - public static Settings EditorFontSize = SetEditorFontSize; - public static Settings EditorFontStyle = SetEditorFontStyle; - public static Settings EditorFontWeight = SetEditorFontWeight; - public static Settings EditorDefaultTextWrapping = SetEditorDefaultTextWrapping; - public static Settings EditorDisplayLineHighlighter = SetEditorDisplayLineHighlighter; - public static Settings EditorDisplayLineNumbers = SetEditorDisplayLineNumbers; - public static Settings EditorDefaultLineEnding = SetEditorDefaultLineEnding; - public static Settings EditorDefaultEncoding = SetEditorDefaultEncoding; - public static Settings EditorDefaultDecoding = SetEditorDefaultDecoding; - public static Settings EditorDefaultTabIndents = SetEditorDefaultTabIndents; - public static Settings EditorDefaultSearchEngine = SetEditorDefaultSearchEngine; - public static Settings EditorCustomMadeSearchUrl = SetEditorCustomMadeSearchUrl; - public static Settings ShowStatusBar = SetShowStatusBar; - public static Settings IsHighlightMisspelledWordsEnabled = SetIsHighlightMisspelledWordsEnabled; - public static Settings AlwaysOpenNewWindow = SetAlwaysOpenNewWindow; - - private static void SetEditorFontFamily(object value) - { - AppSettingsService.EditorFontFamily = (string)value; - } - - private static void SetEditorFontSize(object value) - { - AppSettingsService.EditorFontSize = (int)value; - } - - private static void SetEditorFontStyle(object value) - { - Enum.TryParse(typeof(FontStyle), (string)value, out var result); - AppSettingsService.EditorFontStyle = (FontStyle)result; - } - - private static void SetEditorFontWeight(object value) - { - AppSettingsService.EditorFontWeight = new FontWeight() - { - Weight = (ushort)value - }; - } - - private static void SetEditorDefaultTextWrapping(object value) - { - Enum.TryParse(typeof(TextWrapping), (string)value, out var result); - AppSettingsService.EditorDefaultTextWrapping = (TextWrapping)result; - } - - private static void SetEditorDisplayLineHighlighter(object value) - { - AppSettingsService.EditorDisplayLineHighlighter = (bool)value; - } - - private static void SetEditorDisplayLineNumbers(object value) - { - AppSettingsService.EditorDisplayLineNumbers = (bool)value; - } - - private static void SetEditorDefaultLineEnding(object value) - { - Enum.TryParse(typeof(LineEnding), (string)value, out var result); - AppSettingsService.EditorDefaultLineEnding = (LineEnding)result; - } - - private static void SetEditorDefaultEncoding(object value) - { - AppSettingsService.InitializeEncodingSettings(); - } - - private static void SetEditorDefaultDecoding(object value) - { - AppSettingsService.InitializeDecodingSettings(); - } - - private static void SetEditorDefaultTabIndents(object value) - { - AppSettingsService.EditorDefaultTabIndents = (int)value; - } - - private static void SetEditorDefaultSearchEngine(object value) - { - Enum.TryParse(typeof(SearchEngine), (string)value, out var result); - AppSettingsService.EditorDefaultSearchEngine = (SearchEngine)result; - } - - private static void SetEditorCustomMadeSearchUrl(object value) - { - AppSettingsService.EditorCustomMadeSearchUrl = (string)value; - } - - private static void SetShowStatusBar(object value) - { - AppSettingsService.ShowStatusBar = (bool)value; - } - - private static void SetIsHighlightMisspelledWordsEnabled(object value) - { - AppSettingsService.IsHighlightMisspelledWordsEnabled = (bool)value; - } - - private static void SetAlwaysOpenNewWindow(object value) - { - AppSettingsService.AlwaysOpenNewWindow = (bool)value; - } - - public static Settings UseWindowsAccentColor = SetUseWindowsAccentColor; - public static Settings AppBackgroundPanelTintOpacity = SetAppBackgroundPanelTintOpacity; - public static Settings AppAccentColor = SetAppAccentColor; - public static Settings CustomAccentColor = SetCustomAccentColor; - public static Settings ThemeMode = SetThemeMode; - - private static void SetUseWindowsAccentColor(object value) - { - ThemeSettingsService.UseWindowsAccentColor = (bool)value; - } - - private static async void SetAppBackgroundPanelTintOpacity(object value) - { - await Dispatcher.RunAsync(CoreDispatcherPriority.High, () => - { - ThemeSettingsService.AppBackgroundPanelTintOpacity = (double)value; - }); - } - - private static void SetAppAccentColor(object value) - { - ThemeSettingsService.AppAccentColor = ((string)value).ToColor(); - } - - private static void SetCustomAccentColor(object value) - { - ThemeSettingsService.CustomAccentColor = ((string)value).ToColor(); - } - - private static void SetThemeMode(object value) - { - Enum.TryParse(typeof(ElementTheme), (string)value, out var result); - ThemeSettingsService.ThemeMode = (ElementTheme)result; - } - } -} diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs index a122db7ae..354dc3f17 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs @@ -285,7 +285,7 @@ private async void Sets_Loaded(object sender, RoutedEventArgs e) { await BuildOpenRecentButtonSubItems(updateForOtherInstaneArgs); }); - SettingsDelegate.Dispatcher = Dispatcher; + SettingsSyncService.Dispatcher = Dispatcher; } private async void App_EnteredBackground(object sender, Windows.ApplicationModel.EnteredBackgroundEventArgs e) From 7afd461a9999b2670723a00ccff66dfaf84198cc Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 4 Jun 2020 02:20:31 +0530 Subject: [PATCH 023/181] fix. --- src/Notepads.DesktopExtension/AdminService.cs | 5 --- .../IAdminService.cs | 3 -- src/Notepads.DesktopExtension/Program.cs | 12 +++++ .../AdminService/AdminService.wsdl | 19 -------- .../AdminService/AdminService1.xsd | 12 ----- .../AdminService/Reference.cs | 9 +--- src/Notepads/Program.cs | 4 +- src/Notepads/Services/InteropService.cs | 45 ++++++++++--------- .../Views/MainPage/NotepadsMainPage.IO.cs | 15 ++----- .../Views/MainPage/NotepadsMainPage.xaml.cs | 4 +- 10 files changed, 46 insertions(+), 82 deletions(-) diff --git a/src/Notepads.DesktopExtension/AdminService.cs b/src/Notepads.DesktopExtension/AdminService.cs index 8a2b0740b..137604fc1 100644 --- a/src/Notepads.DesktopExtension/AdminService.cs +++ b/src/Notepads.DesktopExtension/AdminService.cs @@ -25,10 +25,5 @@ public async Task SaveFile(string filePath, byte[] data) return false; } } - - public bool IsLive() - { - return true; - } } } diff --git a/src/Notepads.DesktopExtension/IAdminService.cs b/src/Notepads.DesktopExtension/IAdminService.cs index b6d6a499e..a1e69b306 100644 --- a/src/Notepads.DesktopExtension/IAdminService.cs +++ b/src/Notepads.DesktopExtension/IAdminService.cs @@ -10,8 +10,5 @@ public interface IAdminService { [OperationContract] Task SaveFile(string filePath, byte[] data); - - [OperationContract] - bool IsLive(); } } diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs index 7c586d884..26dc284aa 100644 --- a/src/Notepads.DesktopExtension/Program.cs +++ b/src/Notepads.DesktopExtension/Program.cs @@ -88,6 +88,8 @@ private static void CheckInstance(string key) if (!isFirstInstance) { mutex.ReleaseMutex(); + RemoveMutexId(AdminExtensionMutexIdStr); + RemoveMutexId(DesktopExtensionMutexIdStr); Application.Exit(); } } @@ -169,5 +171,15 @@ private static void WriteMutexId(string key, object obj) ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; localSettings.Values[key] = obj; } + + private static void RemoveMutexId(string key) + { + try + { + ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; + localSettings.Values.Remove(key); + } + catch (Exception) { } + } } } diff --git a/src/Notepads/Connected Services/AdminService/AdminService.wsdl b/src/Notepads/Connected Services/AdminService/AdminService.wsdl index d255bdfd0..a08f960ec 100644 --- a/src/Notepads/Connected Services/AdminService/AdminService.wsdl +++ b/src/Notepads/Connected Services/AdminService/AdminService.wsdl @@ -12,21 +12,11 @@ - - - - - - - - - - @@ -39,15 +29,6 @@ - - - - - - - - - diff --git a/src/Notepads/Connected Services/AdminService/AdminService1.xsd b/src/Notepads/Connected Services/AdminService/AdminService1.xsd index 22381e294..58a2bc7a2 100644 --- a/src/Notepads/Connected Services/AdminService/AdminService1.xsd +++ b/src/Notepads/Connected Services/AdminService/AdminService1.xsd @@ -15,16 +15,4 @@ - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Notepads/Connected Services/AdminService/Reference.cs b/src/Notepads/Connected Services/AdminService/Reference.cs index 7088f8148..2fcea6ce4 100644 --- a/src/Notepads/Connected Services/AdminService/Reference.cs +++ b/src/Notepads/Connected Services/AdminService/Reference.cs @@ -9,7 +9,7 @@ //------------------------------------------------------------------------------ // -// This code was auto-generated by Microsoft.VisualStudio.ServiceReference.Platforms, version 16.0.30011.22 +// This code was auto-generated by Microsoft.VisualStudio.ServiceReference.Platforms, version 16.0.30104.148 // namespace Notepads.AdminService { @@ -20,9 +20,6 @@ public interface IAdminService { [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IAdminService/SaveFile", ReplyAction="http://tempuri.org/IAdminService/SaveFileResponse")] System.Threading.Tasks.Task SaveFileAsync(string filePath, byte[] data); - - [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IAdminService/IsLive", ReplyAction="http://tempuri.org/IAdminService/IsLiveResponse")] - System.Threading.Tasks.Task IsLiveAsync(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] @@ -72,10 +69,6 @@ public System.Threading.Tasks.Task SaveFileAsync(string filePath, byte[] d return base.Channel.SaveFileAsync(filePath, data); } - public System.Threading.Tasks.Task IsLiveAsync() { - return base.Channel.IsLiveAsync(); - } - public virtual System.Threading.Tasks.Task OpenAsync() { return System.Threading.Tasks.Task.Factory.FromAsync(((System.ServiceModel.ICommunicationObject)(this)).BeginOpen(null, null), new System.Action(((System.ServiceModel.ICommunicationObject)(this)).EndOpen)); } diff --git a/src/Notepads/Program.cs b/src/Notepads/Program.cs index 0a5c30e2e..ce9e59d27 100644 --- a/src/Notepads/Program.cs +++ b/src/Notepads/Program.cs @@ -2,6 +2,7 @@ { using System; using System.Linq; + using System.Security.Principal; using System.Threading.Tasks; using Notepads.Services; using Notepads.Settings; @@ -149,7 +150,8 @@ private static AppInstance GetLastActiveInstance() private static async void OpenExtension() { - if (ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0)) + if (ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0) && + !new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) { await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); } diff --git a/src/Notepads/Services/InteropService.cs b/src/Notepads/Services/InteropService.cs index 5942928d8..95a3e9843 100644 --- a/src/Notepads/Services/InteropService.cs +++ b/src/Notepads/Services/InteropService.cs @@ -12,6 +12,11 @@ using Windows.Foundation.Collections; using Windows.UI.Xaml; + public class AdminstratorAccessException : Exception + { + public AdminstratorAccessException():base("Failed to save due to no Adminstration access") { } + } + public static class InteropService { public static EventHandler HideSettingsPane; @@ -20,7 +25,7 @@ public static class InteropService public static AppServiceConnection InteropServiceConnection = null; public static AdminServiceClient AdminServiceClient = new AdminServiceClient(); - public static readonly Exception AdminstratorAccessException = new Exception("Failed to save due to no Adminstration access"); + private static bool _isAdminExtensionAvailable = false; private static readonly ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView(); private static readonly string _commandLabel = "Command"; @@ -54,7 +59,7 @@ public static class InteropService {SettingsKey.RequestedThemeStr, SettingsSyncService.ThemeMode} }; - public static async void Initialize() + public static async Task Initialize() { InteropServiceConnection = new AppServiceConnection() { @@ -93,6 +98,7 @@ await DispatcherExtensions.CallOnUIThreadAsync(SettingsSyncService.Dispatcher, ( if (message.ContainsKey(_adminCreatedLabel) && (bool)message[_adminCreatedLabel]) { NotificationCenter.Instance.PostNotification(_resourceLoader.GetString("TextEditor_NotificationMsg_AdminExtensionCreated"), 1500); + _isAdminExtensionAvailable = true; } else { @@ -110,7 +116,7 @@ private static void InteropServiceConnection_ServiceClosed(AppServiceConnection public static async void SyncSettings(string settingsKey, object value) { - if (InteropServiceConnection == null) return; + if (InteropServiceConnection == null) await Initialize(); var message = new ValueSet(); message.Add(_commandLabel, CommandArgs.SyncSettings.ToString()); @@ -128,7 +134,7 @@ public static async void SyncSettings(string settingsKey, object value) public static async void SyncRecentList() { - if (InteropServiceConnection == null) return; + if (InteropServiceConnection == null) await Initialize(); var message = new ValueSet(); message.Add(_commandLabel, CommandArgs.SyncRecentList.ToString()); @@ -137,31 +143,28 @@ public static async void SyncRecentList() public static async Task SaveFileAsAdmin(string filePath, byte[] data) { - if (InteropServiceConnection == null) return; + if (InteropServiceConnection == null) await Initialize(); - bool isAdminExtensionAvailable = true; bool failedFromAdminExtension = false; - - try + if (_isAdminExtensionAvailable) { - if (await AdminServiceClient.IsLiveAsync()) + try { ApplicationSettingsStore.Write(SettingsKey.AdminAuthenticationTokenStr, Guid.NewGuid().ToString()); failedFromAdminExtension = !await AdminServiceClient.SaveFileAsync(filePath, data); } + catch + { + _isAdminExtensionAvailable = false; + } + finally + { + ApplicationSettingsStore.Remove(SettingsKey.AdminAuthenticationTokenStr); + } } - catch - { - isAdminExtensionAvailable = false; - } - finally - { - ApplicationSettingsStore.Remove(SettingsKey.AdminAuthenticationTokenStr); - } - - if (!isAdminExtensionAvailable) + else { - throw AdminstratorAccessException; + throw new AdminstratorAccessException(); } if (failedFromAdminExtension) @@ -172,7 +175,7 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) public static async Task CreateElevetedExtension() { - if (InteropServiceConnection == null) return; + if (InteropServiceConnection == null) await Initialize(); var message = new ValueSet(); message.Add(_commandLabel, CommandArgs.CreateElevetedExtension.ToString()); diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs index 97d347e5b..62adf07f0 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs @@ -163,11 +163,9 @@ private async Task Save(ITextEditor textEditor, bool saveAs, bool ignoreUn { promptSaveAs = true; } - catch (Exception ex) // Happens when the file we are saving is read-only, ask user for permission to write + catch (AdminstratorAccessException) // Happens when the file we are saving is read-only, ask user for permission to write { - if (ex == InteropService.AdminstratorAccessException) - { - var createElevatedExtensionDialog = NotepadsDialogFactory.GetCreateElevatedExtensionDialog( + var createElevatedExtensionDialog = NotepadsDialogFactory.GetCreateElevatedExtensionDialog( async () => { await InteropService.CreateElevetedExtension(); @@ -177,14 +175,9 @@ private async Task Save(ITextEditor textEditor, bool saveAs, bool ignoreUn promptSaveAs = true; }); - var dialogResult = await DialogManager.OpenDialogAsync(createElevatedExtensionDialog, awaitPreviousDialog: false); + var dialogResult = await DialogManager.OpenDialogAsync(createElevatedExtensionDialog, awaitPreviousDialog: false); - if (dialogResult == null || createElevatedExtensionDialog.IsAborted) - { - promptSaveAs = true; - } - } - else + if (dialogResult == null || createElevatedExtensionDialog.IsAborted) { promptSaveAs = true; } diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs index 354dc3f17..7c780372f 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs @@ -279,7 +279,7 @@ private async void Sets_Loaded(object sender, RoutedEventArgs e) Window.Current.CoreWindow.Activated += CoreWindow_Activated; } - InteropService.Initialize(); + await InteropService.Initialize(); InteropService.HideSettingsPane += HideSettingsPane_OnSettingsChanged; InteropService.UpdateRecentList += async (_, updateForOtherInstaneArgs) => await Dispatcher.CallOnUIThreadAsync(async () => { @@ -306,7 +306,7 @@ private async void App_LeavingBackground(object sender, LeavingBackgroundEventAr ThemeSettingsService.UpdateAllSettings(); AppSettingsService.UpdateAllSettings(); await BuildOpenRecentButtonSubItems(false); - InteropService.Initialize(); + await InteropService.Initialize(); } public void ExecuteProtocol(Uri uri) From 50ef6e9aeabfcb0c6c9db30f7bc8eb5733abf8eb Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 26 Jun 2020 07:48:38 +0530 Subject: [PATCH 024/181] Implemented settings and recently opened file list syncing across all instances. --- src/Notepads/App.xaml.cs | 1 - .../Controls/Dialog/NotepadsDialog.cs | 4 +- src/Notepads/Notepads.csproj | 1 + src/Notepads/Services/AppSettingsService.cs | 72 ++++++++++++--- .../Services/InterInstanceSyncService.cs | 69 +++++++++++++++ src/Notepads/Services/ThemeSettingsService.cs | 88 ++++++++----------- src/Notepads/Settings/ApplicationSettings.cs | 7 ++ src/Notepads/Settings/SettingsKey.cs | 3 +- src/Notepads/Strings/en-US/Resources.resw | 2 +- .../MainPage/NotepadsMainPage.MainMenu.cs | 12 ++- .../Views/MainPage/NotepadsMainPage.xaml.cs | 7 ++ .../PersonalizationSettingsPage.xaml.cs | 32 +++---- 12 files changed, 205 insertions(+), 93 deletions(-) create mode 100644 src/Notepads/Services/InterInstanceSyncService.cs diff --git a/src/Notepads/App.xaml.cs b/src/Notepads/App.xaml.cs index d8ffef582..58641361d 100644 --- a/src/Notepads/App.xaml.cs +++ b/src/Notepads/App.xaml.cs @@ -93,7 +93,6 @@ private async Task ActivateAsync(IActivatedEventArgs e) { { "OSArchitecture", SystemInformation.OperatingSystemArchitecture.ToString() }, { "OSVersion", $"{SystemInformation.OperatingSystemVersion.Major}.{SystemInformation.OperatingSystemVersion.Minor}.{SystemInformation.OperatingSystemVersion.Build}" }, - { "UseWindowsTheme", ThemeSettingsService.UseWindowsTheme.ToString() }, { "ThemeMode", ThemeSettingsService.ThemeMode.ToString() }, { "UseWindowsAccentColor", ThemeSettingsService.UseWindowsAccentColor.ToString() }, { "AppBackgroundTintOpacity", $"{(int) (ThemeSettingsService.AppBackgroundPanelTintOpacity * 10.0) * 10}" }, diff --git a/src/Notepads/Controls/Dialog/NotepadsDialog.cs b/src/Notepads/Controls/Dialog/NotepadsDialog.cs index bb27e1b9c..73c82d856 100644 --- a/src/Notepads/Controls/Dialog/NotepadsDialog.cs +++ b/src/Notepads/Controls/Dialog/NotepadsDialog.cs @@ -17,8 +17,8 @@ public class NotepadsDialog : ContentDialog public NotepadsDialog() { - RequestedTheme = ThemeSettingsService.ThemeMode; - Background = ThemeSettingsService.ThemeMode == ElementTheme.Dark + RequestedTheme = ThemeSettingsService.GetActualTheme(ThemeSettingsService.ThemeMode); + Background = RequestedTheme == ElementTheme.Dark ? _darkModeBackgroundBrush : _lightModeBackgroundBrush; diff --git a/src/Notepads/Notepads.csproj b/src/Notepads/Notepads.csproj index 5bda548f5..63b41413a 100644 --- a/src/Notepads/Notepads.csproj +++ b/src/Notepads/Notepads.csproj @@ -137,6 +137,7 @@ + diff --git a/src/Notepads/Services/AppSettingsService.cs b/src/Notepads/Services/AppSettingsService.cs index d98c868d1..3966aa59d 100644 --- a/src/Notepads/Services/AppSettingsService.cs +++ b/src/Notepads/Services/AppSettingsService.cs @@ -286,13 +286,17 @@ public static bool IsSmartCopyEnabled public static void Initialize() { - InitializeFontSettings(); + InitializeFontFamilySettings(); + InitializeFontSizeSettings(); + InitializeFontStyleSettings(); + InitializeFontWeightSettings(); InitializeTextWrappingSettings(); InitializeSpellingSettings(); - InitializeDisplaySettings(); + InitializeDisplayLineHighlighterSettings(); + InitializeDisplayLineNumbersSettings(); InitializeSmartCopySettings(); @@ -305,6 +309,7 @@ public static void Initialize() InitializeTabIndentsSettings(); InitializeSearchEngineSettings(); + InitializeCustomSearchUrlSettings(); InitializeStatusBarSettings(); @@ -313,7 +318,7 @@ public static void Initialize() InitializeAppOpeningPreferencesSettings(); } - private static void InitializeStatusBarSettings() + public static void InitializeStatusBarSettings(bool invokeChangedEvent = false) { if (ApplicationSettingsStore.Read(SettingsKey.EditorShowStatusBarBool) is bool showStatusBar) { @@ -323,6 +328,8 @@ private static void InitializeStatusBarSettings() { _showStatusBar = true; } + + if (invokeChangedEvent) OnStatusBarVisibilityChanged?.Invoke(null, _showStatusBar); } private static void InitializeSessionSnapshotSettings() @@ -349,7 +356,7 @@ private static void InitializeSessionSnapshotSettings() } } - private static void InitializeLineEndingSettings() + public static void InitializeLineEndingSettings(bool invokeChangedEvent = false) { if (ApplicationSettingsStore.Read(SettingsKey.EditorDefaultLineEndingStr) is string lineEndingStr && Enum.TryParse(typeof(LineEnding), lineEndingStr, out var lineEnding)) @@ -360,9 +367,11 @@ private static void InitializeLineEndingSettings() { _editorDefaultLineEnding = LineEnding.Crlf; } + + if (invokeChangedEvent) OnDefaultLineEndingChanged?.Invoke(null, _editorDefaultLineEnding); } - private static void InitializeTextWrappingSettings() + public static void InitializeTextWrappingSettings(bool invokeChangedEvent = false) { if (ApplicationSettingsStore.Read(SettingsKey.EditorDefaultTextWrappingStr) is string textWrappingStr && Enum.TryParse(typeof(TextWrapping), textWrappingStr, out var textWrapping)) @@ -373,9 +382,11 @@ private static void InitializeTextWrappingSettings() { _editorDefaultTextWrapping = TextWrapping.NoWrap; } + + if (invokeChangedEvent) OnDefaultTextWrappingChanged?.Invoke(null, _editorDefaultTextWrapping); } - private static void InitializeSpellingSettings() + public static void InitializeSpellingSettings(bool invokeChangedEvent = false) { if (ApplicationSettingsStore.Read(SettingsKey.EditorHighlightMisspelledWordsBool) is bool highlightMisspelledWords) { @@ -385,9 +396,11 @@ private static void InitializeSpellingSettings() { _isHighlightMisspelledWordsEnabled = false; } + + if (invokeChangedEvent) OnHighlightMisspelledWordsChanged?.Invoke(null, _isHighlightMisspelledWordsEnabled); } - private static void InitializeDisplaySettings() + public static void InitializeDisplayLineHighlighterSettings(bool invokeChangedEvent = false) { if (ApplicationSettingsStore.Read(SettingsKey.EditorDefaultLineHighlighterViewStateBool) is bool displayLineHighlighter) { @@ -398,6 +411,11 @@ private static void InitializeDisplaySettings() _editorDisplayLineHighlighter = true; } + if (invokeChangedEvent) OnDefaultLineHighlighterViewStateChanged?.Invoke(null, _editorDisplayLineHighlighter); + } + + public static void InitializeDisplayLineNumbersSettings(bool invokeChangedEvent = false) + { if (ApplicationSettingsStore.Read(SettingsKey.EditorDefaultDisplayLineNumbersBool) is bool displayLineNumbers) { _displayLineNumbers = displayLineNumbers; @@ -406,9 +424,11 @@ private static void InitializeDisplaySettings() { _displayLineNumbers = true; } + + if (invokeChangedEvent) OnDefaultDisplayLineNumbersViewStateChanged?.Invoke(null, _displayLineNumbers); } - private static void InitializeSmartCopySettings() + public static void InitializeSmartCopySettings() { if (ApplicationSettingsStore.Read(SettingsKey.EditorEnableSmartCopyBool) is bool enableSmartCopy) { @@ -420,7 +440,7 @@ private static void InitializeSmartCopySettings() } } - private static void InitializeEncodingSettings() + public static void InitializeEncodingSettings(bool invokeChangedEvent = false) { Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); @@ -446,9 +466,11 @@ private static void InitializeEncodingSettings() { _editorDefaultEncoding = new UTF8Encoding(false); } + + if (invokeChangedEvent) OnDefaultEncodingChanged?.Invoke(null, _editorDefaultEncoding); } - private static void InitializeDecodingSettings() + public static void InitializeDecodingSettings() { if (ApplicationSettingsStore.Read(SettingsKey.EditorDefaultDecodingCodePageInt) is int decodingCodePage) { @@ -480,7 +502,7 @@ private static void InitializeDecodingSettings() } } - private static void InitializeTabIndentsSettings() + public static void InitializeTabIndentsSettings(bool invokeChangedEvent = false) { if (ApplicationSettingsStore.Read(SettingsKey.EditorDefaultTabIndentsInt) is int tabIndents) { @@ -490,9 +512,11 @@ private static void InitializeTabIndentsSettings() { _editorDefaultTabIndents = -1; } + + if (invokeChangedEvent) OnDefaultTabIndentsChanged?.Invoke(null, _editorDefaultTabIndents); } - private static void InitializeSearchEngineSettings() + public static void InitializeSearchEngineSettings() { if (ApplicationSettingsStore.Read(SettingsKey.EditorDefaultSearchEngineStr) is string searchEngineStr && Enum.TryParse(typeof(SearchEngine), searchEngineStr, out var searchEngine)) @@ -503,7 +527,10 @@ private static void InitializeSearchEngineSettings() { _editorDefaultSearchEngine = SearchEngine.Bing; } + } + public static void InitializeCustomSearchUrlSettings() + { if (ApplicationSettingsStore.Read(SettingsKey.EditorCustomMadeSearchUrlStr) is string customMadeSearchUrl) { _editorCustomMadeSearchUrl = customMadeSearchUrl; @@ -514,7 +541,7 @@ private static void InitializeSearchEngineSettings() } } - private static void InitializeFontSettings() + public static void InitializeFontFamilySettings(bool invokeChangedEvent = false) { if (ApplicationSettingsStore.Read(SettingsKey.EditorFontFamilyStr) is string fontFamily) { @@ -525,6 +552,11 @@ private static void InitializeFontSettings() _editorFontFamily = "Consolas"; } + if (invokeChangedEvent) OnFontFamilyChanged?.Invoke(null, _editorFontFamily); + } + + public static void InitializeFontSizeSettings(bool invokeChangedEvent = false) + { if (ApplicationSettingsStore.Read(SettingsKey.EditorFontSizeInt) is int fontSize) { _editorFontSize = fontSize; @@ -534,6 +566,11 @@ private static void InitializeFontSettings() _editorFontSize = 14; } + if (invokeChangedEvent) OnFontSizeChanged?.Invoke(null, _editorFontSize); + } + + public static void InitializeFontStyleSettings(bool invokeChangedEvent = false) + { if (ApplicationSettingsStore.Read(SettingsKey.EditorFontStyleStr) is string fontStyleStr && Enum.TryParse(typeof(FontStyle), fontStyleStr, out var fontStyle)) { @@ -544,6 +581,11 @@ private static void InitializeFontSettings() _editorFontStyle = FontStyle.Normal; } + if (invokeChangedEvent) OnFontStyleChanged?.Invoke(null, _editorFontStyle); + } + + public static void InitializeFontWeightSettings(bool invokeChangedEvent = false) + { if (ApplicationSettingsStore.Read(SettingsKey.EditorFontWeightUshort) is ushort fontWeight) { _editorFontWeight = new FontWeight() @@ -555,9 +597,11 @@ private static void InitializeFontSettings() { _editorFontWeight = FontWeights.Normal; } + + if (invokeChangedEvent) OnFontWeightChanged?.Invoke(null, _editorFontWeight); } - private static void InitializeAppOpeningPreferencesSettings() + public static void InitializeAppOpeningPreferencesSettings() { if (ApplicationSettingsStore.Read(SettingsKey.AlwaysOpenNewWindowBool) is bool alwaysOpenNewWindow) { diff --git a/src/Notepads/Services/InterInstanceSyncService.cs b/src/Notepads/Services/InterInstanceSyncService.cs new file mode 100644 index 000000000..751040a5b --- /dev/null +++ b/src/Notepads/Services/InterInstanceSyncService.cs @@ -0,0 +1,69 @@ +namespace Notepads.Services +{ + using Notepads.Extensions; + using Notepads.Settings; + using Notepads.Views.MainPage; + using System; + using System.Collections.Generic; + using Windows.Storage; + + public static class InterInstanceSyncService + { + private static NotepadsMainPage _notepadsMainPage = null; + + public static readonly string OpenRecentKey = "BuildOpenRecentButtonSubItems"; + + public static IReadOnlyDictionary SyncManager = new Dictionary + { + {SettingsKey.AppBackgroundTintOpacityDouble, () => ThemeSettingsService.InitializeAppBackgroundPanelTintOpacity(true)}, + {SettingsKey.RequestedThemeStr, () => ThemeSettingsService.InitializeThemeMode(true)}, + {SettingsKey.UseWindowsAccentColorBool, () => { } }, + {SettingsKey.AppAccentColorHexStr, () => { } }, + {SettingsKey.CustomAccentColorHexStr, () => ThemeSettingsService.InitializeCustomAccentColor()}, + {SettingsKey.EditorDefaultLineHighlighterViewStateBool, () => AppSettingsService.InitializeDisplayLineHighlighterSettings(true)}, + {SettingsKey.EditorDefaultDisplayLineNumbersBool, () => AppSettingsService.InitializeDisplayLineNumbersSettings(true)}, + {SettingsKey.EditorDefaultTabIndentsInt, () => AppSettingsService.InitializeTabIndentsSettings(true)}, + {SettingsKey.EditorDefaultTextWrappingStr, () => AppSettingsService.InitializeTextWrappingSettings(true)}, + {SettingsKey.EditorFontFamilyStr, () => AppSettingsService.InitializeFontFamilySettings(true)}, + {SettingsKey.EditorFontSizeInt, () => AppSettingsService.InitializeFontSizeSettings(true)}, + {SettingsKey.EditorFontStyleStr, () => AppSettingsService.InitializeFontStyleSettings(true)}, + {SettingsKey.EditorFontWeightUshort, () => AppSettingsService.InitializeFontWeightSettings(true)}, + {SettingsKey.EditorHighlightMisspelledWordsBool, () => AppSettingsService.InitializeSpellingSettings(true)}, + {SettingsKey.EditorDefaultEncodingCodePageInt, () => AppSettingsService.InitializeEncodingSettings(true)}, + {SettingsKey.EditorDefaultLineEndingStr, () => AppSettingsService.InitializeLineEndingSettings(true)}, + {SettingsKey.EditorShowStatusBarBool, () => AppSettingsService.InitializeStatusBarSettings(true)}, + {SettingsKey.EditorCustomMadeSearchUrlStr, () => AppSettingsService.InitializeCustomSearchUrlSettings()}, + {SettingsKey.EditorDefaultDecodingCodePageInt, () => AppSettingsService.InitializeDecodingSettings()}, + {SettingsKey.EditorDefaultSearchEngineStr, () => AppSettingsService.InitializeSearchEngineSettings()}, + {SettingsKey.EditorEnableSmartCopyBool, () => AppSettingsService.InitializeSmartCopySettings() }, + {SettingsKey.AlwaysOpenNewWindowBool, () => AppSettingsService.InitializeAppOpeningPreferencesSettings() }, + {OpenRecentKey, async () => await _notepadsMainPage.BuildOpenRecentButtonSubItems(false) } + }; + + public static void Initialize(NotepadsMainPage page) + { + _notepadsMainPage = page; + ApplicationData.Current.DataChanged += Application_OnDataChanged; + } + + private static async void Application_OnDataChanged(ApplicationData sender, object args) + { + if (ApplicationSettingsStore.Read(SettingsKey.LastChangedSettingsAppInstanceIdStr) is string lastChangedSettingsAppInstanceIdStr && + lastChangedSettingsAppInstanceIdStr == App.Id.ToString()) + { + return; + } + + if (ApplicationSettingsStore.Read(SettingsKey.LastChangedSettingsKeyStr) is string lastChangedSettingsKeyStr && + SyncManager.ContainsKey(lastChangedSettingsKeyStr) && _notepadsMainPage != null) + { + await DispatcherExtensions.CallOnUIThreadAsync(_notepadsMainPage.Dispatcher, () => + { + if (lastChangedSettingsKeyStr != OpenRecentKey) _notepadsMainPage.CloseSettingsPane(); + SyncManager[lastChangedSettingsKeyStr].Invoke(); + ThemeSettingsService.InitializeAppAccentColor(true); + }); + } + } + } +} diff --git a/src/Notepads/Services/ThemeSettingsService.cs b/src/Notepads/Services/ThemeSettingsService.cs index c1a438b81..c3c1e1695 100644 --- a/src/Notepads/Services/ThemeSettingsService.cs +++ b/src/Notepads/Services/ThemeSettingsService.cs @@ -18,32 +18,22 @@ public static class ThemeSettingsService public static event EventHandler OnBackgroundChanged; public static event EventHandler OnAccentColorChanged; - public static ElementTheme ThemeMode { get; set; } - private static readonly UISettings UISettings = new UISettings(); private static readonly ThemeListener ThemeListener = new ThemeListener(); private static Brush _currentAppBackgroundBrush; - private static bool _useWindowsTheme; + private static ElementTheme _themeMode; - public static bool UseWindowsTheme + public static ElementTheme ThemeMode { - get => _useWindowsTheme; + get => _themeMode; set { - if (value != _useWindowsTheme) + if (value != _themeMode) { - _useWindowsTheme = value; - if (value) - { - var currentWindowsTheme = Application.Current.RequestedTheme.ToElementTheme(); - if (ThemeMode != currentWindowsTheme) - { - ThemeMode = currentWindowsTheme; - OnThemeChanged?.Invoke(null, ThemeMode); - } - } - ApplicationSettingsStore.Write(SettingsKey.UseWindowsThemeBool, _useWindowsTheme); + _themeMode = value; + OnThemeChanged?.Invoke(null, value); + ApplicationSettingsStore.Write(SettingsKey.RequestedThemeStr, value.ToString()); } } } @@ -113,7 +103,7 @@ public static void Initialize() InitializeAppBackgroundPanelTintOpacity(); } - private static void InitializeAppAccentColor() + public static void InitializeAppAccentColor(bool invokeChangedEvent = false) { if (ApplicationSettingsStore.Read(SettingsKey.UseWindowsAccentColorBool) is bool useWindowsAccentColor) { @@ -135,9 +125,11 @@ private static void InitializeAppAccentColor() _appAccentColor = accentColorHexStr.ToColor(); } } + + if (invokeChangedEvent) OnAccentColorChanged?.Invoke(null, _appAccentColor); } - private static void InitializeCustomAccentColor() + public static void InitializeCustomAccentColor() { if (ApplicationSettingsStore.Read(SettingsKey.CustomAccentColorHexStr) is string customAccentColorHexStr) { @@ -157,7 +149,7 @@ private static void UiSettings_ColorValuesChanged(UISettings sender, object args } } - private static void InitializeAppBackgroundPanelTintOpacity() + public static void InitializeAppBackgroundPanelTintOpacity(bool invokeChangedEvent = false) { if (ApplicationSettingsStore.Read(SettingsKey.AppBackgroundTintOpacityDouble) is double tintOpacity) { @@ -167,51 +159,32 @@ private static void InitializeAppBackgroundPanelTintOpacity() { _appBackgroundPanelTintOpacity = 0.75; } + + if (invokeChangedEvent) OnBackgroundChanged?.Invoke(null, GetAppBackgroundBrush(ThemeMode)); } - private static void InitializeThemeMode() + public static void InitializeThemeMode(bool invokeChangedEvent = false) { - if (ApplicationSettingsStore.Read(SettingsKey.UseWindowsThemeBool) is bool useWindowsTheme) - { - _useWindowsTheme = useWindowsTheme; - } - else - { - _useWindowsTheme = true; - } - ThemeListener.ThemeChanged += ThemeListener_ThemeChanged; - ThemeMode = Application.Current.RequestedTheme.ToElementTheme(); - - if (!UseWindowsTheme) + if (ApplicationSettingsStore.Read(SettingsKey.RequestedThemeStr) is string themeModeStr) { - if (ApplicationSettingsStore.Read(SettingsKey.RequestedThemeStr) is string themeModeStr) + if (Enum.TryParse(typeof(ElementTheme), themeModeStr, out var theme)) { - if (Enum.TryParse(typeof(ElementTheme), themeModeStr, out var theme)) - { - ThemeMode = (ElementTheme)theme; - } + _themeMode = (ElementTheme)theme; } } - } - - private static void ThemeListener_ThemeChanged(ThemeListener sender) - { - if (UseWindowsTheme) + else { - SetTheme(sender.CurrentTheme.ToElementTheme()); + _themeMode = ElementTheme.Default; } + + if (invokeChangedEvent) OnThemeChanged?.Invoke(null, ThemeMode); } - public static void SetTheme(ElementTheme theme) + private static void ThemeListener_ThemeChanged(ThemeListener sender) { - if (ThemeMode != theme) - { - ThemeMode = theme; - ApplicationSettingsStore.Write(SettingsKey.RequestedThemeStr, ThemeMode.ToString()); - OnThemeChanged?.Invoke(null, theme); - } + _themeMode = sender.CurrentTheme.ToElementTheme(); } public static void SetRequestedTheme(Panel backgroundPanel, UIElement currentContent, ApplicationViewTitleBar titleBar) @@ -235,7 +208,7 @@ public static void SetRequestedTheme(Panel backgroundPanel, UIElement currentCon // Set ContentDialog background dimming color ((SolidColorBrush)Application.Current.Resources["SystemControlPageBackgroundMediumAltMediumBrush"]).Color = - ThemeMode == ElementTheme.Dark ? Color.FromArgb(153, 0, 0, 0) : Color.FromArgb(153, 255, 255, 255); + GetActualTheme(ThemeMode) == ElementTheme.Dark ? Color.FromArgb(153, 0, 0, 0) : Color.FromArgb(153, 255, 255, 255); if (DialogManager.ActiveDialog != null) { @@ -264,11 +237,20 @@ public static ElementTheme ToElementTheme(this ApplicationTheme theme) } } + public static ElementTheme GetActualTheme(ElementTheme theme) + { + if (theme == ElementTheme.Default) + return Application.Current.RequestedTheme.ToElementTheme(); + else + return theme; + } + private static Brush GetAppBackgroundBrush(ElementTheme theme) { var darkModeBaseColor = Color.FromArgb(255, 46, 46, 46); var lightModeBaseColor = Color.FromArgb(255, 240, 240, 240); + theme = GetActualTheme(theme); var baseColor = theme == ElementTheme.Light ? lightModeBaseColor : darkModeBaseColor; if (AppBackgroundPanelTintOpacity > 0.99f || @@ -291,6 +273,8 @@ private static Brush GetAppBackgroundBrush(ElementTheme theme) public static void ApplyThemeForTitleBarButtons(ApplicationViewTitleBar titleBar, ElementTheme theme) { + theme = GetActualTheme(theme); + if (theme == ElementTheme.Dark) { // Set active window colors diff --git a/src/Notepads/Settings/ApplicationSettings.cs b/src/Notepads/Settings/ApplicationSettings.cs index c0e682984..e994e1b66 100644 --- a/src/Notepads/Settings/ApplicationSettings.cs +++ b/src/Notepads/Settings/ApplicationSettings.cs @@ -23,6 +23,13 @@ public static void Write(string key, object obj) { ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; localSettings.Values[key] = obj; + + if (InterInstanceSyncService.SyncManager.ContainsKey(key)) + { + localSettings.Values[SettingsKey.LastChangedSettingsKeyStr] = key; + localSettings.Values[SettingsKey.LastChangedSettingsAppInstanceIdStr] = App.Id.ToString(); + ApplicationData.Current.SignalDataChanged(); + } } public static bool Remove(string key) diff --git a/src/Notepads/Settings/SettingsKey.cs b/src/Notepads/Settings/SettingsKey.cs index 245afdf1b..5fbed1313 100644 --- a/src/Notepads/Settings/SettingsKey.cs +++ b/src/Notepads/Settings/SettingsKey.cs @@ -7,10 +7,11 @@ internal static class SettingsKey internal static string IsJumpListOutOfDateBool = "IsJumpListOutOfDateBool"; internal static string ActiveInstanceIdStr = "ActiveInstanceIdStr"; internal static string AlwaysOpenNewWindowBool = "AlwaysOpenNewWindowBool"; + internal static string LastChangedSettingsKeyStr = "LastChangedSettingsKeyStr"; + internal static string LastChangedSettingsAppInstanceIdStr = "LastChangedSettingsAppInstanceIdStr"; // Theme related internal static string RequestedThemeStr = "RequestedThemeStr"; - internal static string UseWindowsThemeBool = "UseWindowsThemeBool"; internal static string AppBackgroundTintOpacityDouble = "AppBackgroundTintOpacityDouble"; internal static string AppAccentColorHexStr = "AppAccentColorHexStr"; internal static string CustomAccentColorHexStr = "CustomAccentColorHexStr"; diff --git a/src/Notepads/Strings/en-US/Resources.resw b/src/Notepads/Strings/en-US/Resources.resw index b5ec406ab..18a0d0367 100644 --- a/src/Notepads/Strings/en-US/Resources.resw +++ b/src/Notepads/Strings/en-US/Resources.resw @@ -438,7 +438,7 @@ App: DragAndDrop UIOverride Caption: "Open with Notepads" display text - This is a shadow window of Notepads. Session snapshot and settings are disabled. + This is a shadow window of Notepads. Session snapshot is disabled. App: ShadowWindowIndicator Description display text. diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.MainMenu.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.MainMenu.cs index eb407df80..740e3a5df 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.MainMenu.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.MainMenu.cs @@ -11,6 +11,7 @@ using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Media; using Notepads.Services; + using Notepads.Settings; public sealed partial class NotepadsMainPage { @@ -34,8 +35,7 @@ private void InitializeMainMenu() if (!App.IsFirstInstance) { - MainMenuButton.Foreground = new SolidColorBrush(ThemeSettingsService.AppAccentColor); - MenuSettingsButton.IsEnabled = false; + MainMenuButton.Foreground = (SolidColorBrush)Application.Current.Resources["SystemControlForegroundAccentBrush"]; } if (App.IsGameBarWidget) @@ -106,7 +106,7 @@ private void MainMenuButtonFlyout_Opening(object sender, object e) MenuSaveAllButton.IsEnabled = NotepadsCore.HaveUnsavedTextEditor(); } - private async Task BuildOpenRecentButtonSubItems() + public async Task BuildOpenRecentButtonSubItems(bool invokeAfterChanged = true) { var openRecentSubItem = new MenuFlyoutSubItem { @@ -168,6 +168,12 @@ private async Task BuildOpenRecentButtonSubItems() var indexToInsert = MainMenuButtonFlyout.Items.IndexOf(MenuOpenFileButton) + 1; MainMenuButtonFlyout.Items.Insert(indexToInsert, openRecentSubItem); } + + if (invokeAfterChanged) + { + ApplicationSettingsStore.Write(SettingsKey.LastChangedSettingsKeyStr, InterInstanceSyncService.OpenRecentKey); + ApplicationData.Current.SignalDataChanged(); + } } } } \ No newline at end of file diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs index 7b02764de..3ae329436 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs @@ -274,6 +274,8 @@ private async void Sets_Loaded(object sender, RoutedEventArgs e) Window.Current.CoreWindow.Activated -= CoreWindow_Activated; Window.Current.CoreWindow.Activated += CoreWindow_Activated; } + + InterInstanceSyncService.Initialize(this); } private async void App_EnteredBackground(object sender, Windows.ApplicationModel.EnteredBackgroundEventArgs e) @@ -423,6 +425,11 @@ private void HideAllOpenFlyouts() } } + public void CloseSettingsPane() + { + RootSplitView.IsPaneOpen = false; + } + private async void OnSessionBackupAndRestoreOptionChanged(object sender, bool isSessionBackupAndRestoreEnabled) { await Dispatcher.CallOnUIThreadAsync(async () => diff --git a/src/Notepads/Views/Settings/PersonalizationSettingsPage.xaml.cs b/src/Notepads/Views/Settings/PersonalizationSettingsPage.xaml.cs index 4ec25a495..764cb0bf0 100644 --- a/src/Notepads/Views/Settings/PersonalizationSettingsPage.xaml.cs +++ b/src/Notepads/Views/Settings/PersonalizationSettingsPage.xaml.cs @@ -18,21 +18,17 @@ public PersonalizationSettingsPage() { InitializeComponent(); - if (ThemeSettingsService.UseWindowsTheme) + switch (ThemeSettingsService.ThemeMode) { - ThemeModeDefaultButton.IsChecked = true; - } - else - { - switch (ThemeSettingsService.ThemeMode) - { - case ElementTheme.Light: - ThemeModeLightButton.IsChecked = true; - break; - case ElementTheme.Dark: - ThemeModeDarkButton.IsChecked = true; - break; - } + case ElementTheme.Light: + ThemeModeLightButton.IsChecked = true; + break; + case ElementTheme.Dark: + ThemeModeDarkButton.IsChecked = true; + break; + default: + ThemeModeDefaultButton.IsChecked = true; + break; } AccentColorToggle.IsOn = ThemeSettingsService.UseWindowsAccentColor; @@ -124,15 +120,13 @@ private void ThemeRadioButton_OnChecked(object sender, RoutedEventArgs e) switch (radioButton.Tag) { case "Light": - ThemeSettingsService.UseWindowsTheme = false; - ThemeSettingsService.SetTheme(ElementTheme.Light); + ThemeSettingsService.ThemeMode = ElementTheme.Light; break; case "Dark": - ThemeSettingsService.UseWindowsTheme = false; - ThemeSettingsService.SetTheme(ElementTheme.Dark); + ThemeSettingsService.ThemeMode = ElementTheme.Dark; break; case "Default": - ThemeSettingsService.UseWindowsTheme = true; + ThemeSettingsService.ThemeMode = ElementTheme.Default; break; } } From 281edc7e17ace175410706d4e8d331057bf50583 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 26 Jun 2020 08:44:38 +0530 Subject: [PATCH 025/181] fixed. --- src/Notepads/App.xaml.cs | 13 ++++++++++ src/Notepads/Services/AppSettingsService.cs | 26 +++++++++---------- src/Notepads/Services/ThemeSettingsService.cs | 8 +++--- 3 files changed, 30 insertions(+), 17 deletions(-) diff --git a/src/Notepads/App.xaml.cs b/src/Notepads/App.xaml.cs index 58641361d..4f8f605bc 100644 --- a/src/Notepads/App.xaml.cs +++ b/src/Notepads/App.xaml.cs @@ -51,6 +51,7 @@ public App() InitializeComponent(); Suspending += OnSuspending; + LeavingBackground += OnLeavingBackground; } /// @@ -197,6 +198,18 @@ private void OnSuspending(object sender, SuspendingEventArgs e) deferral.Complete(); } + /// + /// Occurs when the app moves to foreground from background. + /// Pending changes to the UI is made before app comes to focus. + /// + /// The source of the leaving background request. + /// Details about the leaving background request. + private void OnLeavingBackground(object sender, LeavingBackgroundEventArgs e) + { + ThemeSettingsService.Initialize(true); + AppSettingsService.Initialize(true); + } + // Occurs when an exception is not handled on the UI thread. private static void OnUnhandledException(object sender, Windows.UI.Xaml.UnhandledExceptionEventArgs e) { diff --git a/src/Notepads/Services/AppSettingsService.cs b/src/Notepads/Services/AppSettingsService.cs index 3966aa59d..d395259b6 100644 --- a/src/Notepads/Services/AppSettingsService.cs +++ b/src/Notepads/Services/AppSettingsService.cs @@ -284,34 +284,34 @@ public static bool IsSmartCopyEnabled } } - public static void Initialize() + public static void Initialize(bool shouldInvokeChangedEvent = false) { - InitializeFontFamilySettings(); - InitializeFontSizeSettings(); - InitializeFontStyleSettings(); - InitializeFontWeightSettings(); + InitializeFontFamilySettings(shouldInvokeChangedEvent); + InitializeFontSizeSettings(shouldInvokeChangedEvent); + InitializeFontStyleSettings(shouldInvokeChangedEvent); + InitializeFontWeightSettings(shouldInvokeChangedEvent); - InitializeTextWrappingSettings(); + InitializeTextWrappingSettings(shouldInvokeChangedEvent); - InitializeSpellingSettings(); + InitializeSpellingSettings(shouldInvokeChangedEvent); - InitializeDisplayLineHighlighterSettings(); - InitializeDisplayLineNumbersSettings(); + InitializeDisplayLineHighlighterSettings(shouldInvokeChangedEvent); + InitializeDisplayLineNumbersSettings(shouldInvokeChangedEvent); InitializeSmartCopySettings(); - InitializeLineEndingSettings(); + InitializeLineEndingSettings(shouldInvokeChangedEvent); - InitializeEncodingSettings(); + InitializeEncodingSettings(shouldInvokeChangedEvent); InitializeDecodingSettings(); - InitializeTabIndentsSettings(); + InitializeTabIndentsSettings(shouldInvokeChangedEvent); InitializeSearchEngineSettings(); InitializeCustomSearchUrlSettings(); - InitializeStatusBarSettings(); + InitializeStatusBarSettings(shouldInvokeChangedEvent); InitializeSessionSnapshotSettings(); diff --git a/src/Notepads/Services/ThemeSettingsService.cs b/src/Notepads/Services/ThemeSettingsService.cs index c3c1e1695..993595fcf 100644 --- a/src/Notepads/Services/ThemeSettingsService.cs +++ b/src/Notepads/Services/ThemeSettingsService.cs @@ -92,15 +92,15 @@ public static Color CustomAccentColor } } - public static void Initialize() + public static void Initialize(bool shouldInvokeChangedEvent = false) { - InitializeThemeMode(); + InitializeThemeMode(shouldInvokeChangedEvent); - InitializeAppAccentColor(); + InitializeAppAccentColor(shouldInvokeChangedEvent); InitializeCustomAccentColor(); - InitializeAppBackgroundPanelTintOpacity(); + InitializeAppBackgroundPanelTintOpacity(shouldInvokeChangedEvent); } public static void InitializeAppAccentColor(bool invokeChangedEvent = false) From 2bb7a86e47347e96c0281993ea0c14628262b0c9 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 27 Jun 2020 15:25:32 +0530 Subject: [PATCH 026/181] fixed. --- src/Notepads.DesktopExtension/Program.cs | 4 +--- src/Notepads.Package/Notepads.Package.wapproj | 2 +- src/Notepads.Package/Package.appxmanifest | 4 ++-- ...e.cs => DesktopExtensionConnectionService.cs} | 16 +--------------- src/Notepads.Services/Notepads.Services.csproj | 4 ++-- .../Connected Services/AdminService/Reference.cs | 2 +- .../AdminService/Reference.svcmap | 10 +++++----- src/Notepads/Controls/Dialog/NotepadsDialog.cs | 4 ++-- src/Notepads/Notepads.csproj | 12 ++++++------ ...eropService.cs => DesktopExtensionService.cs} | 7 ++++--- src/Notepads/Services/ThemeSettingsService.cs | 15 ++++++++++++--- src/Notepads/Utilities/FileSystemUtility.cs | 2 +- .../Views/MainPage/NotepadsMainPage.IO.cs | 2 +- .../Views/MainPage/NotepadsMainPage.xaml.cs | 6 +++--- 14 files changed, 42 insertions(+), 48 deletions(-) rename src/Notepads.Services/{InteropConnectionService.cs => DesktopExtensionConnectionService.cs} (87%) rename src/Notepads/Services/{InteropService.cs => DesktopExtensionService.cs} (95%) diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs index 26dc284aa..edf659f88 100644 --- a/src/Notepads.DesktopExtension/Program.cs +++ b/src/Notepads.DesktopExtension/Program.cs @@ -14,8 +14,6 @@ public enum CommandArgs { - SyncSettings, - SyncRecentList, RegisterExtension, CreateElevetedExtension, ExitApp @@ -57,7 +55,7 @@ private static async void InitializeAppServiceConnection() { connection = new AppServiceConnection() { - AppServiceName = "InteropServiceConnection", + AppServiceName = "DesktopExtensionServiceConnection", PackageFamilyName = Package.Current.Id.FamilyName }; diff --git a/src/Notepads.Package/Notepads.Package.wapproj b/src/Notepads.Package/Notepads.Package.wapproj index 4b7b027e8..05ebde22e 100644 --- a/src/Notepads.Package/Notepads.Package.wapproj +++ b/src/Notepads.Package/Notepads.Package.wapproj @@ -51,7 +51,7 @@ f451c0eb-4f7f-47d4-bcce-b0e265909dd9 - 10.0.18362.0 + 10.0.19041.0 10.0.17763.0 en-US false diff --git a/src/Notepads.Package/Package.appxmanifest b/src/Notepads.Package/Package.appxmanifest index 83efe5fe0..56b1a429c 100644 --- a/src/Notepads.Package/Package.appxmanifest +++ b/src/Notepads.Package/Package.appxmanifest @@ -71,8 +71,8 @@ - - + + diff --git a/src/Notepads.Services/InteropConnectionService.cs b/src/Notepads.Services/DesktopExtensionConnectionService.cs similarity index 87% rename from src/Notepads.Services/InteropConnectionService.cs rename to src/Notepads.Services/DesktopExtensionConnectionService.cs index f53ba23a2..d005755dd 100644 --- a/src/Notepads.Services/InteropConnectionService.cs +++ b/src/Notepads.Services/DesktopExtensionConnectionService.cs @@ -10,14 +10,12 @@ public enum CommandArgs { - SyncSettings, - SyncRecentList, RegisterExtension, CreateElevetedExtension, ExitApp } - public sealed class InteropConnectionService : IBackgroundTask + public sealed class DesktopExtensionConnectionService : IBackgroundTask { private BackgroundTaskDeferral backgroundTaskDeferral; private AppServiceConnection appServiceConnection; @@ -61,18 +59,6 @@ private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequ switch (command) { - case CommandArgs.SyncSettings: - Parallel.ForEach(appServiceConnections, async (serviceConnection) => - { - if (serviceConnection != appServiceConnection) await serviceConnection.SendMessageAsync(args.Request.Message); - }); - break; - case CommandArgs.SyncRecentList: - Parallel.ForEach(appServiceConnections, async (serviceConnection) => - { - if (serviceConnection != appServiceConnection) await serviceConnection.SendMessageAsync(args.Request.Message); - }); - break; case CommandArgs.RegisterExtension: appServiceConnections.Remove(appServiceConnection); if (extensionAppServiceConnection == null) diff --git a/src/Notepads.Services/Notepads.Services.csproj b/src/Notepads.Services/Notepads.Services.csproj index 1c6074764..28d1b3e89 100644 --- a/src/Notepads.Services/Notepads.Services.csproj +++ b/src/Notepads.Services/Notepads.Services.csproj @@ -11,7 +11,7 @@ Notepads.Services en-US UAP - 10.0.18362.0 + 10.0.19041.0 10.0.17763.0 14 512 @@ -121,7 +121,7 @@ PackageReference - + diff --git a/src/Notepads/Connected Services/AdminService/Reference.cs b/src/Notepads/Connected Services/AdminService/Reference.cs index 2fcea6ce4..9b51d2c4b 100644 --- a/src/Notepads/Connected Services/AdminService/Reference.cs +++ b/src/Notepads/Connected Services/AdminService/Reference.cs @@ -9,7 +9,7 @@ //------------------------------------------------------------------------------ // -// This code was auto-generated by Microsoft.VisualStudio.ServiceReference.Platforms, version 16.0.30104.148 +// This code was auto-generated by Microsoft.VisualStudio.ServiceReference.Platforms, version 16.0.30114.105 // namespace Notepads.AdminService { diff --git a/src/Notepads/Connected Services/AdminService/Reference.svcmap b/src/Notepads/Connected Services/AdminService/Reference.svcmap index 0e9f5cdca..de3cc7c29 100644 --- a/src/Notepads/Connected Services/AdminService/Reference.svcmap +++ b/src/Notepads/Connected Services/AdminService/Reference.svcmap @@ -1,5 +1,5 @@ - + false true @@ -24,10 +24,10 @@ - - - - + + + + diff --git a/src/Notepads/Controls/Dialog/NotepadsDialog.cs b/src/Notepads/Controls/Dialog/NotepadsDialog.cs index bb27e1b9c..73c82d856 100644 --- a/src/Notepads/Controls/Dialog/NotepadsDialog.cs +++ b/src/Notepads/Controls/Dialog/NotepadsDialog.cs @@ -17,8 +17,8 @@ public class NotepadsDialog : ContentDialog public NotepadsDialog() { - RequestedTheme = ThemeSettingsService.ThemeMode; - Background = ThemeSettingsService.ThemeMode == ElementTheme.Dark + RequestedTheme = ThemeSettingsService.GetActualTheme(ThemeSettingsService.ThemeMode); + Background = RequestedTheme == ElementTheme.Dark ? _darkModeBackgroundBrush : _lightModeBackgroundBrush; diff --git a/src/Notepads/Notepads.csproj b/src/Notepads/Notepads.csproj index 0c1783aba..f310a1e1e 100644 --- a/src/Notepads/Notepads.csproj +++ b/src/Notepads/Notepads.csproj @@ -109,6 +109,11 @@ + + True + True + Reference.svcmap + @@ -116,11 +121,6 @@ - - True - True - Reference.svcmap - FindAndReplaceControl.xaml @@ -142,7 +142,7 @@ - + diff --git a/src/Notepads/Services/InteropService.cs b/src/Notepads/Services/DesktopExtensionService.cs similarity index 95% rename from src/Notepads/Services/InteropService.cs rename to src/Notepads/Services/DesktopExtensionService.cs index f0d45db30..3f7a603a9 100644 --- a/src/Notepads/Services/InteropService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -10,6 +10,7 @@ using Windows.ApplicationModel.Core; using Windows.ApplicationModel.Resources; using Windows.Foundation.Collections; + using Windows.UI.Core; using Windows.UI.ViewManagement; using Windows.UI.Xaml; @@ -18,7 +19,7 @@ public class AdminstratorAccessException : Exception public AdminstratorAccessException():base("Failed to save due to no Adminstration access") { } } - public static class InteropService + public static class DesktopExtensionService { public static AppServiceConnection InteropServiceConnection = null; public static AdminServiceClient AdminServiceClient = new AdminServiceClient(); @@ -33,7 +34,7 @@ public static async Task Initialize() { InteropServiceConnection = new AppServiceConnection() { - AppServiceName = "InteropServiceConnection", + AppServiceName = "DesktopExtensionServiceConnection", PackageFamilyName = Package.Current.Id.FamilyName }; @@ -51,7 +52,7 @@ private static async void InteropServiceConnection_RequestReceived(AppServiceCon if (!message.ContainsKey(_commandLabel) || !Enum.TryParse(typeof(CommandArgs), (string)message[_commandLabel], out var commandObj) || (CommandArgs)commandObj != CommandArgs.CreateElevetedExtension) return; - await DispatcherExtensions.CallOnUIThreadAsync(CoreApplication.GetCurrentView().Dispatcher, () => + await CoreApplication.MainView.CoreWindow.Dispatcher.CallOnUIThreadAsync(() => { if (message.ContainsKey(_adminCreatedLabel) && (bool)message[_adminCreatedLabel]) { diff --git a/src/Notepads/Services/ThemeSettingsService.cs b/src/Notepads/Services/ThemeSettingsService.cs index d0c014e87..28af828bf 100644 --- a/src/Notepads/Services/ThemeSettingsService.cs +++ b/src/Notepads/Services/ThemeSettingsService.cs @@ -202,7 +202,7 @@ public static void SetRequestedTheme(Panel backgroundPanel, UIElement currentCon // Set ContentDialog background dimming color var themeMode = ThemeMode; - if (themeMode == ElementTheme.Default) themeMode = Application.Current.RequestedTheme.ToElementTheme(); + themeMode = GetActualTheme(themeMode); ((SolidColorBrush)Application.Current.Resources["SystemControlPageBackgroundMediumAltMediumBrush"]).Color = themeMode == ElementTheme.Dark ? Color.FromArgb(153, 0, 0, 0) : Color.FromArgb(153, 255, 255, 255); @@ -233,12 +233,21 @@ public static ElementTheme ToElementTheme(this ApplicationTheme theme) } } + public static ElementTheme GetActualTheme(ElementTheme theme) + { + if (theme == ElementTheme.Default) + return Application.Current.RequestedTheme.ToElementTheme(); + else + return theme; + } + + private static Brush GetAppBackgroundBrush(ElementTheme theme) { var darkModeBaseColor = Color.FromArgb(255, 46, 46, 46); var lightModeBaseColor = Color.FromArgb(255, 240, 240, 240); - if (theme == ElementTheme.Default) theme = Application.Current.RequestedTheme.ToElementTheme(); + theme = GetActualTheme(theme); var baseColor = theme == ElementTheme.Light ? lightModeBaseColor : darkModeBaseColor; if (AppBackgroundPanelTintOpacity > 0.99f || @@ -261,7 +270,7 @@ private static Brush GetAppBackgroundBrush(ElementTheme theme) public static void ApplyThemeForTitleBarButtons(ApplicationViewTitleBar titleBar, ElementTheme theme) { - if (theme == ElementTheme.Default) theme = Application.Current.RequestedTheme.ToElementTheme(); + theme = GetActualTheme(theme); if (theme == ElementTheme.Dark) { // Set active window colors diff --git a/src/Notepads/Utilities/FileSystemUtility.cs b/src/Notepads/Utilities/FileSystemUtility.cs index d4c5040f5..868ce3beb 100644 --- a/src/Notepads/Utilities/FileSystemUtility.cs +++ b/src/Notepads/Utilities/FileSystemUtility.cs @@ -546,7 +546,7 @@ public static async Task WriteToFile(string text, Encoding encoding, StorageFile { throw ex; } - await InteropService.SaveFileAsAdmin(file.Path, result); + await DesktopExtensionService.SaveFileAsAdmin(file.Path, result); } } else // Use StorageFile API to save diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs index f44e140b2..f6af935c1 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs @@ -193,7 +193,7 @@ private async Task Save(ITextEditor textEditor, bool saveAs, bool ignoreUn var createElevatedExtensionDialog = new CreateElevatedExtensionDialog( async () => { - await InteropService.CreateElevetedExtension(); + await DesktopExtensionService.CreateElevetedExtension(); }, () => { diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs index 81f2fc85a..e43dfd586 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs @@ -278,7 +278,7 @@ private async void Sets_Loaded(object sender, RoutedEventArgs e) Window.Current.CoreWindow.Activated += CoreWindow_Activated; } - await InteropService.Initialize(); + await DesktopExtensionService.Initialize(); } private async void App_EnteredBackground(object sender, Windows.ApplicationModel.EnteredBackgroundEventArgs e) @@ -290,13 +290,13 @@ private async void App_EnteredBackground(object sender, Windows.ApplicationModel await SessionManager.SaveSessionAsync(); } - InteropService.InteropServiceConnection.Dispose(); + DesktopExtensionService.InteropServiceConnection.Dispose(); deferral.Complete(); } private async void App_LeavingBackground(object sender, LeavingBackgroundEventArgs e) { - await InteropService.Initialize(); + await DesktopExtensionService.Initialize(); } public void ExecuteProtocol(Uri uri) From b46d77e98d45f40d9bb5e1afcd0138c7362f39b1 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 27 Jun 2020 15:33:21 +0530 Subject: [PATCH 027/181] fixed. --- src/Notepads/Services/DesktopExtensionService.cs | 1 - src/Notepads/Services/ThemeSettingsService.cs | 1 - 2 files changed, 2 deletions(-) diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index 3f7a603a9..c9abd8411 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -10,7 +10,6 @@ using Windows.ApplicationModel.Core; using Windows.ApplicationModel.Resources; using Windows.Foundation.Collections; - using Windows.UI.Core; using Windows.UI.ViewManagement; using Windows.UI.Xaml; diff --git a/src/Notepads/Services/ThemeSettingsService.cs b/src/Notepads/Services/ThemeSettingsService.cs index 28af828bf..55c38fe75 100644 --- a/src/Notepads/Services/ThemeSettingsService.cs +++ b/src/Notepads/Services/ThemeSettingsService.cs @@ -241,7 +241,6 @@ public static ElementTheme GetActualTheme(ElementTheme theme) return theme; } - private static Brush GetAppBackgroundBrush(ElementTheme theme) { var darkModeBaseColor = Color.FromArgb(255, 46, 46, 46); From 3ceb36998f057cd2182b66f83edb27bd3b754962 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 27 Jun 2020 18:12:52 +0530 Subject: [PATCH 028/181] fixed. --- .../ExtensionService/ExtensionService.disco | 4 - .../ExtensionService/ExtensionService.wsdl | 76 ----------- .../ExtensionService/ExtensionService.xsd | 43 ------ .../ExtensionService/ExtensionService1.xsd | 42 ------ .../ExtensionService/Reference.cs | 126 ------------------ .../ExtensionService/Reference.svcmap | 36 ----- .../ExtensionService/configuration.svcinfo | 6 - .../ExtensionService/configuration91.svcinfo | 5 - 8 files changed, 338 deletions(-) delete mode 100644 src/Notepads/Connected Services/ExtensionService/ExtensionService.disco delete mode 100644 src/Notepads/Connected Services/ExtensionService/ExtensionService.wsdl delete mode 100644 src/Notepads/Connected Services/ExtensionService/ExtensionService.xsd delete mode 100644 src/Notepads/Connected Services/ExtensionService/ExtensionService1.xsd delete mode 100644 src/Notepads/Connected Services/ExtensionService/Reference.cs delete mode 100644 src/Notepads/Connected Services/ExtensionService/Reference.svcmap delete mode 100644 src/Notepads/Connected Services/ExtensionService/configuration.svcinfo delete mode 100644 src/Notepads/Connected Services/ExtensionService/configuration91.svcinfo diff --git a/src/Notepads/Connected Services/ExtensionService/ExtensionService.disco b/src/Notepads/Connected Services/ExtensionService/ExtensionService.disco deleted file mode 100644 index bd7d02c9a..000000000 --- a/src/Notepads/Connected Services/ExtensionService/ExtensionService.disco +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/src/Notepads/Connected Services/ExtensionService/ExtensionService.wsdl b/src/Notepads/Connected Services/ExtensionService/ExtensionService.wsdl deleted file mode 100644 index e55efcf10..000000000 --- a/src/Notepads/Connected Services/ExtensionService/ExtensionService.wsdl +++ /dev/null @@ -1,76 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Notepads/Connected Services/ExtensionService/ExtensionService.xsd b/src/Notepads/Connected Services/ExtensionService/ExtensionService.xsd deleted file mode 100644 index 87353d604..000000000 --- a/src/Notepads/Connected Services/ExtensionService/ExtensionService.xsd +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Notepads/Connected Services/ExtensionService/ExtensionService1.xsd b/src/Notepads/Connected Services/ExtensionService/ExtensionService1.xsd deleted file mode 100644 index d58e7f39c..000000000 --- a/src/Notepads/Connected Services/ExtensionService/ExtensionService1.xsd +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Notepads/Connected Services/ExtensionService/Reference.cs b/src/Notepads/Connected Services/ExtensionService/Reference.cs deleted file mode 100644 index 24ed5461a..000000000 --- a/src/Notepads/Connected Services/ExtensionService/Reference.cs +++ /dev/null @@ -1,126 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -// -// This code was auto-generated by Microsoft.VisualStudio.ServiceReference.Platforms, version 16.0.30011.22 -// -namespace Notepads.ExtensionService { - - - [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] - [System.ServiceModel.ServiceContractAttribute(ConfigurationName="ExtensionService.IExtensionService")] - public interface IExtensionService { - - [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IExtensionService/DoWork", ReplyAction="http://tempuri.org/IExtensionService/DoWorkResponse")] - System.Threading.Tasks.Task DoWorkAsync(); - - [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IExtensionService/ReplaceFile", ReplyAction="http://tempuri.org/IExtensionService/ReplaceFileResponse")] - System.Threading.Tasks.Task ReplaceFileAsync(string newPath, string oldPath); - - [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IExtensionService/Add", ReplyAction="http://tempuri.org/IExtensionService/AddResponse")] - System.Threading.Tasks.Task AddAsync(int a, int b); - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] - public interface IExtensionServiceChannel : Notepads.ExtensionService.IExtensionService, System.ServiceModel.IClientChannel { - } - - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] - public partial class ExtensionServiceClient : System.ServiceModel.ClientBase, Notepads.ExtensionService.IExtensionService { - - /// - /// Implement this partial method to configure the service endpoint. - /// - /// The endpoint to configure - /// The client credentials - static partial void ConfigureEndpoint(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint, System.ServiceModel.Description.ClientCredentials clientCredentials); - - public ExtensionServiceClient() : - base(ExtensionServiceClient.GetDefaultBinding(), ExtensionServiceClient.GetDefaultEndpointAddress()) { - this.Endpoint.Name = EndpointConfiguration.BasicHttpBinding_IExtensionService.ToString(); - ConfigureEndpoint(this.Endpoint, this.ClientCredentials); - } - - public ExtensionServiceClient(EndpointConfiguration endpointConfiguration) : - base(ExtensionServiceClient.GetBindingForEndpoint(endpointConfiguration), ExtensionServiceClient.GetEndpointAddress(endpointConfiguration)) { - this.Endpoint.Name = endpointConfiguration.ToString(); - ConfigureEndpoint(this.Endpoint, this.ClientCredentials); - } - - public ExtensionServiceClient(EndpointConfiguration endpointConfiguration, string remoteAddress) : - base(ExtensionServiceClient.GetBindingForEndpoint(endpointConfiguration), new System.ServiceModel.EndpointAddress(remoteAddress)) { - this.Endpoint.Name = endpointConfiguration.ToString(); - ConfigureEndpoint(this.Endpoint, this.ClientCredentials); - } - - public ExtensionServiceClient(EndpointConfiguration endpointConfiguration, System.ServiceModel.EndpointAddress remoteAddress) : - base(ExtensionServiceClient.GetBindingForEndpoint(endpointConfiguration), remoteAddress) { - this.Endpoint.Name = endpointConfiguration.ToString(); - ConfigureEndpoint(this.Endpoint, this.ClientCredentials); - } - - public ExtensionServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : - base(binding, remoteAddress) { - } - - public System.Threading.Tasks.Task DoWorkAsync() { - return base.Channel.DoWorkAsync(); - } - - public System.Threading.Tasks.Task ReplaceFileAsync(string newPath, string oldPath) { - return base.Channel.ReplaceFileAsync(newPath, oldPath); - } - - public System.Threading.Tasks.Task AddAsync(int a, int b) { - return base.Channel.AddAsync(a, b); - } - - public virtual System.Threading.Tasks.Task OpenAsync() { - return System.Threading.Tasks.Task.Factory.FromAsync(((System.ServiceModel.ICommunicationObject)(this)).BeginOpen(null, null), new System.Action(((System.ServiceModel.ICommunicationObject)(this)).EndOpen)); - } - - public virtual System.Threading.Tasks.Task CloseAsync() { - return System.Threading.Tasks.Task.Factory.FromAsync(((System.ServiceModel.ICommunicationObject)(this)).BeginClose(null, null), new System.Action(((System.ServiceModel.ICommunicationObject)(this)).EndClose)); - } - - private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(EndpointConfiguration endpointConfiguration) { - if ((endpointConfiguration == EndpointConfiguration.BasicHttpBinding_IExtensionService)) { - System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding(); - result.MaxBufferSize = int.MaxValue; - result.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max; - result.MaxReceivedMessageSize = int.MaxValue; - result.AllowCookies = true; - return result; - } - throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration)); - } - - private static System.ServiceModel.EndpointAddress GetEndpointAddress(EndpointConfiguration endpointConfiguration) { - if ((endpointConfiguration == EndpointConfiguration.BasicHttpBinding_IExtensionService)) { - return new System.ServiceModel.EndpointAddress("http://localhost:8000/Notepads.DesktopExtension/ExtensionService"); - } - throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration)); - } - - private static System.ServiceModel.Channels.Binding GetDefaultBinding() { - return ExtensionServiceClient.GetBindingForEndpoint(EndpointConfiguration.BasicHttpBinding_IExtensionService); - } - - private static System.ServiceModel.EndpointAddress GetDefaultEndpointAddress() { - return ExtensionServiceClient.GetEndpointAddress(EndpointConfiguration.BasicHttpBinding_IExtensionService); - } - - public enum EndpointConfiguration { - - BasicHttpBinding_IExtensionService, - } - } -} diff --git a/src/Notepads/Connected Services/ExtensionService/Reference.svcmap b/src/Notepads/Connected Services/ExtensionService/Reference.svcmap deleted file mode 100644 index 34ca65556..000000000 --- a/src/Notepads/Connected Services/ExtensionService/Reference.svcmap +++ /dev/null @@ -1,36 +0,0 @@ - - - - false - true - true - - false - false - false - - - - - false - Auto - true - true - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Notepads/Connected Services/ExtensionService/configuration.svcinfo b/src/Notepads/Connected Services/ExtensionService/configuration.svcinfo deleted file mode 100644 index d3da738a3..000000000 --- a/src/Notepads/Connected Services/ExtensionService/configuration.svcinfo +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/src/Notepads/Connected Services/ExtensionService/configuration91.svcinfo b/src/Notepads/Connected Services/ExtensionService/configuration91.svcinfo deleted file mode 100644 index 08bf21e68..000000000 --- a/src/Notepads/Connected Services/ExtensionService/configuration91.svcinfo +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file From 6a9131a65c05107b1abdf62307146fa5473e129d Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 27 Jun 2020 20:10:09 +0530 Subject: [PATCH 029/181] fixed. --- src/Notepads/Services/AppSettingsService.cs | 24 ++++---- .../Services/InterInstanceSyncService.cs | 55 +++++++++---------- src/Notepads/Services/ThemeSettingsService.cs | 4 +- .../MainPage/NotepadsMainPage.MainMenu.cs | 3 +- .../PersonalizationSettingsPage.xaml.cs | 2 +- 5 files changed, 44 insertions(+), 44 deletions(-) diff --git a/src/Notepads/Services/AppSettingsService.cs b/src/Notepads/Services/AppSettingsService.cs index d395259b6..5e65d62b3 100644 --- a/src/Notepads/Services/AppSettingsService.cs +++ b/src/Notepads/Services/AppSettingsService.cs @@ -298,24 +298,24 @@ public static void Initialize(bool shouldInvokeChangedEvent = false) InitializeDisplayLineHighlighterSettings(shouldInvokeChangedEvent); InitializeDisplayLineNumbersSettings(shouldInvokeChangedEvent); - InitializeSmartCopySettings(); + InitializeSmartCopySettings(shouldInvokeChangedEvent); InitializeLineEndingSettings(shouldInvokeChangedEvent); InitializeEncodingSettings(shouldInvokeChangedEvent); - InitializeDecodingSettings(); + InitializeDecodingSettings(shouldInvokeChangedEvent); InitializeTabIndentsSettings(shouldInvokeChangedEvent); - InitializeSearchEngineSettings(); - InitializeCustomSearchUrlSettings(); + InitializeSearchEngineSettings(shouldInvokeChangedEvent); + InitializeCustomSearchUrlSettings(shouldInvokeChangedEvent); InitializeStatusBarSettings(shouldInvokeChangedEvent); - InitializeSessionSnapshotSettings(); + InitializeSessionSnapshotSettings(shouldInvokeChangedEvent); - InitializeAppOpeningPreferencesSettings(); + InitializeAppOpeningPreferencesSettings(shouldInvokeChangedEvent); } public static void InitializeStatusBarSettings(bool invokeChangedEvent = false) @@ -332,7 +332,7 @@ public static void InitializeStatusBarSettings(bool invokeChangedEvent = false) if (invokeChangedEvent) OnStatusBarVisibilityChanged?.Invoke(null, _showStatusBar); } - private static void InitializeSessionSnapshotSettings() + private static void InitializeSessionSnapshotSettings(bool invokeChangedEvent = false) { // We should disable session snapshot feature on multi instances if (!App.IsFirstInstance) @@ -428,7 +428,7 @@ public static void InitializeDisplayLineNumbersSettings(bool invokeChangedEvent if (invokeChangedEvent) OnDefaultDisplayLineNumbersViewStateChanged?.Invoke(null, _displayLineNumbers); } - public static void InitializeSmartCopySettings() + public static void InitializeSmartCopySettings(bool invokeChangedEvent = false) { if (ApplicationSettingsStore.Read(SettingsKey.EditorEnableSmartCopyBool) is bool enableSmartCopy) { @@ -470,7 +470,7 @@ public static void InitializeEncodingSettings(bool invokeChangedEvent = false) if (invokeChangedEvent) OnDefaultEncodingChanged?.Invoke(null, _editorDefaultEncoding); } - public static void InitializeDecodingSettings() + public static void InitializeDecodingSettings(bool invokeChangedEvent = false) { if (ApplicationSettingsStore.Read(SettingsKey.EditorDefaultDecodingCodePageInt) is int decodingCodePage) { @@ -516,7 +516,7 @@ public static void InitializeTabIndentsSettings(bool invokeChangedEvent = false) if (invokeChangedEvent) OnDefaultTabIndentsChanged?.Invoke(null, _editorDefaultTabIndents); } - public static void InitializeSearchEngineSettings() + public static void InitializeSearchEngineSettings(bool invokeChangedEvent = false) { if (ApplicationSettingsStore.Read(SettingsKey.EditorDefaultSearchEngineStr) is string searchEngineStr && Enum.TryParse(typeof(SearchEngine), searchEngineStr, out var searchEngine)) @@ -529,7 +529,7 @@ public static void InitializeSearchEngineSettings() } } - public static void InitializeCustomSearchUrlSettings() + public static void InitializeCustomSearchUrlSettings(bool invokeChangedEvent = false) { if (ApplicationSettingsStore.Read(SettingsKey.EditorCustomMadeSearchUrlStr) is string customMadeSearchUrl) { @@ -601,7 +601,7 @@ public static void InitializeFontWeightSettings(bool invokeChangedEvent = false) if (invokeChangedEvent) OnFontWeightChanged?.Invoke(null, _editorFontWeight); } - public static void InitializeAppOpeningPreferencesSettings() + public static void InitializeAppOpeningPreferencesSettings(bool invokeChangedEvent = false) { if (ApplicationSettingsStore.Read(SettingsKey.AlwaysOpenNewWindowBool) is bool alwaysOpenNewWindow) { diff --git a/src/Notepads/Services/InterInstanceSyncService.cs b/src/Notepads/Services/InterInstanceSyncService.cs index 751040a5b..05176b813 100644 --- a/src/Notepads/Services/InterInstanceSyncService.cs +++ b/src/Notepads/Services/InterInstanceSyncService.cs @@ -11,33 +11,33 @@ public static class InterInstanceSyncService { private static NotepadsMainPage _notepadsMainPage = null; - public static readonly string OpenRecentKey = "BuildOpenRecentButtonSubItems"; + public static readonly string RecentFilesListKey = "BuildOpenRecentButtonSubItems"; - public static IReadOnlyDictionary SyncManager = new Dictionary + public static IReadOnlyDictionary> SyncManager = new Dictionary> { - {SettingsKey.AppBackgroundTintOpacityDouble, () => ThemeSettingsService.InitializeAppBackgroundPanelTintOpacity(true)}, - {SettingsKey.RequestedThemeStr, () => ThemeSettingsService.InitializeThemeMode(true)}, - {SettingsKey.UseWindowsAccentColorBool, () => { } }, - {SettingsKey.AppAccentColorHexStr, () => { } }, - {SettingsKey.CustomAccentColorHexStr, () => ThemeSettingsService.InitializeCustomAccentColor()}, - {SettingsKey.EditorDefaultLineHighlighterViewStateBool, () => AppSettingsService.InitializeDisplayLineHighlighterSettings(true)}, - {SettingsKey.EditorDefaultDisplayLineNumbersBool, () => AppSettingsService.InitializeDisplayLineNumbersSettings(true)}, - {SettingsKey.EditorDefaultTabIndentsInt, () => AppSettingsService.InitializeTabIndentsSettings(true)}, - {SettingsKey.EditorDefaultTextWrappingStr, () => AppSettingsService.InitializeTextWrappingSettings(true)}, - {SettingsKey.EditorFontFamilyStr, () => AppSettingsService.InitializeFontFamilySettings(true)}, - {SettingsKey.EditorFontSizeInt, () => AppSettingsService.InitializeFontSizeSettings(true)}, - {SettingsKey.EditorFontStyleStr, () => AppSettingsService.InitializeFontStyleSettings(true)}, - {SettingsKey.EditorFontWeightUshort, () => AppSettingsService.InitializeFontWeightSettings(true)}, - {SettingsKey.EditorHighlightMisspelledWordsBool, () => AppSettingsService.InitializeSpellingSettings(true)}, - {SettingsKey.EditorDefaultEncodingCodePageInt, () => AppSettingsService.InitializeEncodingSettings(true)}, - {SettingsKey.EditorDefaultLineEndingStr, () => AppSettingsService.InitializeLineEndingSettings(true)}, - {SettingsKey.EditorShowStatusBarBool, () => AppSettingsService.InitializeStatusBarSettings(true)}, - {SettingsKey.EditorCustomMadeSearchUrlStr, () => AppSettingsService.InitializeCustomSearchUrlSettings()}, - {SettingsKey.EditorDefaultDecodingCodePageInt, () => AppSettingsService.InitializeDecodingSettings()}, - {SettingsKey.EditorDefaultSearchEngineStr, () => AppSettingsService.InitializeSearchEngineSettings()}, - {SettingsKey.EditorEnableSmartCopyBool, () => AppSettingsService.InitializeSmartCopySettings() }, - {SettingsKey.AlwaysOpenNewWindowBool, () => AppSettingsService.InitializeAppOpeningPreferencesSettings() }, - {OpenRecentKey, async () => await _notepadsMainPage.BuildOpenRecentButtonSubItems(false) } + {SettingsKey.AppBackgroundTintOpacityDouble, ThemeSettingsService.InitializeAppBackgroundPanelTintOpacity }, + {SettingsKey.RequestedThemeStr, ThemeSettingsService.InitializeThemeMode }, + {SettingsKey.UseWindowsAccentColorBool, ThemeSettingsService.InitializeAppAccentColor }, + {SettingsKey.AppAccentColorHexStr, ThemeSettingsService.InitializeAppAccentColor }, + {SettingsKey.CustomAccentColorHexStr, ThemeSettingsService.InitializeCustomAccentColor }, + {SettingsKey.EditorDefaultLineHighlighterViewStateBool, AppSettingsService.InitializeDisplayLineHighlighterSettings }, + {SettingsKey.EditorDefaultDisplayLineNumbersBool, AppSettingsService.InitializeDisplayLineNumbersSettings }, + {SettingsKey.EditorDefaultTabIndentsInt, AppSettingsService.InitializeTabIndentsSettings }, + {SettingsKey.EditorDefaultTextWrappingStr, AppSettingsService.InitializeTextWrappingSettings }, + {SettingsKey.EditorFontFamilyStr, AppSettingsService.InitializeFontFamilySettings }, + {SettingsKey.EditorFontSizeInt, AppSettingsService.InitializeFontSizeSettings }, + {SettingsKey.EditorFontStyleStr, AppSettingsService.InitializeFontStyleSettings }, + {SettingsKey.EditorFontWeightUshort, AppSettingsService.InitializeFontWeightSettings }, + {SettingsKey.EditorHighlightMisspelledWordsBool, AppSettingsService.InitializeSpellingSettings }, + {SettingsKey.EditorDefaultEncodingCodePageInt, AppSettingsService.InitializeEncodingSettings }, + {SettingsKey.EditorDefaultLineEndingStr, AppSettingsService.InitializeLineEndingSettings }, + {SettingsKey.EditorShowStatusBarBool, AppSettingsService.InitializeStatusBarSettings }, + {SettingsKey.EditorCustomMadeSearchUrlStr, AppSettingsService.InitializeCustomSearchUrlSettings }, + {SettingsKey.EditorDefaultDecodingCodePageInt, AppSettingsService.InitializeDecodingSettings }, + {SettingsKey.EditorDefaultSearchEngineStr, AppSettingsService.InitializeSearchEngineSettings }, + {SettingsKey.EditorEnableSmartCopyBool, AppSettingsService.InitializeSmartCopySettings }, + {SettingsKey.AlwaysOpenNewWindowBool, AppSettingsService.InitializeAppOpeningPreferencesSettings }, + {RecentFilesListKey, async (permission) => await _notepadsMainPage.BuildOpenRecentButtonSubItems(!permission) } }; public static void Initialize(NotepadsMainPage page) @@ -59,9 +59,8 @@ private static async void Application_OnDataChanged(ApplicationData sender, obje { await DispatcherExtensions.CallOnUIThreadAsync(_notepadsMainPage.Dispatcher, () => { - if (lastChangedSettingsKeyStr != OpenRecentKey) _notepadsMainPage.CloseSettingsPane(); - SyncManager[lastChangedSettingsKeyStr].Invoke(); - ThemeSettingsService.InitializeAppAccentColor(true); + if (lastChangedSettingsKeyStr != RecentFilesListKey) _notepadsMainPage.CloseSettingsPane(); + SyncManager[lastChangedSettingsKeyStr].Invoke(true); }); } } diff --git a/src/Notepads/Services/ThemeSettingsService.cs b/src/Notepads/Services/ThemeSettingsService.cs index 993595fcf..548b73458 100644 --- a/src/Notepads/Services/ThemeSettingsService.cs +++ b/src/Notepads/Services/ThemeSettingsService.cs @@ -98,7 +98,7 @@ public static void Initialize(bool shouldInvokeChangedEvent = false) InitializeAppAccentColor(shouldInvokeChangedEvent); - InitializeCustomAccentColor(); + InitializeCustomAccentColor(shouldInvokeChangedEvent); InitializeAppBackgroundPanelTintOpacity(shouldInvokeChangedEvent); } @@ -129,7 +129,7 @@ public static void InitializeAppAccentColor(bool invokeChangedEvent = false) if (invokeChangedEvent) OnAccentColorChanged?.Invoke(null, _appAccentColor); } - public static void InitializeCustomAccentColor() + public static void InitializeCustomAccentColor(bool invokeChangedEvent = false) { if (ApplicationSettingsStore.Read(SettingsKey.CustomAccentColorHexStr) is string customAccentColorHexStr) { diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.MainMenu.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.MainMenu.cs index 740e3a5df..c5ace665d 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.MainMenu.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.MainMenu.cs @@ -171,7 +171,8 @@ public async Task BuildOpenRecentButtonSubItems(bool invokeAfterChanged = true) if (invokeAfterChanged) { - ApplicationSettingsStore.Write(SettingsKey.LastChangedSettingsKeyStr, InterInstanceSyncService.OpenRecentKey); + ApplicationSettingsStore.Write(SettingsKey.LastChangedSettingsKeyStr, InterInstanceSyncService.RecentFilesListKey); + ApplicationSettingsStore.Write(SettingsKey.LastChangedSettingsAppInstanceIdStr, App.Id.ToString()); ApplicationData.Current.SignalDataChanged(); } } diff --git a/src/Notepads/Views/Settings/PersonalizationSettingsPage.xaml.cs b/src/Notepads/Views/Settings/PersonalizationSettingsPage.xaml.cs index 764cb0bf0..2ab069ea1 100644 --- a/src/Notepads/Views/Settings/PersonalizationSettingsPage.xaml.cs +++ b/src/Notepads/Views/Settings/PersonalizationSettingsPage.xaml.cs @@ -136,8 +136,8 @@ private void AccentColorPicker_OnColorChanged(ColorPicker sender, ColorChangedEv { if (AccentColorPicker.IsEnabled) { - ThemeSettingsService.AppAccentColor = args.NewColor; if (!AccentColorToggle.IsOn) ThemeSettingsService.CustomAccentColor = args.NewColor; + ThemeSettingsService.AppAccentColor = args.NewColor; } } From 1cb689016a2fb3e59a3435262c716ebe3f151f43 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 27 Jun 2020 20:33:39 +0530 Subject: [PATCH 030/181] fixed. --- src/Notepads/Settings/ApplicationSettings.cs | 21 +++++++++++-------- .../MainPage/NotepadsMainPage.MainMenu.cs | 7 +------ 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/src/Notepads/Settings/ApplicationSettings.cs b/src/Notepads/Settings/ApplicationSettings.cs index e994e1b66..05d607f45 100644 --- a/src/Notepads/Settings/ApplicationSettings.cs +++ b/src/Notepads/Settings/ApplicationSettings.cs @@ -6,14 +6,15 @@ public static class ApplicationSettingsStore { + private static readonly ApplicationDataContainer _localSettings = ApplicationData.Current.LocalSettings; + public static object Read(string key) { object obj = null; - ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; - if (localSettings.Values.ContainsKey(key)) + if (_localSettings.Values.ContainsKey(key)) { - obj = localSettings.Values[key]; + obj = _localSettings.Values[key]; } return obj; @@ -21,13 +22,16 @@ public static object Read(string key) public static void Write(string key, object obj) { - ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; - localSettings.Values[key] = obj; + _localSettings.Values[key] = obj; + SignalDataChanged(key); + } + public static void SignalDataChanged(string key) + { if (InterInstanceSyncService.SyncManager.ContainsKey(key)) { - localSettings.Values[SettingsKey.LastChangedSettingsKeyStr] = key; - localSettings.Values[SettingsKey.LastChangedSettingsAppInstanceIdStr] = App.Id.ToString(); + _localSettings.Values[SettingsKey.LastChangedSettingsKeyStr] = key; + _localSettings.Values[SettingsKey.LastChangedSettingsAppInstanceIdStr] = App.Id.ToString(); ApplicationData.Current.SignalDataChanged(); } } @@ -36,8 +40,7 @@ public static bool Remove(string key) { try { - ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; - return localSettings.Values.Remove(key); + return _localSettings.Values.Remove(key); } catch (Exception ex) { diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.MainMenu.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.MainMenu.cs index c5ace665d..df7688ef0 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.MainMenu.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.MainMenu.cs @@ -169,12 +169,7 @@ public async Task BuildOpenRecentButtonSubItems(bool invokeAfterChanged = true) MainMenuButtonFlyout.Items.Insert(indexToInsert, openRecentSubItem); } - if (invokeAfterChanged) - { - ApplicationSettingsStore.Write(SettingsKey.LastChangedSettingsKeyStr, InterInstanceSyncService.RecentFilesListKey); - ApplicationSettingsStore.Write(SettingsKey.LastChangedSettingsAppInstanceIdStr, App.Id.ToString()); - ApplicationData.Current.SignalDataChanged(); - } + if (invokeAfterChanged) ApplicationSettingsStore.SignalDataChanged(InterInstanceSyncService.RecentFilesListKey); } } } \ No newline at end of file From 780a2a6d64ae2624a17029c5529e8bee8df0b379 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sun, 28 Jun 2020 02:53:50 +0530 Subject: [PATCH 031/181] fixed. --- src/Notepads/Services/InterInstanceSyncService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Notepads/Services/InterInstanceSyncService.cs b/src/Notepads/Services/InterInstanceSyncService.cs index 05176b813..f0de7c05a 100644 --- a/src/Notepads/Services/InterInstanceSyncService.cs +++ b/src/Notepads/Services/InterInstanceSyncService.cs @@ -13,7 +13,7 @@ public static class InterInstanceSyncService public static readonly string RecentFilesListKey = "BuildOpenRecentButtonSubItems"; - public static IReadOnlyDictionary> SyncManager = new Dictionary> + public static readonly IReadOnlyDictionary> SyncManager = new Dictionary> { {SettingsKey.AppBackgroundTintOpacityDouble, ThemeSettingsService.InitializeAppBackgroundPanelTintOpacity }, {SettingsKey.RequestedThemeStr, ThemeSettingsService.InitializeThemeMode }, From ed22a33eac011be0372041e802aa93f934959982 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 3 Jul 2020 17:28:37 +0530 Subject: [PATCH 032/181] fixed. --- .../Notepads.DesktopExtension.csproj | 9 ++++++--- src/Notepads.DesktopExtension/Program.cs | 2 +- src/Notepads.Package/Package.appxmanifest | 2 +- src/Notepads/Notepads.csproj | 10 +++++----- 4 files changed, 13 insertions(+), 10 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index e1c7ce9b7..b6b02ebce 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -7,7 +7,7 @@ {66937CD2-5D8C-42F6-88B9-C963D68ACD08} WinExe Notepads.DesktopExtension - Notepads.DesktopExtension + Notepads32 v4.7.2 512 true @@ -40,6 +40,7 @@ False C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll + False @@ -51,8 +52,10 @@ - - C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.17763.0\Windows.winmd + + False + C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.18362.0\Windows.winmd + False diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs index edf659f88..a4e6c51e7 100644 --- a/src/Notepads.DesktopExtension/Program.cs +++ b/src/Notepads.DesktopExtension/Program.cs @@ -133,7 +133,7 @@ private static async void CreateElevetedExtension() string result = Assembly.GetExecutingAssembly().Location; int index = result.LastIndexOf("\\"); string rootPath = $"{result.Substring(0, index)}\\..\\"; - string aliasPath = rootPath + @"\Notepads.DesktopExtension\Notepads.DesktopExtension.exe"; + string aliasPath = rootPath + @"\Notepads.DesktopExtension\Notepads32.exe"; ProcessStartInfo info = new ProcessStartInfo(); info.Verb = "runas"; diff --git a/src/Notepads.Package/Package.appxmanifest b/src/Notepads.Package/Package.appxmanifest index 56b1a429c..59b5d1656 100644 --- a/src/Notepads.Package/Package.appxmanifest +++ b/src/Notepads.Package/Package.appxmanifest @@ -74,7 +74,7 @@ - + diff --git a/src/Notepads/Notepads.csproj b/src/Notepads/Notepads.csproj index f310a1e1e..12ba2b1c0 100644 --- a/src/Notepads/Notepads.csproj +++ b/src/Notepads/Notepads.csproj @@ -853,11 +853,6 @@ - - - Windows Desktop Extensions for the UWP - - @@ -874,6 +869,11 @@ + + + Windows Desktop Extensions for the UWP + + 14.0 From 18966728b09f3cec2bda4b8443c393759116fa38 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Wed, 15 Jul 2020 15:04:43 +0530 Subject: [PATCH 033/181] fixed. --- src/Notepads/Settings/ApplicationSettings.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Notepads/Settings/ApplicationSettings.cs b/src/Notepads/Settings/ApplicationSettings.cs index 05d607f45..8c5b785ef 100644 --- a/src/Notepads/Settings/ApplicationSettings.cs +++ b/src/Notepads/Settings/ApplicationSettings.cs @@ -22,6 +22,8 @@ public static object Read(string key) public static void Write(string key, object obj) { + if (_localSettings.Values.ContainsKey(key) && _localSettings.Values[key].Equals(obj)) return; + _localSettings.Values[key] = obj; SignalDataChanged(key); } From 9fd4c6602e7e2cb5941bcb73f0c14d6c274c49dc Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 16 Jul 2020 00:28:44 +0530 Subject: [PATCH 034/181] fixed. --- azure-pipelines.yml | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 64990b151..3b86694f5 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -22,10 +22,18 @@ steps: - task: VSBuild@1 inputs: platform: 'x64' - solution: '$(solution)' + solution: '**/*.wapproj' configuration: '$(buildConfiguration)' - msbuildArgs: '/p:AppxBundlePlatforms="$(buildPlatform)" - /p:AppxPackageDir="$(appxPackageDir)" - /p:AppxBundle=Always - /p:UapAppxPackageBuildMode=StoreUpload - /p:AppxPackageSigningEnabled=false' + msbuildArgs: '/t:build;_GenerateAppxPackage /p:AppxBundlePlatforms="$(buildPlatform)" /p:AppxPackageDir="$(appxPackageDir)" /p:AppxBundle=Always /p:UapAppxPackageBuildMode=StoreUpload /p:AppxPackageSigningEnabled=false' + +- task: CopyFiles@2 + displayName: 'Copy Files to: $(build.artifactstagingdirectory)' + inputs: + SourceFolder: '$(system.defaultworkingdirectory)' + Contents: '**\bin\$(BuildConfiguration)\**' + TargetFolder: '$(build.artifactstagingdirectory)' + +- task: PublishBuildArtifacts@1 + displayName: 'Publish Artifact: drop' + inputs: + PathtoPublish: '$(build.artifactstagingdirectory)' From e5168bde1055eb9ac5a5de67108c397541dd6ea8 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 16 Jul 2020 00:51:37 +0530 Subject: [PATCH 035/181] fixed. --- azure-pipelines.yml | 2 +- .../Views/MainPage/NotepadsMainPage.IO.cs | 73 +++++++++++-------- 2 files changed, 42 insertions(+), 33 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 3b86694f5..adcdacf27 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -21,7 +21,7 @@ steps: - task: VSBuild@1 inputs: - platform: 'x64' + platform: 'x86' solution: '**/*.wapproj' configuration: '$(buildConfiguration)' msbuildArgs: '/t:build;_GenerateAppxPackage /p:AppxBundlePlatforms="$(buildPlatform)" /p:AppxPackageDir="$(appxPackageDir)" /p:AppxBundle=Always /p:UapAppxPackageBuildMode=StoreUpload /p:AppxPackageSigningEnabled=false' diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs index f6af935c1..a8313e306 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs @@ -152,6 +152,45 @@ private async Task SaveInternal(ITextEditor textEditor, StorageFile file, bool r } } + private async Task TrySaveFile(ITextEditor textEditor, StorageFile file, bool rebuildOpenRecentItems) + { + var promptSaveAs = false; + + try + { + await SaveInternal(textEditor, file, rebuildOpenRecentItems); + } + catch (UnauthorizedAccessException) // Happens when the file we are saving is read-only + { + promptSaveAs = true; + } + catch (FileNotFoundException) // Happens when the file not found or storage media is removed + { + promptSaveAs = true; + } + catch (AdminstratorAccessException) // Happens when the file we are saving is read-only, ask user for permission to write + { + var createElevatedExtensionDialog = new CreateElevatedExtensionDialog( + async () => + { + await DesktopExtensionService.CreateElevetedExtension(); + }, + () => + { + promptSaveAs = true; + }); + + var dialogResult = await DialogManager.OpenDialogAsync(createElevatedExtensionDialog, awaitPreviousDialog: false); + + if (dialogResult == null || createElevatedExtensionDialog.IsAborted) + { + promptSaveAs = true; + } + } + + return promptSaveAs; + } + private async Task Save(ITextEditor textEditor, bool saveAs, bool ignoreUnmodifiedDocument = false, bool rebuildOpenRecentItems = true) { if (textEditor == null) return false; @@ -175,38 +214,8 @@ private async Task Save(ITextEditor textEditor, bool saveAs, bool ignoreUn file = textEditor.EditingFile; } - bool promptSaveAs = false; - try - { - await SaveInternal(textEditor, file, rebuildOpenRecentItems); - } - catch (UnauthorizedAccessException) // Happens when the file we are saving is read-only - { - promptSaveAs = true; - } - catch (FileNotFoundException) // Happens when the file not found or storage media is removed - { - promptSaveAs = true; - } - catch (AdminstratorAccessException) // Happens when the file we are saving is read-only, ask user for permission to write - { - var createElevatedExtensionDialog = new CreateElevatedExtensionDialog( - async () => - { - await DesktopExtensionService.CreateElevetedExtension(); - }, - () => - { - promptSaveAs = true; - }); - - var dialogResult = await DialogManager.OpenDialogAsync(createElevatedExtensionDialog, awaitPreviousDialog: false); - - if (dialogResult == null || createElevatedExtensionDialog.IsAborted) - { - promptSaveAs = true; - } - } + var promptSaveAs = await TrySaveFile(textEditor, file, rebuildOpenRecentItems); + if (promptSaveAs) { From f581db5584a3c22aa0be9b3c0c219c5c8f978783 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 16 Jul 2020 01:51:05 +0530 Subject: [PATCH 036/181] fixed. --- azure-pipelines.yml | 9 +++++++++ .../Views/MainPage/NotepadsMainPage.IO.cs | 17 +++++++---------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index adcdacf27..6f9da8ee5 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -13,6 +13,15 @@ variables: appxPackageDir: '$(build.artifactStagingDirectory)\AppxPackages\\' steps: +- task: PowerShell@2 + displayName: 'Update appxmanifest' + inputs: + targetType: 'inline' + script: | + [xml]$manifest = Get-Content $(Build.SourcesDirectory)\Notepads.Package\Package.appxmanifest + $manifest.Save('$(Build.SourcesDirectory)\Notepads.Package\Package.appxmanifest') + failOnStderr: true + - task: NuGetToolInstaller@1 - task: NuGetCommand@2 diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs index a8313e306..0774b90e4 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs @@ -154,7 +154,7 @@ private async Task SaveInternal(ITextEditor textEditor, StorageFile file, bool r private async Task TrySaveFile(ITextEditor textEditor, StorageFile file, bool rebuildOpenRecentItems) { - var promptSaveAs = false; + var isSaveSuccess = true; try { @@ -162,11 +162,11 @@ private async Task TrySaveFile(ITextEditor textEditor, StorageFile file, b } catch (UnauthorizedAccessException) // Happens when the file we are saving is read-only { - promptSaveAs = true; + isSaveSuccess = false; } catch (FileNotFoundException) // Happens when the file not found or storage media is removed { - promptSaveAs = true; + isSaveSuccess = false; } catch (AdminstratorAccessException) // Happens when the file we are saving is read-only, ask user for permission to write { @@ -177,18 +177,18 @@ private async Task TrySaveFile(ITextEditor textEditor, StorageFile file, b }, () => { - promptSaveAs = true; + isSaveSuccess = false; }); var dialogResult = await DialogManager.OpenDialogAsync(createElevatedExtensionDialog, awaitPreviousDialog: false); if (dialogResult == null || createElevatedExtensionDialog.IsAborted) { - promptSaveAs = true; + isSaveSuccess = false; } } - return promptSaveAs; + return isSaveSuccess; } private async Task Save(ITextEditor textEditor, bool saveAs, bool ignoreUnmodifiedDocument = false, bool rebuildOpenRecentItems = true) @@ -214,10 +214,7 @@ private async Task Save(ITextEditor textEditor, bool saveAs, bool ignoreUn file = textEditor.EditingFile; } - var promptSaveAs = await TrySaveFile(textEditor, file, rebuildOpenRecentItems); - - - if (promptSaveAs) + if (!await TrySaveFile(textEditor, file, rebuildOpenRecentItems)) { file = await OpenFileUsingFileSavePicker(textEditor); if (file == null) return false; // User cancelled From e8641ed2b16a24d24085a311132c192d95b673cb Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 16 Jul 2020 02:01:36 +0530 Subject: [PATCH 037/181] fixed. --- azure-pipelines.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 6f9da8ee5..fc22d2f1a 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -19,6 +19,10 @@ steps: targetType: 'inline' script: | [xml]$manifest = Get-Content $(Build.SourcesDirectory)\Notepads.Package\Package.appxmanifest + $manifest.Package.Identity.Name="Notepads" + $manifest.Package.Identity.Version="1.3.9.0" + $manifest.Package.Properties.DisplayName="Notepads App" + $manifest.Package.Applications.Application.VisualElements.DisplayName="Notepads" $manifest.Save('$(Build.SourcesDirectory)\Notepads.Package\Package.appxmanifest') failOnStderr: true From 008b3eec1aca420066d75b936e9e3e385bb048b8 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 16 Jul 2020 02:11:08 +0530 Subject: [PATCH 038/181] fixed. --- azure-pipelines.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index fc22d2f1a..cef40d413 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -18,12 +18,12 @@ steps: inputs: targetType: 'inline' script: | - [xml]$manifest = Get-Content $(Build.SourcesDirectory)\Notepads.Package\Package.appxmanifest + [xml]$manifest = Get-Content $(Build.SourcesDirectory)\src\Notepads.Package\Package.appxmanifest $manifest.Package.Identity.Name="Notepads" $manifest.Package.Identity.Version="1.3.9.0" $manifest.Package.Properties.DisplayName="Notepads App" $manifest.Package.Applications.Application.VisualElements.DisplayName="Notepads" - $manifest.Save('$(Build.SourcesDirectory)\Notepads.Package\Package.appxmanifest') + $manifest.Save('$(Build.SourcesDirectory)\src\Notepads.Package\Package.appxmanifest') failOnStderr: true - task: NuGetToolInstaller@1 From 733721ca6087df2160d2ba6fe3576c30e79c0dbc Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 16 Jul 2020 02:32:23 +0530 Subject: [PATCH 039/181] fixed. --- azure-pipelines.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index cef40d413..cde832f1b 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -32,12 +32,12 @@ steps: inputs: restoreSolution: '$(solution)' -- task: VSBuild@1 +- task: MSBuild@1 inputs: platform: 'x86' solution: '**/*.wapproj' configuration: '$(buildConfiguration)' - msbuildArgs: '/t:build;_GenerateAppxPackage /p:AppxBundlePlatforms="$(buildPlatform)" /p:AppxPackageDir="$(appxPackageDir)" /p:AppxBundle=Always /p:UapAppxPackageBuildMode=StoreUpload /p:AppxPackageSigningEnabled=false' + msbuildArgs: '/t:build;_GenerateAppxPackage /p:Configuration=Release;Platform="$(buildPlatform)";AppxBundle=Always;AppxBundlePlatforms="$(buildPlatform)"' - task: CopyFiles@2 displayName: 'Copy Files to: $(build.artifactstagingdirectory)' From 86eee774669ceb09c33e1993525c59bcadc26aa1 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 16 Jul 2020 02:48:22 +0530 Subject: [PATCH 040/181] fixed. --- .../Notepads.DesktopExtension.csproj | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index b6b02ebce..b6c960c29 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -14,6 +14,16 @@ true True + + true + full + false + bin\Latest\ + DEBUG;TRACE + prompt + 4 + true + AnyCPU true From 7294f62a309cd4b7b1bdba53abd5dce60498827a Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 16 Jul 2020 03:04:57 +0530 Subject: [PATCH 041/181] fixed. --- .../Notepads.DesktopExtension.csproj | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index b6c960c29..9da928ecc 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -43,6 +43,50 @@ prompt 4 + + true + bin\x64\Debug\ + DEBUG;TRACE + full + x64 + 8.0 + prompt + MinimumRecommendedRules.ruleset + true + + + bin\x64\Release\ + TRACE + true + pdbonly + x64 + 8.0 + prompt + MinimumRecommendedRules.ruleset + true + + + true + bin\x86\Debug\ + DEBUG;TRACE + full + x86 + 8.0 + prompt + MinimumRecommendedRules.ruleset + true + + + bin\x86\Release\ + TRACE + true + pdbonly + x86 + 8.0 + prompt + MinimumRecommendedRules.ruleset + true + From 7ca455ed4ea8d6a686e4271e39e73c12f39555ce Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 16 Jul 2020 04:53:09 +0530 Subject: [PATCH 042/181] fixed. --- azure-pipelines.yml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index cde832f1b..2e3270431 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -37,7 +37,12 @@ steps: platform: 'x86' solution: '**/*.wapproj' configuration: '$(buildConfiguration)' - msbuildArgs: '/t:build;_GenerateAppxPackage /p:Configuration=Release;Platform="$(buildPlatform)";AppxBundle=Always;AppxBundlePlatforms="$(buildPlatform)"' + msbuildArgs: '/t:build;_GenerateAppxPackage + /p:AppxBundlePlatforms="$(buildPlatform)" + /p:AppxPackageDir="$(appxPackageDir)" + /p:AppxBundle=Always + /p:UapAppxPackageBuildMode=StoreUpload + /p:AppxPackageSigningEnabled=false' - task: CopyFiles@2 displayName: 'Copy Files to: $(build.artifactstagingdirectory)' From 670cb2cf589fd3195f185e51d5287c4b2e6ce9b0 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 16 Jul 2020 04:55:14 +0530 Subject: [PATCH 043/181] fixed. --- azure-pipelines.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 2e3270431..9781906e6 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -39,9 +39,9 @@ steps: configuration: '$(buildConfiguration)' msbuildArgs: '/t:build;_GenerateAppxPackage /p:AppxBundlePlatforms="$(buildPlatform)" - /p:AppxPackageDir="$(appxPackageDir)" - /p:AppxBundle=Always - /p:UapAppxPackageBuildMode=StoreUpload + /p:AppxPackageDir="$(appxPackageDir)" + /p:AppxBundle=Always + /p:UapAppxPackageBuildMode=StoreUpload /p:AppxPackageSigningEnabled=false' - task: CopyFiles@2 From abb566c91e2ca5bbe5b2ee51ee080ccd0af72f9f Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 25 Jul 2020 19:41:18 +0530 Subject: [PATCH 044/181] fixed. --- src/Notepads/Services/DesktopExtensionService.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index c9abd8411..42bdc6905 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -91,7 +91,8 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) ApplicationSettingsStore.Remove(SettingsKey.AdminAuthenticationTokenStr); } } - else + + if (!_isAdminExtensionAvailable) { throw new AdminstratorAccessException(); } From 1db7aa31966e46795c11e279c7526c578835a444 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Wed, 5 Aug 2020 12:39:29 +0530 Subject: [PATCH 045/181] Implemented sharing data via memory-mapped-file for faster ipc. --- src/Notepads.DesktopExtension/AdminService.cs | 18 +++++++- .../IAdminService.cs | 2 +- src/Notepads.Package/Package.appxmanifest | 19 +++++++++ .../AdminService/AdminService1.xsd | 3 +- .../AdminService/Reference.cs | 8 ++-- .../Services/DesktopExtensionService.cs | 41 ++++++++++++++----- 6 files changed, 72 insertions(+), 19 deletions(-) diff --git a/src/Notepads.DesktopExtension/AdminService.cs b/src/Notepads.DesktopExtension/AdminService.cs index 137604fc1..c0c622836 100644 --- a/src/Notepads.DesktopExtension/AdminService.cs +++ b/src/Notepads.DesktopExtension/AdminService.cs @@ -1,6 +1,8 @@ namespace Notepads.DesktopExtension { using System; + using System.IO; + using System.IO.MemoryMappedFiles; using System.Threading.Tasks; using Windows.Storage; @@ -9,7 +11,7 @@ public class AdminService : IAdminService { internal static string AdminAuthenticationTokenStr = "AdminAuthenticationTokenStr"; - public async Task SaveFile(string filePath, byte[] data) + public async Task SaveFile(string memoryMapName, string filePath, int dataArrayLength) { try { @@ -17,7 +19,19 @@ public async Task SaveFile(string filePath, byte[] data) if (!localSettings.Values.ContainsKey(AdminAuthenticationTokenStr) || !(localSettings.Values[AdminAuthenticationTokenStr] is string token)) return false; localSettings.Values.Remove(AdminAuthenticationTokenStr); - await PathIO.WriteBytesAsync(filePath, data); + + // Open the memory-mapped file. + using (var mmf = MemoryMappedFile.OpenExisting(memoryMapName)) + { + using (var stream = mmf.CreateViewStream()) + { + var reader = new BinaryReader(stream); + var data = reader.ReadBytes(dataArrayLength); + + await PathIO.WriteBytesAsync(filePath, data); + } + } + return true; } catch (Exception) diff --git a/src/Notepads.DesktopExtension/IAdminService.cs b/src/Notepads.DesktopExtension/IAdminService.cs index a1e69b306..907c54436 100644 --- a/src/Notepads.DesktopExtension/IAdminService.cs +++ b/src/Notepads.DesktopExtension/IAdminService.cs @@ -9,6 +9,6 @@ public interface IAdminService { [OperationContract] - Task SaveFile(string filePath, byte[] data); + Task SaveFile(string memoryMapName, string filePath, int dataArrayLength); } } diff --git a/src/Notepads.Package/Package.appxmanifest b/src/Notepads.Package/Package.appxmanifest index 59b5d1656..ae1b1021a 100644 --- a/src/Notepads.Package/Package.appxmanifest +++ b/src/Notepads.Package/Package.appxmanifest @@ -1188,10 +1188,29 @@ + + diff --git a/src/Notepads/Connected Services/AdminService/AdminService1.xsd b/src/Notepads/Connected Services/AdminService/AdminService1.xsd index 58a2bc7a2..036c6a8bf 100644 --- a/src/Notepads/Connected Services/AdminService/AdminService1.xsd +++ b/src/Notepads/Connected Services/AdminService/AdminService1.xsd @@ -3,8 +3,9 @@ + - + diff --git a/src/Notepads/Connected Services/AdminService/Reference.cs b/src/Notepads/Connected Services/AdminService/Reference.cs index 9b51d2c4b..94254cabd 100644 --- a/src/Notepads/Connected Services/AdminService/Reference.cs +++ b/src/Notepads/Connected Services/AdminService/Reference.cs @@ -9,7 +9,7 @@ //------------------------------------------------------------------------------ // -// This code was auto-generated by Microsoft.VisualStudio.ServiceReference.Platforms, version 16.0.30114.105 +// This code was auto-generated by Microsoft.VisualStudio.ServiceReference.Platforms, version 16.0.30225.117 // namespace Notepads.AdminService { @@ -19,7 +19,7 @@ namespace Notepads.AdminService { public interface IAdminService { [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IAdminService/SaveFile", ReplyAction="http://tempuri.org/IAdminService/SaveFileResponse")] - System.Threading.Tasks.Task SaveFileAsync(string filePath, byte[] data); + System.Threading.Tasks.Task SaveFileAsync(string memoryMapName, string filePath, int dataArrayLength); } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] @@ -65,8 +65,8 @@ public AdminServiceClient(System.ServiceModel.Channels.Binding binding, System.S base(binding, remoteAddress) { } - public System.Threading.Tasks.Task SaveFileAsync(string filePath, byte[] data) { - return base.Channel.SaveFileAsync(filePath, data); + public System.Threading.Tasks.Task SaveFileAsync(string memoryMapName, string filePath, int dataArrayLength) { + return base.Channel.SaveFileAsync(memoryMapName, filePath, dataArrayLength); } public virtual System.Threading.Tasks.Task OpenAsync() { diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index 42bdc6905..122b6871c 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -4,12 +4,15 @@ using Notepads.Extensions; using Notepads.Settings; using System; + using System.IO; + using System.IO.MemoryMappedFiles; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.AppService; using Windows.ApplicationModel.Core; using Windows.ApplicationModel.Resources; using Windows.Foundation.Collections; + using Windows.Security.Authentication.Web; using Windows.UI.ViewManagement; using Windows.UI.Xaml; @@ -77,18 +80,34 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) bool failedFromAdminExtension = false; if (_isAdminExtensionAvailable) { - try - { - ApplicationSettingsStore.Write(SettingsKey.AdminAuthenticationTokenStr, Guid.NewGuid().ToString()); - failedFromAdminExtension = !await AdminServiceClient.SaveFileAsync(filePath, data); - } - catch - { - _isAdminExtensionAvailable = false; - } - finally + var mapName = Guid.NewGuid().ToString(); + + // Create the memory-mapped file. + using (var mmf = MemoryMappedFile.CreateOrOpen(mapName, data.Length, MemoryMappedFileAccess.ReadWrite)) { - ApplicationSettingsStore.Remove(SettingsKey.AdminAuthenticationTokenStr); + using (var stream = mmf.CreateViewStream()) + { + var writer = new BinaryWriter(stream); + writer.Write(data); + writer.Flush(); + } + + try + { + ApplicationSettingsStore.Write(SettingsKey.AdminAuthenticationTokenStr, Guid.NewGuid().ToString()); + failedFromAdminExtension = !await AdminServiceClient.SaveFileAsync( + $"AppContainerNamedObjects\\{ WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host.ToUpper() }\\{ mapName }", + filePath, + data.Length); + } + catch + { + _isAdminExtensionAvailable = false; + } + finally + { + ApplicationSettingsStore.Remove(SettingsKey.AdminAuthenticationTokenStr); + } } } From 879885aca6e86ede2c362e443369c6c6c705f707 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Wed, 5 Aug 2020 14:31:44 +0530 Subject: [PATCH 046/181] update references. --- .../Notepads.DesktopExtension.csproj | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index 9da928ecc..bb112135a 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -91,11 +91,6 @@ - - False - C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll - False - @@ -106,11 +101,6 @@ - - False - C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.18362.0\Windows.winmd - False - @@ -136,6 +126,17 @@ True + + + 10.0.19041.1 + + + 4.7.0 + + + 4.7.0 + + From 2ad49c99a7c9b0c807699f7d96348d2d2163be20 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 6 Aug 2020 00:56:15 +0530 Subject: [PATCH 047/181] fixed saving error. --- src/Notepads/Services/DesktopExtensionService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index 122b6871c..b5a3fd85b 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -83,7 +83,7 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) var mapName = Guid.NewGuid().ToString(); // Create the memory-mapped file. - using (var mmf = MemoryMappedFile.CreateOrOpen(mapName, data.Length, MemoryMappedFileAccess.ReadWrite)) + using (var mmf = MemoryMappedFile.CreateOrOpen(mapName, data.Length > 0 ? data.Length : 1, MemoryMappedFileAccess.ReadWrite)) { using (var stream = mmf.CreateViewStream()) { From c6d16d8c094e52fa14b08f077b59863ddb9d9027 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 6 Aug 2020 11:30:58 +0530 Subject: [PATCH 048/181] code refinement. --- src/Notepads.DesktopExtension/App.config | 6 +- .../Notepads.DesktopExtension.csproj | 7 +- src/Notepads.DesktopExtension/Program.cs | 65 +++++-------------- .../{ => Services}/AdminService.cs | 11 ++-- .../{ => Services}/IAdminService.cs | 2 +- .../AdminService/AdminService.disco | 2 +- .../AdminService/AdminService.wsdl | 6 +- .../AdminService/Reference.cs | 2 +- .../AdminService/Reference.svcmap | 12 ++-- src/Notepads/Notepads.csproj | 6 +- 10 files changed, 46 insertions(+), 73 deletions(-) rename src/Notepads.DesktopExtension/{ => Services}/AdminService.cs (74%) rename src/Notepads.DesktopExtension/{ => Services}/IAdminService.cs (90%) diff --git a/src/Notepads.DesktopExtension/App.config b/src/Notepads.DesktopExtension/App.config index 56974c300..9d9e0aee7 100644 --- a/src/Notepads.DesktopExtension/App.config +++ b/src/Notepads.DesktopExtension/App.config @@ -15,12 +15,12 @@ - - + + - + diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index bb112135a..b7eced845 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -103,8 +103,8 @@ - - + + @@ -125,6 +125,9 @@ Settings.settings True + + Settings\SettingsKey.cs + diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs index a4e6c51e7..249132122 100644 --- a/src/Notepads.DesktopExtension/Program.cs +++ b/src/Notepads.DesktopExtension/Program.cs @@ -1,5 +1,6 @@ namespace Notepads.DesktopExtension { + using Notepads.DesktopExtension.Services; using System; using System.Diagnostics; using System.Reflection; @@ -10,7 +11,6 @@ using Windows.ApplicationModel; using Windows.ApplicationModel.AppService; using Windows.Foundation.Collections; - using Windows.Storage; public enum CommandArgs { @@ -21,15 +21,15 @@ public enum CommandArgs static class Program { - private static string DesktopExtensionMutexIdStr = "DesktopExtensionMutexIdStr"; - private static string AdminExtensionMutexIdStr = "AdminExtensionMutexIdStr"; - private static Mutex mutex; + private const string DesktopExtensionMutexName = "DesktopExtensionMutexName"; + private const string AdminExtensionMutexName = "AdminExtensionMutexName"; - private static AppServiceConnection connection = null; - private static ServiceHost selfHost = null; private static readonly string _commandLabel = "Command"; private static readonly string _adminCreatedLabel = "AdminCreated"; + private static AppServiceConnection connection = null; + private static ServiceHost selfHost = null; + /// /// The main entry point for the application. /// @@ -37,18 +37,17 @@ static void Main(string[] args) { if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) { - CheckInstance(AdminExtensionMutexIdStr); + if (!IsFirstInstance(AdminExtensionMutexName)) return; InitializeExtensionService(); } else { - CheckInstance(DesktopExtensionMutexIdStr); + if (!IsFirstInstance(DesktopExtensionMutexName)) return; InitializeAppServiceConnection(); if (args.Length > 2 && args[2] == "/admin") CreateElevetedExtension(); } Application.Run(); - Application.ApplicationExit += Application_OnApplicationExit; } private static async void InitializeAppServiceConnection() @@ -80,21 +79,20 @@ private static void InitializeExtensionService() selfHost.Open(); } - private static void CheckInstance(string key) + private static bool IsFirstInstance(string mutexName) { - mutex = new Mutex(true, ReadOrInitializeMutexId(key), out var isFirstInstance); - if (!isFirstInstance) + var instanceHandlerMutex = new Mutex(true, mutexName, out var isFirstInstance); + + if (isFirstInstance) { - mutex.ReleaseMutex(); - RemoveMutexId(AdminExtensionMutexIdStr); - RemoveMutexId(DesktopExtensionMutexIdStr); - Application.Exit(); + instanceHandlerMutex.ReleaseMutex(); + } + else + { + instanceHandlerMutex.Close(); } - } - private static void Application_OnApplicationExit(object sender, EventArgs e) - { - mutex.Close(); + return isFirstInstance; } private static void Connection_ServiceClosed(AppServiceConnection sender, AppServiceClosedEventArgs args) @@ -152,32 +150,5 @@ private static async void CreateElevetedExtension() await connection.SendMessageAsync(message); } } - - private static string ReadOrInitializeMutexId(string key) - { - ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; - if (!localSettings.Values.ContainsKey(key) || !(localSettings.Values[key] is string mutexId) || string.IsNullOrEmpty(mutexId)) - { - mutexId = Guid.NewGuid().ToString(); - WriteMutexId(key, mutexId); - } - return mutexId; - } - - private static void WriteMutexId(string key, object obj) - { - ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; - localSettings.Values[key] = obj; - } - - private static void RemoveMutexId(string key) - { - try - { - ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; - localSettings.Values.Remove(key); - } - catch (Exception) { } - } } } diff --git a/src/Notepads.DesktopExtension/AdminService.cs b/src/Notepads.DesktopExtension/Services/AdminService.cs similarity index 74% rename from src/Notepads.DesktopExtension/AdminService.cs rename to src/Notepads.DesktopExtension/Services/AdminService.cs index c0c622836..826a82c1e 100644 --- a/src/Notepads.DesktopExtension/AdminService.cs +++ b/src/Notepads.DesktopExtension/Services/AdminService.cs @@ -1,5 +1,6 @@ -namespace Notepads.DesktopExtension +namespace Notepads.DesktopExtension.Services { + using Notepads.Settings; using System; using System.IO; using System.IO.MemoryMappedFiles; @@ -9,16 +10,14 @@ // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "AdminService" in both code and config file together. public class AdminService : IAdminService { - internal static string AdminAuthenticationTokenStr = "AdminAuthenticationTokenStr"; - public async Task SaveFile(string memoryMapName, string filePath, int dataArrayLength) { try { var localSettings = ApplicationData.Current.LocalSettings; - if (!localSettings.Values.ContainsKey(AdminAuthenticationTokenStr) || - !(localSettings.Values[AdminAuthenticationTokenStr] is string token)) return false; - localSettings.Values.Remove(AdminAuthenticationTokenStr); + if (!localSettings.Values.ContainsKey(SettingsKey.AdminAuthenticationTokenStr) || + !(localSettings.Values[SettingsKey.AdminAuthenticationTokenStr] is string token)) return false; + localSettings.Values.Remove(SettingsKey.AdminAuthenticationTokenStr); // Open the memory-mapped file. using (var mmf = MemoryMappedFile.OpenExisting(memoryMapName)) diff --git a/src/Notepads.DesktopExtension/IAdminService.cs b/src/Notepads.DesktopExtension/Services/IAdminService.cs similarity index 90% rename from src/Notepads.DesktopExtension/IAdminService.cs rename to src/Notepads.DesktopExtension/Services/IAdminService.cs index 907c54436..02da14e4f 100644 --- a/src/Notepads.DesktopExtension/IAdminService.cs +++ b/src/Notepads.DesktopExtension/Services/IAdminService.cs @@ -1,4 +1,4 @@ -namespace Notepads.DesktopExtension +namespace Notepads.DesktopExtension.Services { using System.Runtime.Serialization; using System.ServiceModel; diff --git a/src/Notepads/Connected Services/AdminService/AdminService.disco b/src/Notepads/Connected Services/AdminService/AdminService.disco index fcdc4ed54..2b6f87d6e 100644 --- a/src/Notepads/Connected Services/AdminService/AdminService.disco +++ b/src/Notepads/Connected Services/AdminService/AdminService.disco @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/src/Notepads/Connected Services/AdminService/AdminService.wsdl b/src/Notepads/Connected Services/AdminService/AdminService.wsdl index a08f960ec..246cd73cb 100644 --- a/src/Notepads/Connected Services/AdminService/AdminService.wsdl +++ b/src/Notepads/Connected Services/AdminService/AdminService.wsdl @@ -2,8 +2,8 @@ - - + + @@ -32,7 +32,7 @@ - + \ No newline at end of file diff --git a/src/Notepads/Connected Services/AdminService/Reference.cs b/src/Notepads/Connected Services/AdminService/Reference.cs index 94254cabd..0d0fc6c40 100644 --- a/src/Notepads/Connected Services/AdminService/Reference.cs +++ b/src/Notepads/Connected Services/AdminService/Reference.cs @@ -91,7 +91,7 @@ private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(Endpoi private static System.ServiceModel.EndpointAddress GetEndpointAddress(EndpointConfiguration endpointConfiguration) { if ((endpointConfiguration == EndpointConfiguration.BasicHttpBinding_IAdminService)) { - return new System.ServiceModel.EndpointAddress("http://localhost:8000/Notepads.DesktopExtension/AdminService"); + return new System.ServiceModel.EndpointAddress("http://localhost:8000/Notepads.DesktopExtension.Services/AdminService"); } throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration)); } diff --git a/src/Notepads/Connected Services/AdminService/Reference.svcmap b/src/Notepads/Connected Services/AdminService/Reference.svcmap index de3cc7c29..1c683af58 100644 --- a/src/Notepads/Connected Services/AdminService/Reference.svcmap +++ b/src/Notepads/Connected Services/AdminService/Reference.svcmap @@ -1,5 +1,5 @@ - + false true @@ -21,13 +21,13 @@ - + - - - - + + + + diff --git a/src/Notepads/Notepads.csproj b/src/Notepads/Notepads.csproj index 12ba2b1c0..2f5f39d43 100644 --- a/src/Notepads/Notepads.csproj +++ b/src/Notepads/Notepads.csproj @@ -866,14 +866,14 @@ - - - Windows Desktop Extensions for the UWP + + + 14.0 From 1c3519f7f52e64809a95f7cb2d65d7e27e67aa2d Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 6 Aug 2020 19:22:17 +0530 Subject: [PATCH 049/181] Replaced wcf with pipes. --- .../Notepads.DesktopExtension.csproj | 2 - src/Notepads.DesktopExtension/Program.cs | 67 ++++++++++- .../Services/AdminService.cs | 42 ------- .../Services/IAdminService.cs | 14 --- .../AdminService/AdminService.disco | 4 - .../AdminService/AdminService.wsdl | 38 ------ .../AdminService/AdminService.xsd | 42 ------- .../AdminService/AdminService1.xsd | 19 --- .../AdminService/Reference.cs | 112 ------------------ .../AdminService/Reference.svcmap | 36 ------ .../AdminService/configuration.svcinfo | 6 - .../AdminService/configuration91.svcinfo | 5 - src/Notepads/Notepads.csproj | 22 ---- src/Notepads/Program.cs | 3 + .../Services/DesktopExtensionService.cs | 57 ++++----- src/Notepads/Settings/SettingsKey.cs | 2 +- 16 files changed, 92 insertions(+), 379 deletions(-) delete mode 100644 src/Notepads.DesktopExtension/Services/AdminService.cs delete mode 100644 src/Notepads.DesktopExtension/Services/IAdminService.cs delete mode 100644 src/Notepads/Connected Services/AdminService/AdminService.disco delete mode 100644 src/Notepads/Connected Services/AdminService/AdminService.wsdl delete mode 100644 src/Notepads/Connected Services/AdminService/AdminService.xsd delete mode 100644 src/Notepads/Connected Services/AdminService/AdminService1.xsd delete mode 100644 src/Notepads/Connected Services/AdminService/Reference.cs delete mode 100644 src/Notepads/Connected Services/AdminService/Reference.svcmap delete mode 100644 src/Notepads/Connected Services/AdminService/configuration.svcinfo delete mode 100644 src/Notepads/Connected Services/AdminService/configuration91.svcinfo diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index b7eced845..99113da96 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -103,8 +103,6 @@ - - diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs index 249132122..b85ff92e7 100644 --- a/src/Notepads.DesktopExtension/Program.cs +++ b/src/Notepads.DesktopExtension/Program.cs @@ -1,16 +1,19 @@ namespace Notepads.DesktopExtension { - using Notepads.DesktopExtension.Services; + using Notepads.Settings; using System; using System.Diagnostics; + using System.IO; + using System.IO.MemoryMappedFiles; + using System.IO.Pipes; using System.Reflection; using System.Security.Principal; - using System.ServiceModel; using System.Threading; using System.Windows.Forms; using Windows.ApplicationModel; using Windows.ApplicationModel.AppService; using Windows.Foundation.Collections; + using Windows.Storage; public enum CommandArgs { @@ -28,7 +31,6 @@ static class Program private static readonly string _adminCreatedLabel = "AdminCreated"; private static AppServiceConnection connection = null; - private static ServiceHost selfHost = null; /// /// The main entry point for the application. @@ -75,8 +77,7 @@ private static async void InitializeAppServiceConnection() private static void InitializeExtensionService() { - selfHost = new ServiceHost(typeof(AdminService)); - selfHost.Open(); + SaveFileFromPipeData(); } private static bool IsFirstInstance(string mutexName) @@ -150,5 +151,61 @@ private static async void CreateElevetedExtension() await connection.SendMessageAsync(message); } } + + private static async void SaveFileFromPipeData() + { + using (var clientStream = new NamedPipeClientStream(".", + $"Sessions\\1\\AppContainerNamedObjects\\{ReadSettingsKey(SettingsKey.PackageSidStr)}\\{Package.Current.Id.FamilyName}\\AdminWritePipe", + PipeDirection.InOut, PipeOptions.Asynchronous)) + { + await clientStream.ConnectAsync(); + new Thread(new ThreadStart(SaveFileFromPipeData)).Start(); + + var pipeReader = new StreamReader(clientStream); + var pipeWriter = new StreamWriter(clientStream); + + var writeData = pipeReader.ReadLine().Split(new string[] { "?:" }, StringSplitOptions.None); + + var memoryMapName = writeData[0]; + var filePath = writeData[1]; + int.TryParse(writeData[2], out int dataArrayLength); + + var result = "Failed"; + try + { + // Open the memory-mapped file. + using (var mmf = MemoryMappedFile.OpenExisting(memoryMapName)) + { + using (var stream = mmf.CreateViewStream()) + { + var reader = new BinaryReader(stream); + var data = reader.ReadBytes(dataArrayLength); + + await PathIO.WriteBytesAsync(filePath, data); + } + } + + result = "Success"; + } + finally + { + pipeWriter.WriteLine(result); + pipeWriter.Flush(); + } + } + } + + public static object ReadSettingsKey(string key) + { + object obj = null; + + ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; + if (localSettings.Values.ContainsKey(key)) + { + obj = localSettings.Values[key]; + } + + return obj; + } } } diff --git a/src/Notepads.DesktopExtension/Services/AdminService.cs b/src/Notepads.DesktopExtension/Services/AdminService.cs deleted file mode 100644 index 826a82c1e..000000000 --- a/src/Notepads.DesktopExtension/Services/AdminService.cs +++ /dev/null @@ -1,42 +0,0 @@ -namespace Notepads.DesktopExtension.Services -{ - using Notepads.Settings; - using System; - using System.IO; - using System.IO.MemoryMappedFiles; - using System.Threading.Tasks; - using Windows.Storage; - - // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "AdminService" in both code and config file together. - public class AdminService : IAdminService - { - public async Task SaveFile(string memoryMapName, string filePath, int dataArrayLength) - { - try - { - var localSettings = ApplicationData.Current.LocalSettings; - if (!localSettings.Values.ContainsKey(SettingsKey.AdminAuthenticationTokenStr) || - !(localSettings.Values[SettingsKey.AdminAuthenticationTokenStr] is string token)) return false; - localSettings.Values.Remove(SettingsKey.AdminAuthenticationTokenStr); - - // Open the memory-mapped file. - using (var mmf = MemoryMappedFile.OpenExisting(memoryMapName)) - { - using (var stream = mmf.CreateViewStream()) - { - var reader = new BinaryReader(stream); - var data = reader.ReadBytes(dataArrayLength); - - await PathIO.WriteBytesAsync(filePath, data); - } - } - - return true; - } - catch (Exception) - { - return false; - } - } - } -} diff --git a/src/Notepads.DesktopExtension/Services/IAdminService.cs b/src/Notepads.DesktopExtension/Services/IAdminService.cs deleted file mode 100644 index 02da14e4f..000000000 --- a/src/Notepads.DesktopExtension/Services/IAdminService.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace Notepads.DesktopExtension.Services -{ - using System.Runtime.Serialization; - using System.ServiceModel; - using System.Threading.Tasks; - - // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IAdminService" in both code and config file together. - [ServiceContract] - public interface IAdminService - { - [OperationContract] - Task SaveFile(string memoryMapName, string filePath, int dataArrayLength); - } -} diff --git a/src/Notepads/Connected Services/AdminService/AdminService.disco b/src/Notepads/Connected Services/AdminService/AdminService.disco deleted file mode 100644 index 2b6f87d6e..000000000 --- a/src/Notepads/Connected Services/AdminService/AdminService.disco +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/src/Notepads/Connected Services/AdminService/AdminService.wsdl b/src/Notepads/Connected Services/AdminService/AdminService.wsdl deleted file mode 100644 index 246cd73cb..000000000 --- a/src/Notepads/Connected Services/AdminService/AdminService.wsdl +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Notepads/Connected Services/AdminService/AdminService.xsd b/src/Notepads/Connected Services/AdminService/AdminService.xsd deleted file mode 100644 index d58e7f39c..000000000 --- a/src/Notepads/Connected Services/AdminService/AdminService.xsd +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Notepads/Connected Services/AdminService/AdminService1.xsd b/src/Notepads/Connected Services/AdminService/AdminService1.xsd deleted file mode 100644 index 036c6a8bf..000000000 --- a/src/Notepads/Connected Services/AdminService/AdminService1.xsd +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Notepads/Connected Services/AdminService/Reference.cs b/src/Notepads/Connected Services/AdminService/Reference.cs deleted file mode 100644 index 0d0fc6c40..000000000 --- a/src/Notepads/Connected Services/AdminService/Reference.cs +++ /dev/null @@ -1,112 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -// -// This code was auto-generated by Microsoft.VisualStudio.ServiceReference.Platforms, version 16.0.30225.117 -// -namespace Notepads.AdminService { - - - [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] - [System.ServiceModel.ServiceContractAttribute(ConfigurationName="AdminService.IAdminService")] - public interface IAdminService { - - [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IAdminService/SaveFile", ReplyAction="http://tempuri.org/IAdminService/SaveFileResponse")] - System.Threading.Tasks.Task SaveFileAsync(string memoryMapName, string filePath, int dataArrayLength); - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] - public interface IAdminServiceChannel : Notepads.AdminService.IAdminService, System.ServiceModel.IClientChannel { - } - - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] - public partial class AdminServiceClient : System.ServiceModel.ClientBase, Notepads.AdminService.IAdminService { - - /// - /// Implement this partial method to configure the service endpoint. - /// - /// The endpoint to configure - /// The client credentials - static partial void ConfigureEndpoint(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint, System.ServiceModel.Description.ClientCredentials clientCredentials); - - public AdminServiceClient() : - base(AdminServiceClient.GetDefaultBinding(), AdminServiceClient.GetDefaultEndpointAddress()) { - this.Endpoint.Name = EndpointConfiguration.BasicHttpBinding_IAdminService.ToString(); - ConfigureEndpoint(this.Endpoint, this.ClientCredentials); - } - - public AdminServiceClient(EndpointConfiguration endpointConfiguration) : - base(AdminServiceClient.GetBindingForEndpoint(endpointConfiguration), AdminServiceClient.GetEndpointAddress(endpointConfiguration)) { - this.Endpoint.Name = endpointConfiguration.ToString(); - ConfigureEndpoint(this.Endpoint, this.ClientCredentials); - } - - public AdminServiceClient(EndpointConfiguration endpointConfiguration, string remoteAddress) : - base(AdminServiceClient.GetBindingForEndpoint(endpointConfiguration), new System.ServiceModel.EndpointAddress(remoteAddress)) { - this.Endpoint.Name = endpointConfiguration.ToString(); - ConfigureEndpoint(this.Endpoint, this.ClientCredentials); - } - - public AdminServiceClient(EndpointConfiguration endpointConfiguration, System.ServiceModel.EndpointAddress remoteAddress) : - base(AdminServiceClient.GetBindingForEndpoint(endpointConfiguration), remoteAddress) { - this.Endpoint.Name = endpointConfiguration.ToString(); - ConfigureEndpoint(this.Endpoint, this.ClientCredentials); - } - - public AdminServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : - base(binding, remoteAddress) { - } - - public System.Threading.Tasks.Task SaveFileAsync(string memoryMapName, string filePath, int dataArrayLength) { - return base.Channel.SaveFileAsync(memoryMapName, filePath, dataArrayLength); - } - - public virtual System.Threading.Tasks.Task OpenAsync() { - return System.Threading.Tasks.Task.Factory.FromAsync(((System.ServiceModel.ICommunicationObject)(this)).BeginOpen(null, null), new System.Action(((System.ServiceModel.ICommunicationObject)(this)).EndOpen)); - } - - public virtual System.Threading.Tasks.Task CloseAsync() { - return System.Threading.Tasks.Task.Factory.FromAsync(((System.ServiceModel.ICommunicationObject)(this)).BeginClose(null, null), new System.Action(((System.ServiceModel.ICommunicationObject)(this)).EndClose)); - } - - private static System.ServiceModel.Channels.Binding GetBindingForEndpoint(EndpointConfiguration endpointConfiguration) { - if ((endpointConfiguration == EndpointConfiguration.BasicHttpBinding_IAdminService)) { - System.ServiceModel.BasicHttpBinding result = new System.ServiceModel.BasicHttpBinding(); - result.MaxBufferSize = int.MaxValue; - result.ReaderQuotas = System.Xml.XmlDictionaryReaderQuotas.Max; - result.MaxReceivedMessageSize = int.MaxValue; - result.AllowCookies = true; - return result; - } - throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration)); - } - - private static System.ServiceModel.EndpointAddress GetEndpointAddress(EndpointConfiguration endpointConfiguration) { - if ((endpointConfiguration == EndpointConfiguration.BasicHttpBinding_IAdminService)) { - return new System.ServiceModel.EndpointAddress("http://localhost:8000/Notepads.DesktopExtension.Services/AdminService"); - } - throw new System.InvalidOperationException(string.Format("Could not find endpoint with name \'{0}\'.", endpointConfiguration)); - } - - private static System.ServiceModel.Channels.Binding GetDefaultBinding() { - return AdminServiceClient.GetBindingForEndpoint(EndpointConfiguration.BasicHttpBinding_IAdminService); - } - - private static System.ServiceModel.EndpointAddress GetDefaultEndpointAddress() { - return AdminServiceClient.GetEndpointAddress(EndpointConfiguration.BasicHttpBinding_IAdminService); - } - - public enum EndpointConfiguration { - - BasicHttpBinding_IAdminService, - } - } -} diff --git a/src/Notepads/Connected Services/AdminService/Reference.svcmap b/src/Notepads/Connected Services/AdminService/Reference.svcmap deleted file mode 100644 index 1c683af58..000000000 --- a/src/Notepads/Connected Services/AdminService/Reference.svcmap +++ /dev/null @@ -1,36 +0,0 @@ - - - - false - true - true - - false - false - false - - - - - false - Auto - true - true - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Notepads/Connected Services/AdminService/configuration.svcinfo b/src/Notepads/Connected Services/AdminService/configuration.svcinfo deleted file mode 100644 index d3da738a3..000000000 --- a/src/Notepads/Connected Services/AdminService/configuration.svcinfo +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/src/Notepads/Connected Services/AdminService/configuration91.svcinfo b/src/Notepads/Connected Services/AdminService/configuration91.svcinfo deleted file mode 100644 index 08bf21e68..000000000 --- a/src/Notepads/Connected Services/AdminService/configuration91.svcinfo +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/src/Notepads/Notepads.csproj b/src/Notepads/Notepads.csproj index 2f5f39d43..bc2ef817d 100644 --- a/src/Notepads/Notepads.csproj +++ b/src/Notepads/Notepads.csproj @@ -109,11 +109,6 @@ - - True - True - Reference.svcmap - @@ -430,13 +425,6 @@ - - - - - WCF Proxy Generator - Reference.cs - @@ -857,13 +845,6 @@ - - - Designer - - - Designer - @@ -871,9 +852,6 @@ Windows Desktop Extensions for the UWP - - - 14.0 diff --git a/src/Notepads/Program.cs b/src/Notepads/Program.cs index ce9e59d27..51dbefa65 100644 --- a/src/Notepads/Program.cs +++ b/src/Notepads/Program.cs @@ -9,6 +9,7 @@ using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation.Metadata; + using Windows.Security.Authentication.Web; public static class Program { @@ -153,6 +154,8 @@ private static async void OpenExtension() if (ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0) && !new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) { + ApplicationSettingsStore.Write(SettingsKey.PackageSidStr, WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host.ToUpper()); + await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); } } diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index b5a3fd85b..ce826c128 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -1,11 +1,10 @@ namespace Notepads.Services { - using Notepads.AdminService; using Notepads.Extensions; - using Notepads.Settings; using System; using System.IO; using System.IO.MemoryMappedFiles; + using System.IO.Pipes; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.AppService; @@ -24,8 +23,6 @@ public AdminstratorAccessException():base("Failed to save due to no Adminstratio public static class DesktopExtensionService { public static AppServiceConnection InteropServiceConnection = null; - public static AdminServiceClient AdminServiceClient = new AdminServiceClient(); - private static bool _isAdminExtensionAvailable = false; private static readonly ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView(); private static readonly string _commandLabel = "Command"; @@ -59,7 +56,6 @@ await CoreApplication.MainView.CoreWindow.Dispatcher.CallOnUIThreadAsync(() => if (message.ContainsKey(_adminCreatedLabel) && (bool)message[_adminCreatedLabel]) { NotificationCenter.Instance.PostNotification(_resourceLoader.GetString("TextEditor_NotificationMsg_AdminExtensionCreated"), 1500); - _isAdminExtensionAvailable = true; } else { @@ -77,49 +73,48 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) { if (InteropServiceConnection == null) await Initialize(); - bool failedFromAdminExtension = false; - if (_isAdminExtensionAvailable) + using (var adminConnectionPipeStream = new NamedPipeServerStream($"Local\\{Package.Current.Id.FamilyName}\\AdminWritePipe", + PipeDirection.InOut, 254, PipeTransmissionMode.Message, PipeOptions.Asynchronous)) { + if (!adminConnectionPipeStream.WaitForConnectionAsync().Wait(250)) + { + throw new AdminstratorAccessException(); + } + + var pipeReader = new StreamReader(adminConnectionPipeStream); + var pipeWriter = new StreamWriter(adminConnectionPipeStream); + var mapName = Guid.NewGuid().ToString(); // Create the memory-mapped file. using (var mmf = MemoryMappedFile.CreateOrOpen(mapName, data.Length > 0 ? data.Length : 1, MemoryMappedFileAccess.ReadWrite)) { - using (var stream = mmf.CreateViewStream()) + using (var writer = new BinaryWriter(mmf.CreateViewStream())) { - var writer = new BinaryWriter(stream); writer.Write(data); writer.Flush(); } - try - { - ApplicationSettingsStore.Write(SettingsKey.AdminAuthenticationTokenStr, Guid.NewGuid().ToString()); - failedFromAdminExtension = !await AdminServiceClient.SaveFileAsync( + pipeWriter.WriteLine(string.Join("?:", $"AppContainerNamedObjects\\{ WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host.ToUpper() }\\{ mapName }", filePath, - data.Length); - } - catch - { - _isAdminExtensionAvailable = false; - } - finally + data.Length)); + pipeWriter.Flush(); + + while (true) { - ApplicationSettingsStore.Remove(SettingsKey.AdminAuthenticationTokenStr); + var result = pipeReader.ReadLine(); + if ("Success".Equals(result)) + { + return; + } + else if ("Failed".Equals(result)) + { + throw new UnauthorizedAccessException(); + } } } } - - if (!_isAdminExtensionAvailable) - { - throw new AdminstratorAccessException(); - } - - if (failedFromAdminExtension) - { - throw new UnauthorizedAccessException(); - } } public static async Task CreateElevetedExtension() diff --git a/src/Notepads/Settings/SettingsKey.cs b/src/Notepads/Settings/SettingsKey.cs index 87fdbb6d7..9a5c68d2c 100644 --- a/src/Notepads/Settings/SettingsKey.cs +++ b/src/Notepads/Settings/SettingsKey.cs @@ -7,7 +7,7 @@ internal static class SettingsKey internal static string IsJumpListOutOfDateBool = "IsJumpListOutOfDateBool"; internal static string ActiveInstanceIdStr = "ActiveInstanceIdStr"; internal static string AlwaysOpenNewWindowBool = "AlwaysOpenNewWindowBool"; - internal static string AdminAuthenticationTokenStr = "AdminAuthenticationTokenStr"; + internal static string PackageSidStr = "PackageSidStr"; // Theme related internal static string RequestedThemeStr = "RequestedThemeStr"; From 914acc3ae2de9ee44b2df391def43b94451b9dd0 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 6 Aug 2020 21:08:20 +0530 Subject: [PATCH 050/181] Moved to dotnet core. --- src/Notepads.DesktopExtension/App.config | 29 ---- .../Notepads.DesktopExtension.csproj | 157 +++--------------- src/Notepads.DesktopExtension/Program.cs | 13 +- .../Properties/AssemblyInfo.cs | 36 ---- .../Properties/Resources.Designer.cs | 71 -------- .../Properties/Resources.resx | 117 ------------- .../Properties/Settings.Designer.cs | 30 ---- .../Properties/Settings.settings | 7 - src/Notepads.Package/Notepads.Package.wapproj | 4 +- src/Notepads.sln | 42 ++--- 10 files changed, 50 insertions(+), 456 deletions(-) delete mode 100644 src/Notepads.DesktopExtension/App.config delete mode 100644 src/Notepads.DesktopExtension/Properties/AssemblyInfo.cs delete mode 100644 src/Notepads.DesktopExtension/Properties/Resources.Designer.cs delete mode 100644 src/Notepads.DesktopExtension/Properties/Resources.resx delete mode 100644 src/Notepads.DesktopExtension/Properties/Settings.Designer.cs delete mode 100644 src/Notepads.DesktopExtension/Properties/Settings.settings diff --git a/src/Notepads.DesktopExtension/App.config b/src/Notepads.DesktopExtension/App.config deleted file mode 100644 index 9d9e0aee7..000000000 --- a/src/Notepads.DesktopExtension/App.config +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index 99113da96..ce302343c 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -1,148 +1,29 @@ - - - + + - Debug - AnyCPU - {66937CD2-5D8C-42F6-88B9-C963D68ACD08} WinExe - Notepads.DesktopExtension + netcoreapp3.1 Notepads32 - v4.7.2 - 512 - true - true - True - - - true - full - false - bin\Latest\ - DEBUG;TRACE - prompt - 4 - true - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - true - bin\x64\Debug\ - DEBUG;TRACE - full - x64 - 8.0 - prompt - MinimumRecommendedRules.ruleset - true - - - bin\x64\Release\ - TRACE - true - pdbonly - x64 - 8.0 - prompt - MinimumRecommendedRules.ruleset - true - - - true - bin\x86\Debug\ - DEBUG;TRACE - full - x86 - 8.0 - prompt - MinimumRecommendedRules.ruleset + Notepads + Notepads + Copyright © 2020 Jackie Liu + Notepads + Jackie Liu + Notepads + + + true - - - bin\x86\Release\ - TRACE true - pdbonly - x86 - 8.0 - prompt - MinimumRecommendedRules.ruleset - true + - - - - - - - - - - - - - - - - - - - ResXFileCodeGenerator - Resources.Designer.cs - Designer - - - True - Resources.resx - - - SettingsSingleFileGenerator - Settings.Designer.cs - - - True - Settings.settings - True - - - Settings\SettingsKey.cs - - - - - 10.0.19041.1 - - - 4.7.0 - - - 4.7.0 - - - - + + - + + - - \ No newline at end of file + + diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs index b85ff92e7..c2e9d51d1 100644 --- a/src/Notepads.DesktopExtension/Program.cs +++ b/src/Notepads.DesktopExtension/Program.cs @@ -9,7 +9,6 @@ using System.Reflection; using System.Security.Principal; using System.Threading; - using System.Windows.Forms; using Windows.ApplicationModel; using Windows.ApplicationModel.AppService; using Windows.Foundation.Collections; @@ -31,6 +30,7 @@ static class Program private static readonly string _adminCreatedLabel = "AdminCreated"; private static AppServiceConnection connection = null; + private static AutoResetEvent appServiceExit; /// /// The main entry point for the application. @@ -49,7 +49,8 @@ static void Main(string[] args) if (args.Length > 2 && args[2] == "/admin") CreateElevetedExtension(); } - Application.Run(); + appServiceExit = new AutoResetEvent(false); + appServiceExit.WaitOne(); } private static async void InitializeAppServiceConnection() @@ -65,9 +66,9 @@ private static async void InitializeAppServiceConnection() AppServiceConnectionStatus status = await connection.OpenAsync(); - if(status != AppServiceConnectionStatus.Success) + if (status != AppServiceConnectionStatus.Success) { - Application.Exit(); + appServiceExit.Set(); } var message = new ValueSet(); @@ -99,7 +100,7 @@ private static bool IsFirstInstance(string mutexName) private static void Connection_ServiceClosed(AppServiceConnection sender, AppServiceClosedEventArgs args) { // connection to the UWP lost, so we shut down the desktop process - Application.Exit(); + appServiceExit.Set(); } private static void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) @@ -116,7 +117,7 @@ private static void Connection_RequestReceived(AppServiceConnection sender, AppS CreateElevetedExtension(); break; case CommandArgs.ExitApp: - Application.Exit(); + appServiceExit.Set(); break; } diff --git a/src/Notepads.DesktopExtension/Properties/AssemblyInfo.cs b/src/Notepads.DesktopExtension/Properties/AssemblyInfo.cs deleted file mode 100644 index 9bb66f976..000000000 --- a/src/Notepads.DesktopExtension/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Notepads")] -[assembly: AssemblyDescription("Notepads")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Notepads")] -[assembly: AssemblyCopyright("Copyright © 2020 Jackie Liu")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("66937cd2-5d8c-42f6-88b9-c963d68acd08")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/Notepads.DesktopExtension/Properties/Resources.Designer.cs b/src/Notepads.DesktopExtension/Properties/Resources.Designer.cs deleted file mode 100644 index 7835f8a5c..000000000 --- a/src/Notepads.DesktopExtension/Properties/Resources.Designer.cs +++ /dev/null @@ -1,71 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Notepads.DesktopExtension.Properties -{ - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources - { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() - { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager - { - get - { - if ((resourceMan == null)) - { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Notepads.DesktopExtension.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture - { - get - { - return resourceCulture; - } - set - { - resourceCulture = value; - } - } - } -} diff --git a/src/Notepads.DesktopExtension/Properties/Resources.resx b/src/Notepads.DesktopExtension/Properties/Resources.resx deleted file mode 100644 index af7dbebba..000000000 --- a/src/Notepads.DesktopExtension/Properties/Resources.resx +++ /dev/null @@ -1,117 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Properties/Settings.Designer.cs b/src/Notepads.DesktopExtension/Properties/Settings.Designer.cs deleted file mode 100644 index 8bc4955b4..000000000 --- a/src/Notepads.DesktopExtension/Properties/Settings.Designer.cs +++ /dev/null @@ -1,30 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Notepads.DesktopExtension.Properties -{ - - - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] - internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase - { - - private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); - - public static Settings Default - { - get - { - return defaultInstance; - } - } - } -} diff --git a/src/Notepads.DesktopExtension/Properties/Settings.settings b/src/Notepads.DesktopExtension/Properties/Settings.settings deleted file mode 100644 index 39645652a..000000000 --- a/src/Notepads.DesktopExtension/Properties/Settings.settings +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/src/Notepads.Package/Notepads.Package.wapproj b/src/Notepads.Package/Notepads.Package.wapproj index 05ebde22e..123766b1d 100644 --- a/src/Notepads.Package/Notepads.Package.wapproj +++ b/src/Notepads.Package/Notepads.Package.wapproj @@ -63,7 +63,9 @@ - + + True + diff --git a/src/Notepads.sln b/src/Notepads.sln index 7887fe1ad..a22a311b3 100644 --- a/src/Notepads.sln +++ b/src/Notepads.sln @@ -19,7 +19,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Notepads.Services", "Notepa EndProject Project("{C7167F0D-BC9F-4E6E-AFE1-012C56B48DB5}") = "Notepads.Package", "Notepads.Package\Notepads.Package.wapproj", "{F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Notepads.DesktopExtension", "Notepads.DesktopExtension\Notepads.DesktopExtension.csproj", "{66937CD2-5D8C-42F6-88B9-C963D68ACD08}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Notepads.DesktopExtension", "Notepads.DesktopExtension\Notepads.DesktopExtension.csproj", "{6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -126,26 +126,26 @@ Global {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|x86.ActiveCfg = Release|x86 {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|x86.Build.0 = Release|x86 {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|x86.Deploy.0 = Release|x86 - {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Debug|Any CPU.Build.0 = Debug|Any CPU - {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Debug|ARM.ActiveCfg = Debug|Any CPU - {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Debug|ARM.Build.0 = Debug|Any CPU - {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Debug|ARM64.ActiveCfg = Debug|Any CPU - {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Debug|ARM64.Build.0 = Debug|Any CPU - {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Debug|x64.ActiveCfg = Debug|Any CPU - {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Debug|x64.Build.0 = Debug|Any CPU - {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Debug|x86.ActiveCfg = Debug|Any CPU - {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Debug|x86.Build.0 = Debug|Any CPU - {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Release|Any CPU.ActiveCfg = Release|Any CPU - {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Release|Any CPU.Build.0 = Release|Any CPU - {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Release|ARM.ActiveCfg = Release|Any CPU - {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Release|ARM.Build.0 = Release|Any CPU - {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Release|ARM64.ActiveCfg = Release|Any CPU - {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Release|ARM64.Build.0 = Release|Any CPU - {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Release|x64.ActiveCfg = Release|Any CPU - {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Release|x64.Build.0 = Release|Any CPU - {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Release|x86.ActiveCfg = Release|Any CPU - {66937CD2-5D8C-42F6-88B9-C963D68ACD08}.Release|x86.Build.0 = Release|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|ARM.ActiveCfg = Debug|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|ARM.Build.0 = Debug|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|ARM64.ActiveCfg = Debug|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|ARM64.Build.0 = Debug|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|x64.ActiveCfg = Debug|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|x64.Build.0 = Debug|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|x86.ActiveCfg = Debug|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|x86.Build.0 = Debug|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|Any CPU.Build.0 = Release|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|ARM.ActiveCfg = Release|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|ARM.Build.0 = Release|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|ARM64.ActiveCfg = Release|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|ARM64.Build.0 = Release|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|x64.ActiveCfg = Release|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|x64.Build.0 = Release|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|x86.ActiveCfg = Release|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From 4d0a9426db93aec30fb48937affc99f65d1e2100 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 7 Aug 2020 01:25:49 +0530 Subject: [PATCH 051/181] removed redundant files. --- src/Notepads/Notepads.csproj | 3 --- .../Properties/ServiceReferences.Designer.ClientConfig | 4 ---- 2 files changed, 7 deletions(-) delete mode 100644 src/Notepads/Properties/ServiceReferences.Designer.ClientConfig diff --git a/src/Notepads/Notepads.csproj b/src/Notepads/Notepads.csproj index dbfcc1f97..14c560404 100644 --- a/src/Notepads/Notepads.csproj +++ b/src/Notepads/Notepads.csproj @@ -867,9 +867,6 @@ - - - Windows Desktop Extensions for the UWP diff --git a/src/Notepads/Properties/ServiceReferences.Designer.ClientConfig b/src/Notepads/Properties/ServiceReferences.Designer.ClientConfig deleted file mode 100644 index 337de15db..000000000 --- a/src/Notepads/Properties/ServiceReferences.Designer.ClientConfig +++ /dev/null @@ -1,4 +0,0 @@ - - - - From 611f20b25d790006742912f10de800fd08d213d1 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 7 Aug 2020 07:55:27 +0530 Subject: [PATCH 052/181] fixed. --- src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index ce302343c..92b4802d9 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -13,6 +13,7 @@ + AnyCPU true true From 9c19b5f42fc54b5b4df0244c9d37f67f5822ad01 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 7 Aug 2020 08:09:16 +0530 Subject: [PATCH 053/181] fix for pipeline. --- .../Notepads.DesktopExtension.csproj | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index 92b4802d9..fc0554d9f 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -1,6 +1,8 @@ + Debug + AnyCPU WinExe netcoreapp3.1 Notepads32 @@ -15,6 +17,39 @@ AnyCPU true + true + + + + AnyCPU + true + true + true + + + + x64 + true + true + + + + x64 + true + true + true + + + + x86 + true + true + + + + x86 + true + true true From 62d56622f6d2bfd3205309c9f74753099503aa5b Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 7 Aug 2020 08:17:32 +0530 Subject: [PATCH 054/181] pipeline fix. --- .../Notepads.DesktopExtension.csproj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index fc0554d9f..a28a17024 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -27,26 +27,26 @@ true - + x64 true true - + x64 true true true - + x86 true true - + x86 true true From 0eab962467bbe7a5d694673af25503c51e526afb Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 7 Aug 2020 08:26:05 +0530 Subject: [PATCH 055/181] pipeline fix. --- .../Notepads.DesktopExtension.csproj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index a28a17024..1a5be6c4e 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -27,26 +27,26 @@ true - + x64 true true - + x64 true true true - + x86 true true - + x86 true true From 16eb4ff920c0710c3cebbfd49989254ea6ae5f8e Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 7 Aug 2020 08:42:59 +0530 Subject: [PATCH 056/181] fix pipeline. --- .../Notepads.DesktopExtension.csproj | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index 1a5be6c4e..e64074fa3 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -5,6 +5,7 @@ AnyCPU WinExe netcoreapp3.1 + win-x86 Notepads32 Notepads Notepads @@ -27,26 +28,26 @@ true - + x64 true true - + x64 true true true - + x86 true true - + x86 true true From 3118ce989563cf102bf4e2cb4ce04fa31cf523c6 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 7 Aug 2020 08:55:55 +0530 Subject: [PATCH 057/181] pipeline fix. --- .../Notepads.DesktopExtension.csproj | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index e64074fa3..ba598183a 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -5,7 +5,6 @@ AnyCPU WinExe netcoreapp3.1 - win-x86 Notepads32 Notepads Notepads @@ -30,12 +29,14 @@ x64 + win-x64 true true x64 + win-x64 true true true @@ -43,12 +44,14 @@ x86 + win-x86 true true x86 + win-x86 true true true From d327d5d2a07d950f9894b2b6bd1a3e20fd3b4ae3 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 7 Aug 2020 09:03:21 +0530 Subject: [PATCH 058/181] pipeline fix. --- .../Notepads.DesktopExtension.csproj | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index ba598183a..bae9762b0 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -5,6 +5,7 @@ AnyCPU WinExe netcoreapp3.1 + win Notepads32 Notepads Notepads @@ -29,14 +30,12 @@ x64 - win-x64 true true x64 - win-x64 true true true @@ -44,14 +43,12 @@ x86 - win-x86 true true x86 - win-x86 true true true From 064306384060c28ec72cdc1f3af8238dfa80bb95 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 7 Aug 2020 09:10:54 +0530 Subject: [PATCH 059/181] fixed pipeline. --- .../Notepads.DesktopExtension.csproj | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index bae9762b0..c35657d73 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -5,7 +5,6 @@ AnyCPU WinExe netcoreapp3.1 - win Notepads32 Notepads Notepads @@ -15,39 +14,39 @@ Notepads - + AnyCPU true true - + AnyCPU true true true - + x64 true true - + x64 true true true - + x86 true true - + x86 true true From 6d850c8c9a120d963f3c778542e0a364af009a58 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 7 Aug 2020 09:24:52 +0530 Subject: [PATCH 060/181] fixed pipeline. --- .../Notepads.DesktopExtension.csproj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index c35657d73..50d78729f 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -27,26 +27,26 @@ true - + x64 true true - + x64 true true true - + x86 true true - + x86 true true From 07adf95414f4917e139adc1b32fdcb6da073d476 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 7 Aug 2020 09:35:11 +0530 Subject: [PATCH 061/181] pipeline fix. --- .../Notepads.DesktopExtension.csproj | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index 50d78729f..fb3940a03 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -14,40 +14,46 @@ Notepads - + AnyCPU + any true true - + AnyCPU + any true true true - + x64 + win-x64 true true - + x64 + win-x64 true true true - + x86 + win-x86 true true - + x86 + win-x86 true true true From 37c7382216c9817038186fcec716a3e676110ad6 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 7 Aug 2020 09:39:03 +0530 Subject: [PATCH 062/181] pipeline fix. --- src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index fb3940a03..ba598183a 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -16,14 +16,12 @@ AnyCPU - any true true AnyCPU - any true true true From d33fa95d78e2af0823256684f6b6f39e7a58d0c3 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 7 Aug 2020 11:21:44 +0530 Subject: [PATCH 063/181] code-refactor and added documentation. --- .../Notepads.DesktopExtension.csproj | 9 +- src/Notepads.DesktopExtension/Program.cs | 91 ++++++++++--------- .../DesktopExtensionConnectionService.cs | 16 ++-- .../Notepads.Services.csproj | 4 +- .../Services/DesktopExtensionService.cs | 39 ++++++-- src/Notepads/Settings/SettingsKey.cs | 3 + src/Notepads/Utilities/FileSystemUtility.cs | 2 +- 7 files changed, 90 insertions(+), 74 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index ba598183a..f91316166 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -5,6 +5,7 @@ AnyCPU WinExe netcoreapp3.1 + win-$(Platform) Notepads32 Notepads Notepads @@ -29,14 +30,12 @@ x64 - win-x64 true true x64 - win-x64 true true true @@ -44,15 +43,11 @@ x86 - win-x86 - true true x86 - win-x86 - true true true @@ -62,6 +57,8 @@ + + diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs index c2e9d51d1..e88ecec76 100644 --- a/src/Notepads.DesktopExtension/Program.cs +++ b/src/Notepads.DesktopExtension/Program.cs @@ -26,9 +26,6 @@ static class Program private const string DesktopExtensionMutexName = "DesktopExtensionMutexName"; private const string AdminExtensionMutexName = "AdminExtensionMutexName"; - private static readonly string _commandLabel = "Command"; - private static readonly string _adminCreatedLabel = "AdminCreated"; - private static AppServiceConnection connection = null; private static AutoResetEvent appServiceExit; @@ -71,8 +68,7 @@ private static async void InitializeAppServiceConnection() appServiceExit.Set(); } - var message = new ValueSet(); - message.Add(_commandLabel, CommandArgs.RegisterExtension.ToString()); + var message = new ValueSet { { SettingsKey.InteropCommandLabel, CommandArgs.RegisterExtension.ToString() } }; await connection.SendMessageAsync(message); } @@ -110,7 +106,7 @@ private static void Connection_RequestReceived(AppServiceConnection sender, AppS var messageDeferral = args.GetDeferral(); var message = args.Request.Message; - if (!message.ContainsKey(_commandLabel) || !Enum.TryParse((string)message[_commandLabel], out var command)) return; + if (!message.ContainsKey(SettingsKey.InteropCommandLabel) || !Enum.TryParse((string)message[SettingsKey.InteropCommandLabel], out var command)) return; switch (command) { case CommandArgs.CreateElevetedExtension: @@ -126,8 +122,8 @@ private static void Connection_RequestReceived(AppServiceConnection sender, AppS private static async void CreateElevetedExtension() { - var message = new ValueSet(); - message.Add(_commandLabel, CommandArgs.CreateElevetedExtension.ToString()); + var message = new ValueSet { { SettingsKey.InteropCommandLabel, CommandArgs.CreateElevetedExtension.ToString() } }; + try { string result = Assembly.GetExecutingAssembly().Location; @@ -135,17 +131,20 @@ private static async void CreateElevetedExtension() string rootPath = $"{result.Substring(0, index)}\\..\\"; string aliasPath = rootPath + @"\Notepads.DesktopExtension\Notepads32.exe"; - ProcessStartInfo info = new ProcessStartInfo(); - info.Verb = "runas"; - info.UseShellExecute = true; - info.FileName = aliasPath; + ProcessStartInfo info = new ProcessStartInfo + { + Verb = "runas", + UseShellExecute = true, + FileName = aliasPath + }; + var process = Process.Start(info); AppDomain.CurrentDomain.ProcessExit += (a, b) => process.Kill(); - message.Add(_adminCreatedLabel, true); + message.Add(SettingsKey.InteropCommandAdminCreatedLabel, true); } catch { - message.Add(_adminCreatedLabel, false); + message.Add(SettingsKey.InteropCommandAdminCreatedLabel, false); } finally { @@ -155,44 +154,46 @@ private static async void CreateElevetedExtension() private static async void SaveFileFromPipeData() { - using (var clientStream = new NamedPipeClientStream(".", + using var clientStream = new NamedPipeClientStream(".", $"Sessions\\1\\AppContainerNamedObjects\\{ReadSettingsKey(SettingsKey.PackageSidStr)}\\{Package.Current.Id.FamilyName}\\AdminWritePipe", - PipeDirection.InOut, PipeOptions.Asynchronous)) - { - await clientStream.ConnectAsync(); - new Thread(new ThreadStart(SaveFileFromPipeData)).Start(); + PipeDirection.InOut, PipeOptions.Asynchronous); - var pipeReader = new StreamReader(clientStream); - var pipeWriter = new StreamWriter(clientStream); + // Wait for uwp app to send request to write to file. + await clientStream.ConnectAsync(); - var writeData = pipeReader.ReadLine().Split(new string[] { "?:" }, StringSplitOptions.None); + // Start another thread to accept more write requests. + new Thread(new ThreadStart(SaveFileFromPipeData)).Start(); - var memoryMapName = writeData[0]; - var filePath = writeData[1]; - int.TryParse(writeData[2], out int dataArrayLength); + var pipeReader = new StreamReader(clientStream); + var pipeWriter = new StreamWriter(clientStream); - var result = "Failed"; - try - { - // Open the memory-mapped file. - using (var mmf = MemoryMappedFile.OpenExisting(memoryMapName)) - { - using (var stream = mmf.CreateViewStream()) - { - var reader = new BinaryReader(stream); - var data = reader.ReadBytes(dataArrayLength); - - await PathIO.WriteBytesAsync(filePath, data); - } - } - - result = "Success"; - } - finally + var writeData = pipeReader.ReadLine().Split(new string[] { "?:" }, StringSplitOptions.None); + + var memoryMapName = writeData[0]; + var filePath = writeData[1]; + int.TryParse(writeData[2], out int dataArrayLength); + + var result = "Failed"; + try + { + // Open the memory-mapped file and read data from it. + using (var reader = new BinaryReader(MemoryMappedFile.OpenExisting(memoryMapName).CreateViewStream())) { - pipeWriter.WriteLine(result); - pipeWriter.Flush(); + var data = reader.ReadBytes(dataArrayLength); + + await PathIO.WriteBytesAsync(filePath, data); } + + result = "Success"; + } + catch + { + // Do nothing + } + finally + { + pipeWriter.WriteLine(result); + pipeWriter.Flush(); } } diff --git a/src/Notepads.Services/DesktopExtensionConnectionService.cs b/src/Notepads.Services/DesktopExtensionConnectionService.cs index d005755dd..2c38c0fc8 100644 --- a/src/Notepads.Services/DesktopExtensionConnectionService.cs +++ b/src/Notepads.Services/DesktopExtensionConnectionService.cs @@ -1,5 +1,6 @@ namespace Notepads.Services { + using Notepads.Settings; using System; using System.Collections.Generic; using System.Threading.Tasks; @@ -20,10 +21,7 @@ public sealed class DesktopExtensionConnectionService : IBackgroundTask private BackgroundTaskDeferral backgroundTaskDeferral; private AppServiceConnection appServiceConnection; private static AppServiceConnection extensionAppServiceConnection = null; - private static IList appServiceConnections = new List(); - - private static readonly string _commandLabel = "Command"; - private static readonly string _failedLabel = "Failed"; + private static readonly IList appServiceConnections = new List(); public void Run(IBackgroundTaskInstance taskInstance) { @@ -54,7 +52,8 @@ private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequ var messageDeferral = args.GetDeferral(); var message = args.Request.Message; - if (!message.ContainsKey(_commandLabel) || !Enum.TryParse(typeof(CommandArgs), (string)message[_commandLabel], out var result)) return; + if (!message.ContainsKey(SettingsKey.InteropCommandLabel) || + !Enum.TryParse(typeof(CommandArgs), (string)message[SettingsKey.InteropCommandLabel], out var result)) return; var command = (CommandArgs)result; switch (command) @@ -83,7 +82,7 @@ private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequ if (extensionAppServiceConnection == null) { message.Clear(); - message.Add(_failedLabel, true); + message.Add(SettingsKey.InteropCommandFailedLabel, true); } else { @@ -91,7 +90,7 @@ private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequ if (response.Status != AppServiceResponseStatus.Success) { message.Clear(); - message.Add(_failedLabel, true); + message.Add(SettingsKey.InteropCommandFailedLabel, true); extensionAppServiceConnection = null; } else @@ -124,8 +123,7 @@ private async void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTask appServiceConnections.Remove(serviceConnection); if (appServiceConnections.Count == 0 && extensionAppServiceConnection != null) { - var message = new ValueSet(); - message.Add(_commandLabel, CommandArgs.ExitApp.ToString()); + var message = new ValueSet { { SettingsKey.InteropCommandLabel, CommandArgs.ExitApp.ToString() } }; await extensionAppServiceConnection.SendMessageAsync(message); } } diff --git a/src/Notepads.Services/Notepads.Services.csproj b/src/Notepads.Services/Notepads.Services.csproj index 28d1b3e89..4763b9f13 100644 --- a/src/Notepads.Services/Notepads.Services.csproj +++ b/src/Notepads.Services/Notepads.Services.csproj @@ -123,15 +123,13 @@ + 6.2.10 - - - 14.0 diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index ce826c128..1fa51cfad 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -1,6 +1,7 @@ namespace Notepads.Services { using Notepads.Extensions; + using Notepads.Settings; using System; using System.IO; using System.IO.MemoryMappedFiles; @@ -18,6 +19,9 @@ public class AdminstratorAccessException : Exception { public AdminstratorAccessException():base("Failed to save due to no Adminstration access") { } + + public AdminstratorAccessException(string message) : base(message) { } + public AdminstratorAccessException(string message, Exception innerException) : base(message, innerException) { } } public static class DesktopExtensionService @@ -25,10 +29,6 @@ public static class DesktopExtensionService public static AppServiceConnection InteropServiceConnection = null; private static readonly ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView(); - private static readonly string _commandLabel = "Command"; - private static readonly string _failedLabel = "Failed"; - private static readonly string _adminCreatedLabel = "AdminCreated"; - public static async Task Initialize() { InteropServiceConnection = new AppServiceConnection() @@ -48,12 +48,13 @@ public static async Task Initialize() private static async void InteropServiceConnection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { var message = args.Request.Message; - if (!message.ContainsKey(_commandLabel) || !Enum.TryParse(typeof(CommandArgs), (string)message[_commandLabel], out var commandObj) || + if (!message.ContainsKey(SettingsKey.InteropCommandLabel) || + !Enum.TryParse(typeof(CommandArgs), (string)message[SettingsKey.InteropCommandLabel], out var commandObj) || (CommandArgs)commandObj != CommandArgs.CreateElevetedExtension) return; await CoreApplication.MainView.CoreWindow.Dispatcher.CallOnUIThreadAsync(() => { - if (message.ContainsKey(_adminCreatedLabel) && (bool)message[_adminCreatedLabel]) + if (message.ContainsKey(SettingsKey.InteropCommandAdminCreatedLabel) && (bool)message[SettingsKey.InteropCommandAdminCreatedLabel]) { NotificationCenter.Instance.PostNotification(_resourceLoader.GetString("TextEditor_NotificationMsg_AdminExtensionCreated"), 1500); } @@ -69,6 +70,14 @@ private static void InteropServiceConnection_ServiceClosed(AppServiceConnection return; } + /// + /// Write data to system file. + /// + /// + /// Only available for legacy Windows 10 desktop. + /// + /// Absolute path of the file to write. + /// Data to write. public static async Task SaveFileAsAdmin(string filePath, byte[] data) { if (InteropServiceConnection == null) await Initialize(); @@ -76,8 +85,11 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) using (var adminConnectionPipeStream = new NamedPipeServerStream($"Local\\{Package.Current.Id.FamilyName}\\AdminWritePipe", PipeDirection.InOut, 254, PipeTransmissionMode.Message, PipeOptions.Asynchronous)) { + // Wait for 250 ms for desktop extension to accept request. if (!adminConnectionPipeStream.WaitForConnectionAsync().Wait(250)) { + // If the connection fails, desktop extension is not launched with elevated privilages. + // In that case, prompt user to launch desktop extension with elevated privilages. throw new AdminstratorAccessException(); } @@ -86,7 +98,7 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) var mapName = Guid.NewGuid().ToString(); - // Create the memory-mapped file. + // Create the memory-mapped file and write original file data to be written. using (var mmf = MemoryMappedFile.CreateOrOpen(mapName, data.Length > 0 ? data.Length : 1, MemoryMappedFileAccess.ReadWrite)) { using (var writer = new BinaryWriter(mmf.CreateViewStream())) @@ -101,6 +113,7 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) data.Length)); pipeWriter.Flush(); + // Wait for desktop extension to send response. while (true) { var result = pipeReader.ReadLine(); @@ -110,6 +123,7 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) } else if ("Failed".Equals(result)) { + // Promt user to "Save As" if extension failed to save data. throw new UnauthorizedAccessException(); } } @@ -117,16 +131,21 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) } } + /// + /// Launch desktop extension with elevated privilages. + /// + /// + /// Only available for legacy Windows 10 desktop. + /// public static async Task CreateElevetedExtension() { if (InteropServiceConnection == null) await Initialize(); - var message = new ValueSet(); - message.Add(_commandLabel, CommandArgs.CreateElevetedExtension.ToString()); + var message = new ValueSet { { SettingsKey.InteropCommandLabel, CommandArgs.CreateElevetedExtension.ToString() } }; var response = await InteropServiceConnection.SendMessageAsync(message); message = response.Message; - if (message.ContainsKey(_failedLabel) && (bool)message[_failedLabel]) + if (message.ContainsKey(SettingsKey.InteropCommandFailedLabel) && (bool)message[SettingsKey.InteropCommandFailedLabel]) { await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync("LaunchAdmin"); } diff --git a/src/Notepads/Settings/SettingsKey.cs b/src/Notepads/Settings/SettingsKey.cs index 9a5c68d2c..abf5791ff 100644 --- a/src/Notepads/Settings/SettingsKey.cs +++ b/src/Notepads/Settings/SettingsKey.cs @@ -8,6 +8,9 @@ internal static class SettingsKey internal static string ActiveInstanceIdStr = "ActiveInstanceIdStr"; internal static string AlwaysOpenNewWindowBool = "AlwaysOpenNewWindowBool"; internal static string PackageSidStr = "PackageSidStr"; + internal static string InteropCommandLabel = "Command"; + internal static string InteropCommandFailedLabel = "Failed"; + internal static string InteropCommandAdminCreatedLabel = "AdminCreated"; // Theme related internal static string RequestedThemeStr = "RequestedThemeStr"; diff --git a/src/Notepads/Utilities/FileSystemUtility.cs b/src/Notepads/Utilities/FileSystemUtility.cs index 6d648df16..2ba69877f 100644 --- a/src/Notepads/Utilities/FileSystemUtility.cs +++ b/src/Notepads/Utilities/FileSystemUtility.cs @@ -578,7 +578,7 @@ public static async Task WriteToFile(string text, Encoding encoding, StorageFile { await PathIO.WriteBytesAsync(file.Path, result); } - catch (UnauthorizedAccessException ex) // Try to save as admin if dektop extension supported + catch (UnauthorizedAccessException ex) // Try to save as admin if fullTrust api is supported { if (!ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0)) { From 215a272fd32db4a8c6a7efc0c15d61c44cdbfd43 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 7 Aug 2020 13:14:40 +0530 Subject: [PATCH 064/181] pipeline fix. --- src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index f91316166..d79120429 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -5,7 +5,7 @@ AnyCPU WinExe netcoreapp3.1 - win-$(Platform) + win-x86;win-x64 Notepads32 Notepads Notepads From ef331ac91864e77ae484d869f7a36edc156889a1 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 7 Aug 2020 16:31:09 +0530 Subject: [PATCH 065/181] Moved to dotnet 5. --- .../Notepads.DesktopExtension.csproj | 139 +++++++++++------- src/Notepads.sln | 2 +- 2 files changed, 86 insertions(+), 55 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index d79120429..278c0e1d1 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -1,66 +1,97 @@ - - Debug - AnyCPU - WinExe - netcoreapp3.1 - win-x86;win-x64 - Notepads32 - Notepads - Notepads - Copyright © 2020 Jackie Liu - Notepads - Jackie Liu - Notepads - + + Debug + AnyCPU + net5.0 + win10-x86; win10-x64; win10-arm64; win10-arm + Notepads32 + Notepads + Notepads + Copyright © 2020 Jackie Liu + Notepads + Jackie Liu + Notepads + - - AnyCPU - true - true - + + Exe + AnyCPU + true + true + - - AnyCPU - true - true - true - + + WinExe + AnyCPU + true + true + true + - - x64 - true - true - + + Exe + x64 + true + true + - - x64 - true - true - true - + + WinExe + x64 + true + true + true + - - x86 - true - + + Exe + x86 + true + - - x86 - true - true - + + WinExe + x86 + true + true + - - - + + Exe + ARM64 + true + true + - - - - - - + + WinExe + ARM64 + true + true + true + + + Exe + ARM + true + + + + WinExe + ARM + true + true + + + + + + + + + + + diff --git a/src/Notepads.sln b/src/Notepads.sln index a22a311b3..dc3c8bd3a 100644 --- a/src/Notepads.sln +++ b/src/Notepads.sln @@ -19,7 +19,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Notepads.Services", "Notepa EndProject Project("{C7167F0D-BC9F-4E6E-AFE1-012C56B48DB5}") = "Notepads.Package", "Notepads.Package\Notepads.Package.wapproj", "{F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Notepads.DesktopExtension", "Notepads.DesktopExtension\Notepads.DesktopExtension.csproj", "{6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Notepads.DesktopExtension", "Notepads.DesktopExtension\Notepads.DesktopExtension.csproj", "{6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution From 629efb58e0c321c0ffa24f3499a7bbe3a8c08be4 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 8 Aug 2020 09:16:26 +0530 Subject: [PATCH 066/181] Fixed extension crashing. --- .../Notepads.DesktopExtension.csproj | 32 +++++++++---------- src/Notepads.DesktopExtension/Program.cs | 28 +++++++++++++++- .../Views/MainPage/NotepadsMainPage.xaml.cs | 1 + 3 files changed, 44 insertions(+), 17 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index 278c0e1d1..88745beda 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -14,21 +14,6 @@ Notepads - - Exe - AnyCPU - true - true - - - - WinExe - AnyCPU - true - true - true - - Exe x64 @@ -85,12 +70,27 @@ true + + Exe + AnyCPU + true + true + + + + WinExe + AnyCPU + true + true + true + + - + diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs index e88ecec76..10ae15a8b 100644 --- a/src/Notepads.DesktopExtension/Program.cs +++ b/src/Notepads.DesktopExtension/Program.cs @@ -52,6 +52,8 @@ static void Main(string[] args) private static async void InitializeAppServiceConnection() { + PrintDebugMessage("Successfully started Desktop Extension."); + connection = new AppServiceConnection() { AppServiceName = "DesktopExtensionServiceConnection", @@ -70,10 +72,15 @@ private static async void InitializeAppServiceConnection() var message = new ValueSet { { SettingsKey.InteropCommandLabel, CommandArgs.RegisterExtension.ToString() } }; await connection.SendMessageAsync(message); + + PrintDebugMessage("Successfully created App Service."); } private static void InitializeExtensionService() { + PrintDebugMessage("Successfully started Adminstrator Extension."); + PrintDebugMessage("Waiting on uwp app to send data."); + SaveFileFromPipeData(); } @@ -88,6 +95,8 @@ private static bool IsFirstInstance(string mutexName) else { instanceHandlerMutex.Close(); + + PrintDebugMessage("Closing this instance as another instance is already running.", 5000); } return isFirstInstance; @@ -141,10 +150,14 @@ private static async void CreateElevetedExtension() var process = Process.Start(info); AppDomain.CurrentDomain.ProcessExit += (a, b) => process.Kill(); message.Add(SettingsKey.InteropCommandAdminCreatedLabel, true); + + PrintDebugMessage("Adminstrator Extension has been launched."); } catch { message.Add(SettingsKey.InteropCommandAdminCreatedLabel, false); + + PrintDebugMessage("User canceled launching of Adminstrator Extension."); } finally { @@ -185,15 +198,19 @@ private static async void SaveFileFromPipeData() } result = "Success"; + + PrintDebugMessage($"Successfully wrote to \"{filePath}\"."); } catch { - // Do nothing + PrintDebugMessage($"Failed to write to \"{filePath}\"."); } finally { pipeWriter.WriteLine(result); pipeWriter.Flush(); + + PrintDebugMessage("Waiting on uwp app to send data."); } } @@ -209,5 +226,14 @@ public static object ReadSettingsKey(string key) return obj; } + + private static void PrintDebugMessage(string message, int waitAfterPrintingTime = 0) + { +#if DEBUG + Console.WriteLine(message); + Debug.WriteLine(message); + Thread.Sleep(waitAfterPrintingTime); +#endif + } } } diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs index 80d711c54..e7c3cb10b 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs @@ -297,6 +297,7 @@ private async void App_EnteredBackground(object sender, Windows.ApplicationModel private async void App_LeavingBackground(object sender, LeavingBackgroundEventArgs e) { await DesktopExtensionService.Initialize(); + await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); } public void ExecuteProtocol(Uri uri) From 3080f67fe12ff8744355b23ce88c78700e5d42a1 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 8 Aug 2020 15:24:02 +0530 Subject: [PATCH 067/181] Added ARM builds for desktop extension. --- .../Notepads.DesktopExtension.csproj | 5 ++ src/Notepads.sln | 49 +++++++++--------- src/Notepads/Notepads.csproj | 51 +++++++++++++++++-- 3 files changed, 77 insertions(+), 28 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index 88745beda..e4159df6f 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -5,6 +5,7 @@ AnyCPU net5.0 win10-x86; win10-x64; win10-arm64; win10-arm + AnyCPU; x64; x86; ARM64; ARM Notepads32 Notepads Notepads @@ -32,12 +33,14 @@ Exe x86 + true true WinExe x86 + true true true @@ -60,12 +63,14 @@ Exe ARM + true true WinExe ARM + true true true diff --git a/src/Notepads.sln b/src/Notepads.sln index dc3c8bd3a..c3e7a615a 100644 --- a/src/Notepads.sln +++ b/src/Notepads.sln @@ -35,27 +35,26 @@ Global Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {99274932-9E86-480C-8142-38525F80007D}.Debug|Any CPU.ActiveCfg = Debug|x86 - {99274932-9E86-480C-8142-38525F80007D}.Debug|ARM.ActiveCfg = Debug|x86 + {99274932-9E86-480C-8142-38525F80007D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {99274932-9E86-480C-8142-38525F80007D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {99274932-9E86-480C-8142-38525F80007D}.Debug|ARM.ActiveCfg = Debug|ARM + {99274932-9E86-480C-8142-38525F80007D}.Debug|ARM.Build.0 = Debug|ARM {99274932-9E86-480C-8142-38525F80007D}.Debug|ARM64.ActiveCfg = Debug|ARM64 {99274932-9E86-480C-8142-38525F80007D}.Debug|ARM64.Build.0 = Debug|ARM64 - {99274932-9E86-480C-8142-38525F80007D}.Debug|ARM64.Deploy.0 = Debug|ARM64 {99274932-9E86-480C-8142-38525F80007D}.Debug|x64.ActiveCfg = Debug|x64 {99274932-9E86-480C-8142-38525F80007D}.Debug|x64.Build.0 = Debug|x64 {99274932-9E86-480C-8142-38525F80007D}.Debug|x86.ActiveCfg = Debug|x86 {99274932-9E86-480C-8142-38525F80007D}.Debug|x86.Build.0 = Debug|x86 - {99274932-9E86-480C-8142-38525F80007D}.Debug|x86.Deploy.0 = Debug|x86 - {99274932-9E86-480C-8142-38525F80007D}.Release|Any CPU.ActiveCfg = Release|x86 - {99274932-9E86-480C-8142-38525F80007D}.Release|ARM.ActiveCfg = Release|x86 + {99274932-9E86-480C-8142-38525F80007D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {99274932-9E86-480C-8142-38525F80007D}.Release|Any CPU.Build.0 = Release|Any CPU + {99274932-9E86-480C-8142-38525F80007D}.Release|ARM.ActiveCfg = Release|ARM + {99274932-9E86-480C-8142-38525F80007D}.Release|ARM.Build.0 = Release|ARM {99274932-9E86-480C-8142-38525F80007D}.Release|ARM64.ActiveCfg = Release|ARM64 {99274932-9E86-480C-8142-38525F80007D}.Release|ARM64.Build.0 = Release|ARM64 - {99274932-9E86-480C-8142-38525F80007D}.Release|ARM64.Deploy.0 = Release|ARM64 {99274932-9E86-480C-8142-38525F80007D}.Release|x64.ActiveCfg = Release|x64 {99274932-9E86-480C-8142-38525F80007D}.Release|x64.Build.0 = Release|x64 - {99274932-9E86-480C-8142-38525F80007D}.Release|x64.Deploy.0 = Release|x64 {99274932-9E86-480C-8142-38525F80007D}.Release|x86.ActiveCfg = Release|x86 {99274932-9E86-480C-8142-38525F80007D}.Release|x86.Build.0 = Release|x86 - {99274932-9E86-480C-8142-38525F80007D}.Release|x86.Deploy.0 = Release|x86 {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|Any CPU.Build.0 = Debug|Any CPU {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|ARM.ActiveCfg = Debug|ARM @@ -128,24 +127,24 @@ Global {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|x86.Deploy.0 = Release|x86 {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|ARM.ActiveCfg = Debug|Any CPU - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|ARM.Build.0 = Debug|Any CPU - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|ARM64.ActiveCfg = Debug|Any CPU - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|ARM64.Build.0 = Debug|Any CPU - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|x64.ActiveCfg = Debug|Any CPU - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|x64.Build.0 = Debug|Any CPU - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|x86.ActiveCfg = Debug|Any CPU - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|x86.Build.0 = Debug|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|ARM.ActiveCfg = Debug|ARM + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|ARM.Build.0 = Debug|ARM + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|ARM64.Build.0 = Debug|ARM64 + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|x64.ActiveCfg = Debug|x64 + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|x64.Build.0 = Debug|x64 + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|x86.ActiveCfg = Debug|x86 + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|x86.Build.0 = Debug|x86 {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|Any CPU.ActiveCfg = Release|Any CPU {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|Any CPU.Build.0 = Release|Any CPU - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|ARM.ActiveCfg = Release|Any CPU - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|ARM.Build.0 = Release|Any CPU - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|ARM64.ActiveCfg = Release|Any CPU - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|ARM64.Build.0 = Release|Any CPU - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|x64.ActiveCfg = Release|Any CPU - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|x64.Build.0 = Release|Any CPU - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|x86.ActiveCfg = Release|Any CPU - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|x86.Build.0 = Release|Any CPU + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|ARM.ActiveCfg = Release|ARM + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|ARM.Build.0 = Release|ARM + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|ARM64.ActiveCfg = Release|ARM64 + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|ARM64.Build.0 = Release|ARM64 + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|x64.ActiveCfg = Release|x64 + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|x64.Build.0 = Release|x64 + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|x86.ActiveCfg = Release|x86 + {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/Notepads/Notepads.csproj b/src/Notepads/Notepads.csproj index 14c560404..f7c31748e 100644 --- a/src/Notepads/Notepads.csproj +++ b/src/Notepads/Notepads.csproj @@ -3,7 +3,7 @@ Debug - x86 + AnyCPU {99274932-9E86-480C-8142-38525F80007D} AppContainerExe Properties @@ -23,7 +23,7 @@ OnApplicationRun False True - x86|x64|arm64 + x86|x64|arm64|arm Resource\MiddleClickScrolling-CursorType.res @@ -59,7 +59,6 @@ false prompt true - true bin\ARM64\Release\ @@ -73,6 +72,29 @@ true true + + true + bin\ARM\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP;DISABLE_XAML_GENERATED_MAIN + ;2008 + full + ARM + false + prompt + true + + + bin\ARM\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP;DISABLE_XAML_GENERATED_MAIN + true + ;2008 + pdbonly + ARM + false + prompt + true + true + true bin\x64\Debug\ @@ -97,6 +119,29 @@ true true + + true + bin\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP;DISABLE_XAML_GENERATED_MAIN + ;2008 + full + AnyCPU + false + prompt + true + + + bin\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP;DISABLE_XAML_GENERATED_MAIN + true + ;2008 + pdbonly + AnyCPU + false + prompt + true + true + PackageReference From 1cff7331a265e4f87fe838e96f02055598de7c64 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 8 Aug 2020 16:27:15 +0530 Subject: [PATCH 068/181] updated targets. --- azure-pipelines.yml | 3 +- src/Notepads.Package/Package.appxmanifest | 2 +- src/Notepads/Notepads.csproj | 94 +++++++++++------------ 3 files changed, 49 insertions(+), 50 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 9781906e6..0cac1f6bc 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -20,9 +20,8 @@ steps: script: | [xml]$manifest = Get-Content $(Build.SourcesDirectory)\src\Notepads.Package\Package.appxmanifest $manifest.Package.Identity.Name="Notepads" - $manifest.Package.Identity.Version="1.3.9.0" - $manifest.Package.Properties.DisplayName="Notepads App" $manifest.Package.Applications.Application.VisualElements.DisplayName="Notepads" + $manifest.Package.Applications.Application.Extensions.Extension.AppExecutionAlias.ExecutionAlias.Alias="Notepads.exe" $manifest.Save('$(Build.SourcesDirectory)\src\Notepads.Package\Package.appxmanifest') failOnStderr: true diff --git a/src/Notepads.Package/Package.appxmanifest b/src/Notepads.Package/Package.appxmanifest index ae1b1021a..d18c61c92 100644 --- a/src/Notepads.Package/Package.appxmanifest +++ b/src/Notepads.Package/Package.appxmanifest @@ -11,7 +11,7 @@ xmlns:desktop4="http://schemas.microsoft.com/appx/manifest/desktop/windows10/4" xmlns:iot2="http://schemas.microsoft.com/appx/manifest/iot/windows10/2" xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" - IgnorableNamespaces="mp uap uap3 uap5 uap10 desktop4 iot2 rescap"> + IgnorableNamespaces="mp uap uap3 uap5 uap10 desktop desktop4 iot2 rescap"> true true - - true - bin\ARM\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP;DISABLE_XAML_GENERATED_MAIN - ;2008 - full - ARM - false - prompt - true - - - bin\ARM\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP;DISABLE_XAML_GENERATED_MAIN - true - ;2008 - pdbonly - ARM - false - prompt - true - true - + + true + bin\ARM\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP;DISABLE_XAML_GENERATED_MAIN + ;2008 + full + ARM + false + prompt + true + + + bin\ARM\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP;DISABLE_XAML_GENERATED_MAIN + true + ;2008 + pdbonly + ARM + false + prompt + true + true + true bin\x64\Debug\ @@ -119,29 +119,29 @@ true true - - true - bin\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP;DISABLE_XAML_GENERATED_MAIN - ;2008 - full - AnyCPU - false - prompt - true - - - bin\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP;DISABLE_XAML_GENERATED_MAIN - true - ;2008 - pdbonly - AnyCPU - false - prompt - true - true - + + true + bin\Debug\ + DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP;DISABLE_XAML_GENERATED_MAIN + ;2008 + full + AnyCPU + false + prompt + true + + + bin\Release\ + TRACE;NETFX_CORE;WINDOWS_UWP;DISABLE_XAML_GENERATED_MAIN + true + ;2008 + pdbonly + AnyCPU + false + prompt + true + true + PackageReference @@ -913,7 +913,7 @@ - + Windows Desktop Extensions for the UWP From fb9e3f0d9944ca72f02cb9e223bab33f4646ac65 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 8 Aug 2020 18:01:23 +0530 Subject: [PATCH 069/181] Implemented handling multiple sessions. --- src/Notepads.DesktopExtension/Program.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs index 10ae15a8b..b39783791 100644 --- a/src/Notepads.DesktopExtension/Program.cs +++ b/src/Notepads.DesktopExtension/Program.cs @@ -26,6 +26,7 @@ static class Program private const string DesktopExtensionMutexName = "DesktopExtensionMutexName"; private const string AdminExtensionMutexName = "AdminExtensionMutexName"; + private static readonly int sessionId = Process.GetCurrentProcess().SessionId; private static AppServiceConnection connection = null; private static AutoResetEvent appServiceExit; @@ -168,7 +169,7 @@ private static async void CreateElevetedExtension() private static async void SaveFileFromPipeData() { using var clientStream = new NamedPipeClientStream(".", - $"Sessions\\1\\AppContainerNamedObjects\\{ReadSettingsKey(SettingsKey.PackageSidStr)}\\{Package.Current.Id.FamilyName}\\AdminWritePipe", + $"Sessions\\{sessionId}\\AppContainerNamedObjects\\{ReadSettingsKey(SettingsKey.PackageSidStr)}\\{Package.Current.Id.FamilyName}\\AdminWritePipe", PipeDirection.InOut, PipeOptions.Asynchronous); // Wait for uwp app to send request to write to file. From 9ae0cb84146e9309ed701c540abebd4004e20265 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 8 Aug 2020 20:11:58 +0530 Subject: [PATCH 070/181] Fixed compiling with "Any Cpu" option. --- .../Notepads.Controls.csproj | 21 +--------------- .../Notepads.DesktopExtension.csproj | 17 +------------ src/Notepads.Package/Notepads.Package.wapproj | 8 ------ .../Notepads.Services.csproj | 21 +--------------- src/Notepads.sln | 24 ------------------ src/Notepads/Notepads.csproj | 25 +------------------ 6 files changed, 4 insertions(+), 112 deletions(-) diff --git a/src/Notepads.Controls/Notepads.Controls.csproj b/src/Notepads.Controls/Notepads.Controls.csproj index 7075fca27..73ece057e 100644 --- a/src/Notepads.Controls/Notepads.Controls.csproj +++ b/src/Notepads.Controls/Notepads.Controls.csproj @@ -3,7 +3,7 @@ Debug - AnyCPU + x86 {7AA5E631-B663-420E-A08F-002CD81DF855} Library Properties @@ -17,25 +17,6 @@ 512 {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - prompt - 4 - x86 true diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index e4159df6f..0064c589a 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -2,7 +2,7 @@ Debug - AnyCPU + x86 net5.0 win10-x86; win10-x64; win10-arm64; win10-arm AnyCPU; x64; x86; ARM64; ARM @@ -75,21 +75,6 @@ true - - Exe - AnyCPU - true - true - - - - WinExe - AnyCPU - true - true - true - - diff --git a/src/Notepads.Package/Notepads.Package.wapproj b/src/Notepads.Package/Notepads.Package.wapproj index 123766b1d..3c5239cd0 100644 --- a/src/Notepads.Package/Notepads.Package.wapproj +++ b/src/Notepads.Package/Notepads.Package.wapproj @@ -36,14 +36,6 @@ Release ARM64 - - Debug - AnyCPU - - - Release - AnyCPU - $(MSBuildExtensionsPath)\Microsoft\DesktopBridge\ diff --git a/src/Notepads.Services/Notepads.Services.csproj b/src/Notepads.Services/Notepads.Services.csproj index 4763b9f13..eec5069ee 100644 --- a/src/Notepads.Services/Notepads.Services.csproj +++ b/src/Notepads.Services/Notepads.Services.csproj @@ -3,7 +3,7 @@ Debug - AnyCPU + x86 {29DCAA68-1B6B-4290-8C05-691F52645D55} winmdobj Properties @@ -18,25 +18,6 @@ {A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} false - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP - prompt - 4 - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP - prompt - 4 - x86 true diff --git a/src/Notepads.sln b/src/Notepads.sln index c3e7a615a..e2b7b03cb 100644 --- a/src/Notepads.sln +++ b/src/Notepads.sln @@ -23,20 +23,16 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Notepads.DesktopExtension", EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU Debug|ARM = Debug|ARM Debug|ARM64 = Debug|ARM64 Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU Release|ARM = Release|ARM Release|ARM64 = Release|ARM64 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {99274932-9E86-480C-8142-38525F80007D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {99274932-9E86-480C-8142-38525F80007D}.Debug|Any CPU.Build.0 = Debug|Any CPU {99274932-9E86-480C-8142-38525F80007D}.Debug|ARM.ActiveCfg = Debug|ARM {99274932-9E86-480C-8142-38525F80007D}.Debug|ARM.Build.0 = Debug|ARM {99274932-9E86-480C-8142-38525F80007D}.Debug|ARM64.ActiveCfg = Debug|ARM64 @@ -45,8 +41,6 @@ Global {99274932-9E86-480C-8142-38525F80007D}.Debug|x64.Build.0 = Debug|x64 {99274932-9E86-480C-8142-38525F80007D}.Debug|x86.ActiveCfg = Debug|x86 {99274932-9E86-480C-8142-38525F80007D}.Debug|x86.Build.0 = Debug|x86 - {99274932-9E86-480C-8142-38525F80007D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {99274932-9E86-480C-8142-38525F80007D}.Release|Any CPU.Build.0 = Release|Any CPU {99274932-9E86-480C-8142-38525F80007D}.Release|ARM.ActiveCfg = Release|ARM {99274932-9E86-480C-8142-38525F80007D}.Release|ARM.Build.0 = Release|ARM {99274932-9E86-480C-8142-38525F80007D}.Release|ARM64.ActiveCfg = Release|ARM64 @@ -55,8 +49,6 @@ Global {99274932-9E86-480C-8142-38525F80007D}.Release|x64.Build.0 = Release|x64 {99274932-9E86-480C-8142-38525F80007D}.Release|x86.ActiveCfg = Release|x86 {99274932-9E86-480C-8142-38525F80007D}.Release|x86.Build.0 = Release|x86 - {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|Any CPU.Build.0 = Debug|Any CPU {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|ARM.ActiveCfg = Debug|ARM {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|ARM.Build.0 = Debug|ARM {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|ARM64.ActiveCfg = Debug|ARM64 @@ -65,8 +57,6 @@ Global {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|x64.Build.0 = Debug|x64 {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|x86.ActiveCfg = Debug|x86 {7AA5E631-B663-420E-A08F-002CD81DF855}.Debug|x86.Build.0 = Debug|x86 - {7AA5E631-B663-420E-A08F-002CD81DF855}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7AA5E631-B663-420E-A08F-002CD81DF855}.Release|Any CPU.Build.0 = Release|Any CPU {7AA5E631-B663-420E-A08F-002CD81DF855}.Release|ARM.ActiveCfg = Release|ARM {7AA5E631-B663-420E-A08F-002CD81DF855}.Release|ARM.Build.0 = Release|ARM {7AA5E631-B663-420E-A08F-002CD81DF855}.Release|ARM64.ActiveCfg = Release|ARM64 @@ -75,8 +65,6 @@ Global {7AA5E631-B663-420E-A08F-002CD81DF855}.Release|x64.Build.0 = Release|x64 {7AA5E631-B663-420E-A08F-002CD81DF855}.Release|x86.ActiveCfg = Release|x86 {7AA5E631-B663-420E-A08F-002CD81DF855}.Release|x86.Build.0 = Release|x86 - {29DCAA68-1B6B-4290-8C05-691F52645D55}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {29DCAA68-1B6B-4290-8C05-691F52645D55}.Debug|Any CPU.Build.0 = Debug|Any CPU {29DCAA68-1B6B-4290-8C05-691F52645D55}.Debug|ARM.ActiveCfg = Debug|ARM {29DCAA68-1B6B-4290-8C05-691F52645D55}.Debug|ARM.Build.0 = Debug|ARM {29DCAA68-1B6B-4290-8C05-691F52645D55}.Debug|ARM64.ActiveCfg = Debug|ARM64 @@ -85,8 +73,6 @@ Global {29DCAA68-1B6B-4290-8C05-691F52645D55}.Debug|x64.Build.0 = Debug|x64 {29DCAA68-1B6B-4290-8C05-691F52645D55}.Debug|x86.ActiveCfg = Debug|x86 {29DCAA68-1B6B-4290-8C05-691F52645D55}.Debug|x86.Build.0 = Debug|x86 - {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|Any CPU.ActiveCfg = Release|Any CPU - {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|Any CPU.Build.0 = Release|Any CPU {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|ARM.ActiveCfg = Release|ARM {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|ARM.Build.0 = Release|ARM {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|ARM64.ActiveCfg = Release|ARM64 @@ -95,9 +81,6 @@ Global {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|x64.Build.0 = Release|x64 {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|x86.ActiveCfg = Release|x86 {29DCAA68-1B6B-4290-8C05-691F52645D55}.Release|x86.Build.0 = Release|x86 - {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|Any CPU.Deploy.0 = Debug|Any CPU {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|ARM.ActiveCfg = Debug|ARM {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|ARM.Build.0 = Debug|ARM {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|ARM.Deploy.0 = Debug|ARM @@ -110,9 +93,6 @@ Global {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|x86.ActiveCfg = Debug|x86 {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|x86.Build.0 = Debug|x86 {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|x86.Deploy.0 = Debug|x86 - {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|Any CPU.Build.0 = Release|Any CPU - {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|Any CPU.Deploy.0 = Release|Any CPU {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|ARM.ActiveCfg = Release|ARM {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|ARM.Build.0 = Release|ARM {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|ARM.Deploy.0 = Release|ARM @@ -125,8 +105,6 @@ Global {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|x86.ActiveCfg = Release|x86 {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|x86.Build.0 = Release|x86 {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|x86.Deploy.0 = Release|x86 - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|Any CPU.Build.0 = Debug|Any CPU {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|ARM.ActiveCfg = Debug|ARM {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|ARM.Build.0 = Debug|ARM {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|ARM64.ActiveCfg = Debug|ARM64 @@ -135,8 +113,6 @@ Global {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|x64.Build.0 = Debug|x64 {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|x86.ActiveCfg = Debug|x86 {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|x86.Build.0 = Debug|x86 - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|Any CPU.Build.0 = Release|Any CPU {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|ARM.ActiveCfg = Release|ARM {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|ARM.Build.0 = Release|ARM {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|ARM64.ActiveCfg = Release|ARM64 diff --git a/src/Notepads/Notepads.csproj b/src/Notepads/Notepads.csproj index b4bb50aaa..116bb2ebd 100644 --- a/src/Notepads/Notepads.csproj +++ b/src/Notepads/Notepads.csproj @@ -3,7 +3,7 @@ Debug - AnyCPU + x86 {99274932-9E86-480C-8142-38525F80007D} AppContainerExe Properties @@ -119,29 +119,6 @@ true true - - true - bin\Debug\ - DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP;DISABLE_XAML_GENERATED_MAIN - ;2008 - full - AnyCPU - false - prompt - true - - - bin\Release\ - TRACE;NETFX_CORE;WINDOWS_UWP;DISABLE_XAML_GENERATED_MAIN - true - ;2008 - pdbonly - AnyCPU - false - prompt - true - true - PackageReference From b7b52150e7b85507530566e65021189e177aae05 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 8 Aug 2020 21:54:38 +0530 Subject: [PATCH 071/181] code-refinement. --- .../Notepads.DesktopExtension.csproj | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index 0064c589a..02b89f0d7 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -5,7 +5,7 @@ x86 net5.0 win10-x86; win10-x64; win10-arm64; win10-arm - AnyCPU; x64; x86; ARM64; ARM + x64; x86; ARM64; ARM Notepads32 Notepads Notepads @@ -19,14 +19,12 @@ Exe x64 true - true WinExe x64 true - true true @@ -34,14 +32,12 @@ Exe x86 true - true WinExe x86 true - true true @@ -49,14 +45,12 @@ Exe ARM64 true - true WinExe ARM64 true - true true @@ -64,14 +58,12 @@ Exe ARM true - true WinExe ARM true - true true From 2bee1948b03ddca0a6ef55e87750fe6163c8fc6c Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sun, 9 Aug 2020 11:20:22 +0530 Subject: [PATCH 072/181] code-refinement. --- .../Notepads.DesktopExtension.csproj | 2 +- src/Notepads.DesktopExtension/Program.cs | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index 02b89f0d7..7bf24e1e1 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -12,7 +12,7 @@ Copyright © 2020 Jackie Liu Notepads Jackie Liu - Notepads + Desktop Extension to allow users modifying system files with Notepads diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs index b39783791..045ae9f07 100644 --- a/src/Notepads.DesktopExtension/Program.cs +++ b/src/Notepads.DesktopExtension/Program.cs @@ -9,6 +9,7 @@ using System.Reflection; using System.Security.Principal; using System.Threading; + using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.AppService; using Windows.Foundation.Collections; @@ -35,6 +36,11 @@ static class Program /// static void Main(string[] args) { +#if DEBUG + AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; + TaskScheduler.UnobservedTaskException += OnUnobservedException; +#endif + if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) { if (!IsFirstInstance(AdminExtensionMutexName)) return; @@ -236,5 +242,17 @@ private static void PrintDebugMessage(string message, int waitAfterPrintingTime Thread.Sleep(waitAfterPrintingTime); #endif } + + private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) + { + // TODO: Log/Track Unhandled exception + } + + private static void OnUnobservedException(object sender, UnobservedTaskExceptionEventArgs e) + { + // TODO: Log/Track Unobserved exception + + e.SetObserved(); + } } } From 22882d60bb38de5343bf852b4ebc65443693f064 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sun, 9 Aug 2020 22:39:51 +0530 Subject: [PATCH 073/181] fixed instance handling. --- src/Notepads.DesktopExtension/Program.cs | 8 +------- src/Notepads/Program.cs | 1 - 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs index 045ae9f07..690335a47 100644 --- a/src/Notepads.DesktopExtension/Program.cs +++ b/src/Notepads.DesktopExtension/Program.cs @@ -95,14 +95,8 @@ private static bool IsFirstInstance(string mutexName) { var instanceHandlerMutex = new Mutex(true, mutexName, out var isFirstInstance); - if (isFirstInstance) + if (!isFirstInstance) { - instanceHandlerMutex.ReleaseMutex(); - } - else - { - instanceHandlerMutex.Close(); - PrintDebugMessage("Closing this instance as another instance is already running.", 5000); } diff --git a/src/Notepads/Program.cs b/src/Notepads/Program.cs index cbe0c8a9f..7d8fd84f5 100644 --- a/src/Notepads/Program.cs +++ b/src/Notepads/Program.cs @@ -38,7 +38,6 @@ static void Main(string[] args) { IsPrimaryInstance = true; ApplicationSettingsStore.Write(SettingsKey.ActiveInstanceIdStr, null); - instanceHandlerMutex.ReleaseMutex(); } else { From b07af34115301111451a084664035ba3b8523bcd Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Mon, 17 Aug 2020 22:31:13 +0530 Subject: [PATCH 074/181] Implemented crash-analytics for desktop extension. --- .../Notepads.DesktopExtension.csproj | 5 +- src/Notepads.DesktopExtension/Program.cs | 121 +++++++++++++----- .../DesktopExtensionConnectionService.cs | 16 +-- src/Notepads/App.xaml.cs | 7 +- .../Services/DesktopExtensionService.cs | 5 +- src/Notepads/Settings/SettingsKey.cs | 14 +- 6 files changed, 113 insertions(+), 55 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index 7bf24e1e1..c05b2deed 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -1,9 +1,10 @@ - + Debug x86 net5.0 + true win10-x86; win10-x64; win10-arm64; win10-arm x64; x86; ARM64; ARM Notepads32 @@ -72,6 +73,8 @@ + + diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs index 690335a47..b22ab23e6 100644 --- a/src/Notepads.DesktopExtension/Program.cs +++ b/src/Notepads.DesktopExtension/Program.cs @@ -1,26 +1,27 @@ namespace Notepads.DesktopExtension { + using Microsoft.AppCenter; + using Microsoft.AppCenter.Analytics; + using Microsoft.AppCenter.Crashes; using Notepads.Settings; using System; + using System.Collections.Generic; using System.Diagnostics; + using System.Globalization; using System.IO; using System.IO.MemoryMappedFiles; using System.IO.Pipes; - using System.Reflection; + using System.Linq; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; + using System.Windows.Forms; using Windows.ApplicationModel; using Windows.ApplicationModel.AppService; using Windows.Foundation.Collections; using Windows.Storage; - - public enum CommandArgs - { - RegisterExtension, - CreateElevetedExtension, - ExitApp - } + using Windows.System; + using Windows.System.UserProfile; static class Program { @@ -29,17 +30,14 @@ static class Program private static readonly int sessionId = Process.GetCurrentProcess().SessionId; private static AppServiceConnection connection = null; - private static AutoResetEvent appServiceExit; /// /// The main entry point for the application. /// static void Main(string[] args) { -#if DEBUG AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; TaskScheduler.UnobservedTaskException += OnUnobservedException; -#endif if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) { @@ -53,8 +51,10 @@ static void Main(string[] args) if (args.Length > 2 && args[2] == "/admin") CreateElevetedExtension(); } - appServiceExit = new AutoResetEvent(false); - appServiceExit.WaitOne(); + var services = new Type[] { typeof(Crashes), typeof(Analytics) }; + AppCenter.Start(SettingsKey.AppCenterSecret, services); + + Application.Run(); } private static async void InitializeAppServiceConnection() @@ -74,10 +74,10 @@ private static async void InitializeAppServiceConnection() if (status != AppServiceConnectionStatus.Success) { - appServiceExit.Set(); + Application.Exit(); } - var message = new ValueSet { { SettingsKey.InteropCommandLabel, CommandArgs.RegisterExtension.ToString() } }; + var message = new ValueSet { { SettingsKey.InteropCommandLabel, SettingsKey.RegisterExtensionCommandStr } }; await connection.SendMessageAsync(message); PrintDebugMessage("Successfully created App Service."); @@ -106,7 +106,7 @@ private static bool IsFirstInstance(string mutexName) private static void Connection_ServiceClosed(AppServiceConnection sender, AppServiceClosedEventArgs args) { // connection to the UWP lost, so we shut down the desktop process - appServiceExit.Set(); + Application.Exit(); } private static void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) @@ -116,14 +116,14 @@ private static void Connection_RequestReceived(AppServiceConnection sender, AppS var messageDeferral = args.GetDeferral(); var message = args.Request.Message; - if (!message.ContainsKey(SettingsKey.InteropCommandLabel) || !Enum.TryParse((string)message[SettingsKey.InteropCommandLabel], out var command)) return; + if (!message.ContainsKey(SettingsKey.InteropCommandLabel) || !(message[SettingsKey.InteropCommandLabel] is string command)) return; switch (command) { - case CommandArgs.CreateElevetedExtension: + case SettingsKey.CreateElevetedExtensionCommandStr: CreateElevetedExtension(); break; - case CommandArgs.ExitApp: - appServiceExit.Set(); + case SettingsKey.ExitAppCommandStr: + Application.Exit(); break; } @@ -132,20 +132,15 @@ private static void Connection_RequestReceived(AppServiceConnection sender, AppS private static async void CreateElevetedExtension() { - var message = new ValueSet { { SettingsKey.InteropCommandLabel, CommandArgs.CreateElevetedExtension.ToString() } }; + var message = new ValueSet { { SettingsKey.InteropCommandLabel, SettingsKey.CreateElevetedExtensionCommandStr } }; try { - string result = Assembly.GetExecutingAssembly().Location; - int index = result.LastIndexOf("\\"); - string rootPath = $"{result.Substring(0, index)}\\..\\"; - string aliasPath = rootPath + @"\Notepads.DesktopExtension\Notepads32.exe"; - ProcessStartInfo info = new ProcessStartInfo { Verb = "runas", UseShellExecute = true, - FileName = aliasPath + FileName = Application.ExecutablePath }; var process = Process.Start(info); @@ -153,12 +148,21 @@ private static async void CreateElevetedExtension() message.Add(SettingsKey.InteropCommandAdminCreatedLabel, true); PrintDebugMessage("Adminstrator Extension has been launched."); + Analytics.TrackEvent("OnAdminstratorPrivilageGranted", new Dictionary { { "Accepted", true.ToString() } }); } - catch + catch (Exception ex) { message.Add(SettingsKey.InteropCommandAdminCreatedLabel, false); PrintDebugMessage("User canceled launching of Adminstrator Extension."); + Analytics.TrackEvent("OnAdminstratorPrivilageDenied", + new Dictionary { + { "Denied", true.ToString() }, + { "Message", ex.Message }, + { "Exception", ex.ToString() }, + { "InnerException", ex.InnerException?.ToString() }, + { "InnerExceptionMessage", ex.InnerException?.Message } + }); } finally { @@ -202,9 +206,17 @@ private static async void SaveFileFromPipeData() PrintDebugMessage($"Successfully wrote to \"{filePath}\"."); } - catch + catch (Exception ex) { PrintDebugMessage($"Failed to write to \"{filePath}\"."); + Analytics.TrackEvent("OnWriteToSystemFileRequested", + new Dictionary { + { "Result", result }, + { "Message", ex.Message }, + { "Exception", ex.ToString() }, + { "InnerException", ex.InnerException?.ToString() }, + { "InnerExceptionMessage", ex.InnerException?.Message } + }); } finally { @@ -212,6 +224,10 @@ private static async void SaveFileFromPipeData() pipeWriter.Flush(); PrintDebugMessage("Waiting on uwp app to send data."); + if ("Success".Equals(result)) + { + Analytics.TrackEvent("OnWriteToSystemFileRequested", new Dictionary { { "Result", result } }); + } } } @@ -239,13 +255,56 @@ private static void PrintDebugMessage(string message, int waitAfterPrintingTime private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) { - // TODO: Log/Track Unhandled exception + var exception = e.ExceptionObject as Exception; + + var diagnosticInfo = new Dictionary() + { + { "Message", exception?.Message }, + { "Exception", exception?.ToString() }, + { "Culture", (GlobalizationPreferences.Languages.Count > 0 ? new CultureInfo(GlobalizationPreferences.Languages.First()) : null).EnglishName }, + { "AvailableMemory", ((float)MemoryManager.AppMemoryUsageLimit / 1024 / 1024).ToString("F0") }, + { "FirstUseTimeUTC", Process.GetCurrentProcess().StartTime.ToUniversalTime().ToString("MM/dd/yyyy HH:mm:ss") }, + { "OSArchitecture", Package.Current.Id.Architecture.ToString() }, + { "OSVersion", Environment.OSVersion.Version.ToString() }, + { "IsElevated", new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator).ToString() } + }; + + var attachment = ErrorAttachmentLog.AttachmentWithText( + $"Exception: {exception}, " + + $"Message: {exception?.Message}, " + + $"InnerException: {exception?.InnerException}, " + + $"InnerExceptionMessage: {exception?.InnerException?.Message}", + "UnhandledException"); + + Analytics.TrackEvent("OnUnhandledException", diagnosticInfo); + Crashes.TrackError(exception, diagnosticInfo, attachment); + + // handle it manually. + if (e.IsTerminating) Application.Restart(); } private static void OnUnobservedException(object sender, UnobservedTaskExceptionEventArgs e) { - // TODO: Log/Track Unobserved exception + var diagnosticInfo = new Dictionary() + { + { "Message", e.Exception?.Message }, + { "Exception", e.Exception?.ToString() }, + { "InnerException", e.Exception?.InnerException?.ToString() }, + { "InnerExceptionMessage", e.Exception?.InnerException?.Message } + }; + + var attachment = ErrorAttachmentLog.AttachmentWithText( + $"Exception: {e.Exception}, " + + $"Message: {e.Exception?.Message}, " + + $"InnerException: {e.Exception?.InnerException}, " + + $"InnerExceptionMessage: {e.Exception?.InnerException?.Message}, " + + $"IsDesktopExtension: {true}", + "UnobservedException"); + + Analytics.TrackEvent("OnUnobservedException", diagnosticInfo); + Crashes.TrackError(e.Exception, diagnosticInfo, attachment); + // suppress and handle it manually. e.SetObserved(); } } diff --git a/src/Notepads.Services/DesktopExtensionConnectionService.cs b/src/Notepads.Services/DesktopExtensionConnectionService.cs index 2c38c0fc8..85ec7e48f 100644 --- a/src/Notepads.Services/DesktopExtensionConnectionService.cs +++ b/src/Notepads.Services/DesktopExtensionConnectionService.cs @@ -9,13 +9,6 @@ using Windows.ApplicationModel.Background; using Windows.Foundation.Collections; - public enum CommandArgs - { - RegisterExtension, - CreateElevetedExtension, - ExitApp - } - public sealed class DesktopExtensionConnectionService : IBackgroundTask { private BackgroundTaskDeferral backgroundTaskDeferral; @@ -53,12 +46,11 @@ private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequ var message = args.Request.Message; if (!message.ContainsKey(SettingsKey.InteropCommandLabel) || - !Enum.TryParse(typeof(CommandArgs), (string)message[SettingsKey.InteropCommandLabel], out var result)) return; - var command = (CommandArgs)result; + !(message[SettingsKey.InteropCommandLabel] is string command)) return; switch (command) { - case CommandArgs.RegisterExtension: + case SettingsKey.RegisterExtensionCommandStr: appServiceConnections.Remove(appServiceConnection); if (extensionAppServiceConnection == null) { @@ -69,7 +61,7 @@ private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequ this.backgroundTaskDeferral.Complete(); } break; - case CommandArgs.CreateElevetedExtension: + case SettingsKey.CreateElevetedExtensionCommandStr: if (appServiceConnection == extensionAppServiceConnection) { Parallel.ForEach(appServiceConnections, async (serviceConnection) => @@ -123,7 +115,7 @@ private async void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTask appServiceConnections.Remove(serviceConnection); if (appServiceConnections.Count == 0 && extensionAppServiceConnection != null) { - var message = new ValueSet { { SettingsKey.InteropCommandLabel, CommandArgs.ExitApp.ToString() } }; + var message = new ValueSet { { SettingsKey.InteropCommandLabel, SettingsKey.ExitAppCommandStr } }; await extensionAppServiceConnection.SendMessageAsync(message); } } diff --git a/src/Notepads/App.xaml.cs b/src/Notepads/App.xaml.cs index e5cf3fc17..8dda9ff67 100644 --- a/src/Notepads/App.xaml.cs +++ b/src/Notepads/App.xaml.cs @@ -30,8 +30,6 @@ sealed partial class App : Application public static bool IsPrimaryInstance = false; public static bool IsGameBarWidget = false; - private const string AppCenterSecret = null; - /// /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). @@ -42,7 +40,7 @@ public App() TaskScheduler.UnobservedTaskException += OnUnobservedException; var services = new Type[] { typeof(Crashes), typeof(Analytics) }; - AppCenter.Start(AppCenterSecret, services); + AppCenter.Start(SettingsKey.AppCenterSecret, services); LoggingService.LogInfo($"[{nameof(App)}] Started: Instance = {Id} IsPrimaryInstance: {IsPrimaryInstance} IsGameBarWidget: {IsGameBarWidget}."); @@ -219,7 +217,8 @@ private static void OnUnhandledException(object sender, Windows.UI.Xaml.Unhandle $"Exception: {e.Exception}, " + $"Message: {e.Message}, " + $"InnerException: {e.Exception?.InnerException}, " + - $"InnerExceptionMessage: {e.Exception?.InnerException?.Message}", + $"InnerExceptionMessage: {e.Exception?.InnerException?.Message}, " + + $"IsDesktopExtension: {false}", "UnhandledException"); Analytics.TrackEvent("OnUnhandledException", diagnosticInfo); diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index 1fa51cfad..21432a13c 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -49,8 +49,7 @@ private static async void InteropServiceConnection_RequestReceived(AppServiceCon { var message = args.Request.Message; if (!message.ContainsKey(SettingsKey.InteropCommandLabel) || - !Enum.TryParse(typeof(CommandArgs), (string)message[SettingsKey.InteropCommandLabel], out var commandObj) || - (CommandArgs)commandObj != CommandArgs.CreateElevetedExtension) return; + SettingsKey.CreateElevetedExtensionCommandStr.Equals(message[SettingsKey.InteropCommandLabel])) return; await CoreApplication.MainView.CoreWindow.Dispatcher.CallOnUIThreadAsync(() => { @@ -141,7 +140,7 @@ public static async Task CreateElevetedExtension() { if (InteropServiceConnection == null) await Initialize(); - var message = new ValueSet { { SettingsKey.InteropCommandLabel, CommandArgs.CreateElevetedExtension.ToString() } }; + var message = new ValueSet { { SettingsKey.InteropCommandLabel, SettingsKey.CreateElevetedExtensionCommandStr } }; var response = await InteropServiceConnection.SendMessageAsync(message); message = response.Message; diff --git a/src/Notepads/Settings/SettingsKey.cs b/src/Notepads/Settings/SettingsKey.cs index abf5791ff..664b83f28 100644 --- a/src/Notepads/Settings/SettingsKey.cs +++ b/src/Notepads/Settings/SettingsKey.cs @@ -7,10 +7,6 @@ internal static class SettingsKey internal static string IsJumpListOutOfDateBool = "IsJumpListOutOfDateBool"; internal static string ActiveInstanceIdStr = "ActiveInstanceIdStr"; internal static string AlwaysOpenNewWindowBool = "AlwaysOpenNewWindowBool"; - internal static string PackageSidStr = "PackageSidStr"; - internal static string InteropCommandLabel = "Command"; - internal static string InteropCommandFailedLabel = "Failed"; - internal static string InteropCommandAdminCreatedLabel = "AdminCreated"; // Theme related internal static string RequestedThemeStr = "RequestedThemeStr"; @@ -38,5 +34,15 @@ internal static class SettingsKey internal static string EditorHighlightMisspelledWordsBool = "EditorHighlightMisspelledWordsBool"; internal static string EditorDefaultDisplayLineNumbersBool = "EditorDefaultDisplayLineNumbersBool"; internal static string EditorEnableSmartCopyBool = "EditorEnableSmartCopyBool"; + + // Interop related + internal static string PackageSidStr = "PackageSidStr"; + internal static string InteropCommandLabel = "Command"; + internal static string InteropCommandFailedLabel = "Failed"; + internal static string InteropCommandAdminCreatedLabel = "AdminCreated"; + internal const string RegisterExtensionCommandStr = "RegisterExtension"; + internal const string CreateElevetedExtensionCommandStr = "CreateElevetedExtension"; + internal const string ExitAppCommandStr = "ExitApp"; + internal const string AppCenterSecret = null; } } \ No newline at end of file From f92e508ae5755be771f6fbb83d55b2c99c2a08e6 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Tue, 25 Aug 2020 12:46:16 +0530 Subject: [PATCH 075/181] Added better error handling. --- src/Notepads.DesktopExtension/Program.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs index b22ab23e6..1dd903274 100644 --- a/src/Notepads.DesktopExtension/Program.cs +++ b/src/Notepads.DesktopExtension/Program.cs @@ -37,6 +37,7 @@ static class Program static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; + Application.ThreadException += (sender, args) => OnUnhandledException(sender, new UnhandledExceptionEventArgs(args.Exception, true)); TaskScheduler.UnobservedTaskException += OnUnobservedException; if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) @@ -199,7 +200,7 @@ private static async void SaveFileFromPipeData() { var data = reader.ReadBytes(dataArrayLength); - await PathIO.WriteBytesAsync(filePath, data); + await File.WriteAllBytesAsync(filePath, data); } result = "Success"; From 58091bd0c314b42d993a80577298cffd6fb8b3b0 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 18 Sep 2020 13:31:15 +0530 Subject: [PATCH 076/181] Code refactor. --- .../Notepads.DesktopExtension.csproj | 8 ++++---- src/Notepads/Notepads.csproj | 6 +++--- src/Notepads/Services/DesktopExtensionService.cs | 15 +++++++++++---- 3 files changed, 18 insertions(+), 11 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index c05b2deed..b0530e0d6 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -1,9 +1,9 @@ - + Debug x86 - net5.0 + net5.0-windows true win10-x86; win10-x64; win10-arm64; win10-arm x64; x86; ARM64; ARM @@ -73,8 +73,8 @@ - - + + diff --git a/src/Notepads/Notepads.csproj b/src/Notepads/Notepads.csproj index 116bb2ebd..04652eb82 100644 --- a/src/Notepads/Notepads.csproj +++ b/src/Notepads/Notepads.csproj @@ -643,16 +643,16 @@ 1.6.3 - 3.4.0 + 3.4.1 - 3.4.0 + 3.4.1 6.2.10 - 6.1.0 + 6.1.1 4.7.0 diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index 21432a13c..17f3e07d6 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -12,6 +12,7 @@ using Windows.ApplicationModel.Core; using Windows.ApplicationModel.Resources; using Windows.Foundation.Collections; + using Windows.Foundation.Metadata; using Windows.Security.Authentication.Web; using Windows.UI.ViewManagement; using Windows.UI.Xaml; @@ -29,8 +30,10 @@ public static class DesktopExtensionService public static AppServiceConnection InteropServiceConnection = null; private static readonly ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView(); - public static async Task Initialize() + public static async Task Initialize() { + if (!ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0)) return false; + InteropServiceConnection = new AppServiceConnection() { AppServiceName = "DesktopExtensionServiceConnection", @@ -41,8 +44,12 @@ public static async Task Initialize() InteropServiceConnection.ServiceClosed += InteropServiceConnection_ServiceClosed; AppServiceConnectionStatus status = await InteropServiceConnection.OpenAsync(); - if (status != AppServiceConnectionStatus.Success && !await ApplicationView.GetForCurrentView().TryConsolidateAsync()) + if (status != AppServiceConnectionStatus.Success && !await ApplicationView.GetForCurrentView().TryConsolidateAsync()) + { Application.Current.Exit(); + } + + return true; } private static async void InteropServiceConnection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) @@ -79,7 +86,7 @@ private static void InteropServiceConnection_ServiceClosed(AppServiceConnection /// Data to write. public static async Task SaveFileAsAdmin(string filePath, byte[] data) { - if (InteropServiceConnection == null) await Initialize(); + if (InteropServiceConnection == null && !(await Initialize())) return; using (var adminConnectionPipeStream = new NamedPipeServerStream($"Local\\{Package.Current.Id.FamilyName}\\AdminWritePipe", PipeDirection.InOut, 254, PipeTransmissionMode.Message, PipeOptions.Asynchronous)) @@ -138,7 +145,7 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) /// public static async Task CreateElevetedExtension() { - if (InteropServiceConnection == null) await Initialize(); + if (InteropServiceConnection == null && !(await Initialize())) return; var message = new ValueSet { { SettingsKey.InteropCommandLabel, SettingsKey.CreateElevetedExtensionCommandStr } }; var response = await InteropServiceConnection.SendMessageAsync(message); From 1352a8076dd9e69e880b098d101c9856121e7b36 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Wed, 23 Sep 2020 11:03:11 +0530 Subject: [PATCH 077/181] Code refactor. --- src/Notepads.DesktopExtension/Program.cs | 15 +++-- .../Services/DesktopExtensionService.cs | 13 ++-- src/Notepads/Settings/SettingsKey.cs | 63 ++++++++++--------- src/Notepads/Utilities/FileSystemUtility.cs | 2 +- 4 files changed, 48 insertions(+), 45 deletions(-) diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs index 1dd903274..377942895 100644 --- a/src/Notepads.DesktopExtension/Program.cs +++ b/src/Notepads.DesktopExtension/Program.cs @@ -29,6 +29,8 @@ static class Program private const string AdminExtensionMutexName = "AdminExtensionMutexName"; private static readonly int sessionId = Process.GetCurrentProcess().SessionId; + private static readonly string packageSID = ReadSettingsKey(SettingsKey.PackageSidStr) as string; + private static AppServiceConnection connection = null; /// @@ -173,8 +175,10 @@ private static async void CreateElevetedExtension() private static async void SaveFileFromPipeData() { + var result = "Failed"; + using var clientStream = new NamedPipeClientStream(".", - $"Sessions\\{sessionId}\\AppContainerNamedObjects\\{ReadSettingsKey(SettingsKey.PackageSidStr)}\\{Package.Current.Id.FamilyName}\\AdminWritePipe", + $"Sessions\\{sessionId}\\AppContainerNamedObjects\\{packageSID}\\{Package.Current.Id.FamilyName}\\{SettingsKey.AdminPipeConnectionNameStr}", PipeDirection.InOut, PipeOptions.Asynchronous); // Wait for uwp app to send request to write to file. @@ -187,14 +191,13 @@ private static async void SaveFileFromPipeData() var pipeWriter = new StreamWriter(clientStream); var writeData = pipeReader.ReadLine().Split(new string[] { "?:" }, StringSplitOptions.None); + var filePath = writeData[0]; + var memoryMapName = $"AppContainerNamedObjects\\{packageSID}\\{writeData[1]}"; - var memoryMapName = writeData[0]; - var filePath = writeData[1]; - int.TryParse(writeData[2], out int dataArrayLength); - - var result = "Failed"; try { + if (!int.TryParse(writeData[2], out int dataArrayLength)) throw new Exception("Failed to read piped data"); + // Open the memory-mapped file and read data from it. using (var reader = new BinaryReader(MemoryMappedFile.OpenExisting(memoryMapName).CreateViewStream())) { diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index 17f3e07d6..a41a3887c 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -6,6 +6,7 @@ using System.IO; using System.IO.MemoryMappedFiles; using System.IO.Pipes; + using System.Security.Principal; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.AppService; @@ -13,7 +14,6 @@ using Windows.ApplicationModel.Resources; using Windows.Foundation.Collections; using Windows.Foundation.Metadata; - using Windows.Security.Authentication.Web; using Windows.UI.ViewManagement; using Windows.UI.Xaml; @@ -28,11 +28,13 @@ public AdminstratorAccessException(string message, Exception innerException) : b public static class DesktopExtensionService { public static AppServiceConnection InteropServiceConnection = null; + public static readonly bool ShouldUseDesktopExtension = ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0) && + !new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); private static readonly ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView(); public static async Task Initialize() { - if (!ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0)) return false; + if (!ShouldUseDesktopExtension) return false; InteropServiceConnection = new AppServiceConnection() { @@ -88,7 +90,7 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) { if (InteropServiceConnection == null && !(await Initialize())) return; - using (var adminConnectionPipeStream = new NamedPipeServerStream($"Local\\{Package.Current.Id.FamilyName}\\AdminWritePipe", + using (var adminConnectionPipeStream = new NamedPipeServerStream($"Local\\{Package.Current.Id.FamilyName}\\{SettingsKey.AdminPipeConnectionNameStr}", PipeDirection.InOut, 254, PipeTransmissionMode.Message, PipeOptions.Asynchronous)) { // Wait for 250 ms for desktop extension to accept request. @@ -113,10 +115,7 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) writer.Flush(); } - pipeWriter.WriteLine(string.Join("?:", - $"AppContainerNamedObjects\\{ WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host.ToUpper() }\\{ mapName }", - filePath, - data.Length)); + pipeWriter.WriteLine(string.Join("?:", filePath, mapName, data.Length)); pipeWriter.Flush(); // Wait for desktop extension to send response. diff --git a/src/Notepads/Settings/SettingsKey.cs b/src/Notepads/Settings/SettingsKey.cs index 664b83f28..c7953d948 100644 --- a/src/Notepads/Settings/SettingsKey.cs +++ b/src/Notepads/Settings/SettingsKey.cs @@ -3,43 +3,44 @@ internal static class SettingsKey { // App related - internal static string AppVersionStr = "AppVersionStr"; - internal static string IsJumpListOutOfDateBool = "IsJumpListOutOfDateBool"; - internal static string ActiveInstanceIdStr = "ActiveInstanceIdStr"; - internal static string AlwaysOpenNewWindowBool = "AlwaysOpenNewWindowBool"; + internal const string AppVersionStr = "AppVersionStr"; + internal const string IsJumpListOutOfDateBool = "IsJumpListOutOfDateBool"; + internal const string ActiveInstanceIdStr = "ActiveInstanceIdStr"; + internal const string AlwaysOpenNewWindowBool = "AlwaysOpenNewWindowBool"; // Theme related - internal static string RequestedThemeStr = "RequestedThemeStr"; - internal static string AppBackgroundTintOpacityDouble = "AppBackgroundTintOpacityDouble"; - internal static string AppAccentColorHexStr = "AppAccentColorHexStr"; - internal static string CustomAccentColorHexStr = "CustomAccentColorHexStr"; - internal static string UseWindowsAccentColorBool = "UseWindowsAccentColorBool"; + internal const string RequestedThemeStr = "RequestedThemeStr"; + internal const string AppBackgroundTintOpacityDouble = "AppBackgroundTintOpacityDouble"; + internal const string AppAccentColorHexStr = "AppAccentColorHexStr"; + internal const string CustomAccentColorHexStr = "CustomAccentColorHexStr"; + internal const string UseWindowsAccentColorBool = "UseWindowsAccentColorBool"; // Editor related - internal static string EditorFontFamilyStr = "EditorFontFamilyStr"; - internal static string EditorFontSizeInt = "EditorFontSizeInt"; - internal static string EditorFontStyleStr = "EditorFontStyleStr"; - internal static string EditorFontWeightUshort = "EditorFontWeightUshort"; - internal static string EditorDefaultTextWrappingStr = "EditorDefaultTextWrappingStr"; - internal static string EditorDefaultLineHighlighterViewStateBool = "EditorDefaultLineHighlighterViewStateBool"; - internal static string EditorDefaultLineEndingStr = "EditorDefaultLineEndingStr"; - internal static string EditorDefaultEncodingCodePageInt = "EditorDefaultEncodingCodePageInt"; - internal static string EditorDefaultDecodingCodePageInt = "EditorDefaultDecodingCodePageInt"; - internal static string EditorDefaultUtf8EncoderShouldEmitByteOrderMarkBool = "EditorDefaultUtf8EncoderShouldEmitByteOrderMarkBool"; - internal static string EditorDefaultTabIndentsInt = "EditorDefaultTabIndentsInt"; - internal static string EditorDefaultSearchEngineStr = "EditorDefaultSearchUrlStr"; - internal static string EditorCustomMadeSearchUrlStr = "EditorCustomMadeSearchUrlStr"; - internal static string EditorShowStatusBarBool = "EditorShowStatusBarBool"; - internal static string EditorEnableSessionBackupAndRestoreBool = "EditorEnableSessionBackupAndRestoreBool"; - internal static string EditorHighlightMisspelledWordsBool = "EditorHighlightMisspelledWordsBool"; - internal static string EditorDefaultDisplayLineNumbersBool = "EditorDefaultDisplayLineNumbersBool"; - internal static string EditorEnableSmartCopyBool = "EditorEnableSmartCopyBool"; + internal const string EditorFontFamilyStr = "EditorFontFamilyStr"; + internal const string EditorFontSizeInt = "EditorFontSizeInt"; + internal const string EditorFontStyleStr = "EditorFontStyleStr"; + internal const string EditorFontWeightUshort = "EditorFontWeightUshort"; + internal const string EditorDefaultTextWrappingStr = "EditorDefaultTextWrappingStr"; + internal const string EditorDefaultLineHighlighterViewStateBool = "EditorDefaultLineHighlighterViewStateBool"; + internal const string EditorDefaultLineEndingStr = "EditorDefaultLineEndingStr"; + internal const string EditorDefaultEncodingCodePageInt = "EditorDefaultEncodingCodePageInt"; + internal const string EditorDefaultDecodingCodePageInt = "EditorDefaultDecodingCodePageInt"; + internal const string EditorDefaultUtf8EncoderShouldEmitByteOrderMarkBool = "EditorDefaultUtf8EncoderShouldEmitByteOrderMarkBool"; + internal const string EditorDefaultTabIndentsInt = "EditorDefaultTabIndentsInt"; + internal const string EditorDefaultSearchEngineStr = "EditorDefaultSearchUrlStr"; + internal const string EditorCustomMadeSearchUrlStr = "EditorCustomMadeSearchUrlStr"; + internal const string EditorShowStatusBarBool = "EditorShowStatusBarBool"; + internal const string EditorEnableSessionBackupAndRestoreBool = "EditorEnableSessionBackupAndRestoreBool"; + internal const string EditorHighlightMisspelledWordsBool = "EditorHighlightMisspelledWordsBool"; + internal const string EditorDefaultDisplayLineNumbersBool = "EditorDefaultDisplayLineNumbersBool"; + internal const string EditorEnableSmartCopyBool = "EditorEnableSmartCopyBool"; // Interop related - internal static string PackageSidStr = "PackageSidStr"; - internal static string InteropCommandLabel = "Command"; - internal static string InteropCommandFailedLabel = "Failed"; - internal static string InteropCommandAdminCreatedLabel = "AdminCreated"; + internal const string PackageSidStr = "PackageSidStr"; + internal const string AdminPipeConnectionNameStr = "NotepadsAdminWritePipe"; + internal const string InteropCommandLabel = "Command"; + internal const string InteropCommandFailedLabel = "Failed"; + internal const string InteropCommandAdminCreatedLabel = "AdminCreated"; internal const string RegisterExtensionCommandStr = "RegisterExtension"; internal const string CreateElevetedExtensionCommandStr = "CreateElevetedExtension"; internal const string ExitAppCommandStr = "ExitApp"; diff --git a/src/Notepads/Utilities/FileSystemUtility.cs b/src/Notepads/Utilities/FileSystemUtility.cs index 2ba69877f..1df85ae62 100644 --- a/src/Notepads/Utilities/FileSystemUtility.cs +++ b/src/Notepads/Utilities/FileSystemUtility.cs @@ -580,7 +580,7 @@ public static async Task WriteToFile(string text, Encoding encoding, StorageFile } catch (UnauthorizedAccessException ex) // Try to save as admin if fullTrust api is supported { - if (!ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0)) + if (!DesktopExtensionService.ShouldUseDesktopExtension) { throw ex; } From cd7c13312ab1ad746280b47e3bd8d716fb8c2e1d Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Wed, 23 Sep 2020 13:15:11 +0530 Subject: [PATCH 078/181] Code refactor. --- src/Notepads.DesktopExtension/Program.cs | 6 ++--- .../Services/DesktopExtensionService.cs | 22 ++++++++----------- 2 files changed, 12 insertions(+), 16 deletions(-) diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs index 377942895..5ef8c8c52 100644 --- a/src/Notepads.DesktopExtension/Program.cs +++ b/src/Notepads.DesktopExtension/Program.cs @@ -190,7 +190,7 @@ private static async void SaveFileFromPipeData() var pipeReader = new StreamReader(clientStream); var pipeWriter = new StreamWriter(clientStream); - var writeData = pipeReader.ReadLine().Split(new string[] { "?:" }, StringSplitOptions.None); + var writeData = (await pipeReader.ReadLineAsync()).Split(new string[] { "?:" }, StringSplitOptions.None); var filePath = writeData[0]; var memoryMapName = $"AppContainerNamedObjects\\{packageSID}\\{writeData[1]}"; @@ -224,8 +224,8 @@ private static async void SaveFileFromPipeData() } finally { - pipeWriter.WriteLine(result); - pipeWriter.Flush(); + await pipeWriter.WriteLineAsync(result); + await pipeWriter.FlushAsync(); PrintDebugMessage("Waiting on uwp app to send data."); if ("Success".Equals(result)) diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index a41a3887c..40bfd6f8e 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -115,22 +115,18 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) writer.Flush(); } - pipeWriter.WriteLine(string.Join("?:", filePath, mapName, data.Length)); - pipeWriter.Flush(); + await pipeWriter.WriteLineAsync(string.Join("?:", filePath, mapName, data.Length)); + await pipeWriter.FlushAsync(); // Wait for desktop extension to send response. - while (true) + if ("Success".Equals(await pipeReader.ReadLineAsync())) { - var result = pipeReader.ReadLine(); - if ("Success".Equals(result)) - { - return; - } - else if ("Failed".Equals(result)) - { - // Promt user to "Save As" if extension failed to save data. - throw new UnauthorizedAccessException(); - } + return; + } + else + { + // Promt user to "Save As" if extension failed to save data. + throw new UnauthorizedAccessException(); } } } From 1ed3342d35312ad451b36c1cbf814af247593995 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 12 Nov 2020 10:05:24 +0530 Subject: [PATCH 079/181] Updated app limitations list. --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 89666c360..cee0daff0 100644 --- a/README.md +++ b/README.md @@ -61,7 +61,6 @@ So here comes the “Notepads” 🎉 (s stands for Sets). ## Platform limitations (UWP): -* You won't be able to save files to system folders due to UWP restriction (windows, system32, etc.). * You cannot associate potentially harmful file types (.cmd, .bat etc.) with Notepads. * Notepads does not work well with large files; the file size limit is set to 1MB for now. I will add large file support later. From e60544a537fca1ff38b632fd4db9c967e42907eb Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 12 Nov 2020 19:13:00 +0530 Subject: [PATCH 080/181] Updated target framework to use winrt apis. --- .../Notepads.DesktopExtension.csproj | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj index b0530e0d6..822895ebc 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj @@ -3,9 +3,8 @@ Debug x86 - net5.0-windows + net5.0-windows10.0.19041.0 true - win10-x86; win10-x64; win10-arm64; win10-arm x64; x86; ARM64; ARM Notepads32 Notepads @@ -75,7 +74,6 @@ - From 3d705495a010bdfcb7bd0789b7926e9c7b7515b2 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Mon, 30 Nov 2020 22:55:33 +0530 Subject: [PATCH 081/181] Moved to Win32 from .NET for desktop extension to reuce deployment size. --- src/Notepads.DesktopExtension/AssemblyInfo.rc | 99 +++++ .../Notepads.DesktopExtension.csproj | 80 ----- .../Notepads.DesktopExtension.vcxproj | 150 ++++++++ .../Notepads.DesktopExtension.vcxproj.filters | 18 + src/Notepads.DesktopExtension/Program.cs | 315 ---------------- .../PropertySheet.props | 16 + src/Notepads.DesktopExtension/main.cpp | 339 ++++++++++++++++++ src/Notepads.DesktopExtension/packages.config | 4 + src/Notepads.DesktopExtension/pch.cpp | 1 + src/Notepads.DesktopExtension/pch.h | 11 + src/Notepads.DesktopExtension/resource.h | 14 + src/Notepads.Package/Notepads.Package.wapproj | 4 +- src/Notepads.sln | 34 +- .../Services/DesktopExtensionService.cs | 4 +- 14 files changed, 672 insertions(+), 417 deletions(-) create mode 100644 src/Notepads.DesktopExtension/AssemblyInfo.rc delete mode 100644 src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj create mode 100644 src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj create mode 100644 src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters delete mode 100644 src/Notepads.DesktopExtension/Program.cs create mode 100644 src/Notepads.DesktopExtension/PropertySheet.props create mode 100644 src/Notepads.DesktopExtension/main.cpp create mode 100644 src/Notepads.DesktopExtension/packages.config create mode 100644 src/Notepads.DesktopExtension/pch.cpp create mode 100644 src/Notepads.DesktopExtension/pch.h create mode 100644 src/Notepads.DesktopExtension/resource.h diff --git a/src/Notepads.DesktopExtension/AssemblyInfo.rc b/src/Notepads.DesktopExtension/AssemblyInfo.rc new file mode 100644 index 000000000..a49b38dfb --- /dev/null +++ b/src/Notepads.DesktopExtension/AssemblyInfo.rc @@ -0,0 +1,99 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (India) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENN) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_INDIA +#pragma code_page(1252) + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,0,0,0 + PRODUCTVERSION 1,0,0,0 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x40004L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "000004b0" + BEGIN + VALUE "FileDescription", "Notepads" + VALUE "FileVersion", "1.0.0.0" + VALUE "InternalName", "Notepads.DesktopExtension" + VALUE "LegalCopyright", "Copyright 2020 Jackie Liu" + VALUE "OriginalFilename", "Notepads.DesktopExtension" + VALUE "ProductName", "Notepads" + VALUE "ProductVersion", "1.0.0.0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x0, 1200 + END +END + +#endif // English (India) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj deleted file mode 100644 index 822895ebc..000000000 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.csproj +++ /dev/null @@ -1,80 +0,0 @@ - - - - Debug - x86 - net5.0-windows10.0.19041.0 - true - x64; x86; ARM64; ARM - Notepads32 - Notepads - Notepads - Copyright © 2020 Jackie Liu - Notepads - Jackie Liu - Desktop Extension to allow users modifying system files with Notepads - - - - Exe - x64 - true - - - - WinExe - x64 - true - true - - - - Exe - x86 - true - - - - WinExe - x86 - true - true - - - - Exe - ARM64 - true - - - - WinExe - ARM64 - true - true - - - - Exe - ARM - true - - - - WinExe - ARM - true - true - - - - - - - - - - - - - diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj new file mode 100644 index 000000000..6aa74fe5b --- /dev/null +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -0,0 +1,150 @@ + + + + + true + true + true + true + 15.0 + {0a3b698e-6add-4c9e-9741-08f8ae576b2e} + Win32Proj + Notepads_DesktopExtension + $(ProjectDir)bin\$(Platform)\$(Configuration)\ + obj\$(Platform)\$(Configuration)\ + Notepads32 + 10.0.19041.0 + 10.0.17763.0 + true + + + + + Debug + ARM + + + Debug + ARM64 + + + Debug + Win32 + + + Release + ARM + + + Release + ARM64 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + Application + v140 + v141 + v142 + Unicode + + + true + true + + + false + true + false + + + + + + + + + + + + + + + + Use + pch.h + $(IntDir)pch.pch + _CONSOLE;WIN32_LEAN_AND_MEAN;WINRT_LEAN_AND_MEAN;%(PreprocessorDefinitions) + Level4 + %(AdditionalOptions) /permissive- /bigobj + + + + + Disabled + _DEBUG;%(PreprocessorDefinitions) + + + Console + false + + + + + WIN32;%(PreprocessorDefinitions) + + + + + MaxSpeed + true + true + NDEBUG;%(PreprocessorDefinitions) + + + Windows + true + true + false + + + + + + + + + + Create + + + + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters new file mode 100644 index 000000000..146b6ea89 --- /dev/null +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Program.cs b/src/Notepads.DesktopExtension/Program.cs deleted file mode 100644 index 5ef8c8c52..000000000 --- a/src/Notepads.DesktopExtension/Program.cs +++ /dev/null @@ -1,315 +0,0 @@ -namespace Notepads.DesktopExtension -{ - using Microsoft.AppCenter; - using Microsoft.AppCenter.Analytics; - using Microsoft.AppCenter.Crashes; - using Notepads.Settings; - using System; - using System.Collections.Generic; - using System.Diagnostics; - using System.Globalization; - using System.IO; - using System.IO.MemoryMappedFiles; - using System.IO.Pipes; - using System.Linq; - using System.Security.Principal; - using System.Threading; - using System.Threading.Tasks; - using System.Windows.Forms; - using Windows.ApplicationModel; - using Windows.ApplicationModel.AppService; - using Windows.Foundation.Collections; - using Windows.Storage; - using Windows.System; - using Windows.System.UserProfile; - - static class Program - { - private const string DesktopExtensionMutexName = "DesktopExtensionMutexName"; - private const string AdminExtensionMutexName = "AdminExtensionMutexName"; - - private static readonly int sessionId = Process.GetCurrentProcess().SessionId; - private static readonly string packageSID = ReadSettingsKey(SettingsKey.PackageSidStr) as string; - - private static AppServiceConnection connection = null; - - /// - /// The main entry point for the application. - /// - static void Main(string[] args) - { - AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; - Application.ThreadException += (sender, args) => OnUnhandledException(sender, new UnhandledExceptionEventArgs(args.Exception, true)); - TaskScheduler.UnobservedTaskException += OnUnobservedException; - - if (new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) - { - if (!IsFirstInstance(AdminExtensionMutexName)) return; - InitializeExtensionService(); - } - else - { - if (!IsFirstInstance(DesktopExtensionMutexName)) return; - InitializeAppServiceConnection(); - if (args.Length > 2 && args[2] == "/admin") CreateElevetedExtension(); - } - - var services = new Type[] { typeof(Crashes), typeof(Analytics) }; - AppCenter.Start(SettingsKey.AppCenterSecret, services); - - Application.Run(); - } - - private static async void InitializeAppServiceConnection() - { - PrintDebugMessage("Successfully started Desktop Extension."); - - connection = new AppServiceConnection() - { - AppServiceName = "DesktopExtensionServiceConnection", - PackageFamilyName = Package.Current.Id.FamilyName - }; - - connection.RequestReceived += Connection_RequestReceived; - connection.ServiceClosed += Connection_ServiceClosed; - - AppServiceConnectionStatus status = await connection.OpenAsync(); - - if (status != AppServiceConnectionStatus.Success) - { - Application.Exit(); - } - - var message = new ValueSet { { SettingsKey.InteropCommandLabel, SettingsKey.RegisterExtensionCommandStr } }; - await connection.SendMessageAsync(message); - - PrintDebugMessage("Successfully created App Service."); - } - - private static void InitializeExtensionService() - { - PrintDebugMessage("Successfully started Adminstrator Extension."); - PrintDebugMessage("Waiting on uwp app to send data."); - - SaveFileFromPipeData(); - } - - private static bool IsFirstInstance(string mutexName) - { - var instanceHandlerMutex = new Mutex(true, mutexName, out var isFirstInstance); - - if (!isFirstInstance) - { - PrintDebugMessage("Closing this instance as another instance is already running.", 5000); - } - - return isFirstInstance; - } - - private static void Connection_ServiceClosed(AppServiceConnection sender, AppServiceClosedEventArgs args) - { - // connection to the UWP lost, so we shut down the desktop process - Application.Exit(); - } - - private static void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) - { - // Get a deferral because we use an awaitable API below to respond to the message - // and we don't want this call to get canceled while we are waiting. - var messageDeferral = args.GetDeferral(); - - var message = args.Request.Message; - if (!message.ContainsKey(SettingsKey.InteropCommandLabel) || !(message[SettingsKey.InteropCommandLabel] is string command)) return; - switch (command) - { - case SettingsKey.CreateElevetedExtensionCommandStr: - CreateElevetedExtension(); - break; - case SettingsKey.ExitAppCommandStr: - Application.Exit(); - break; - } - - messageDeferral.Complete(); - } - - private static async void CreateElevetedExtension() - { - var message = new ValueSet { { SettingsKey.InteropCommandLabel, SettingsKey.CreateElevetedExtensionCommandStr } }; - - try - { - ProcessStartInfo info = new ProcessStartInfo - { - Verb = "runas", - UseShellExecute = true, - FileName = Application.ExecutablePath - }; - - var process = Process.Start(info); - AppDomain.CurrentDomain.ProcessExit += (a, b) => process.Kill(); - message.Add(SettingsKey.InteropCommandAdminCreatedLabel, true); - - PrintDebugMessage("Adminstrator Extension has been launched."); - Analytics.TrackEvent("OnAdminstratorPrivilageGranted", new Dictionary { { "Accepted", true.ToString() } }); - } - catch (Exception ex) - { - message.Add(SettingsKey.InteropCommandAdminCreatedLabel, false); - - PrintDebugMessage("User canceled launching of Adminstrator Extension."); - Analytics.TrackEvent("OnAdminstratorPrivilageDenied", - new Dictionary { - { "Denied", true.ToString() }, - { "Message", ex.Message }, - { "Exception", ex.ToString() }, - { "InnerException", ex.InnerException?.ToString() }, - { "InnerExceptionMessage", ex.InnerException?.Message } - }); - } - finally - { - await connection.SendMessageAsync(message); - } - } - - private static async void SaveFileFromPipeData() - { - var result = "Failed"; - - using var clientStream = new NamedPipeClientStream(".", - $"Sessions\\{sessionId}\\AppContainerNamedObjects\\{packageSID}\\{Package.Current.Id.FamilyName}\\{SettingsKey.AdminPipeConnectionNameStr}", - PipeDirection.InOut, PipeOptions.Asynchronous); - - // Wait for uwp app to send request to write to file. - await clientStream.ConnectAsync(); - - // Start another thread to accept more write requests. - new Thread(new ThreadStart(SaveFileFromPipeData)).Start(); - - var pipeReader = new StreamReader(clientStream); - var pipeWriter = new StreamWriter(clientStream); - - var writeData = (await pipeReader.ReadLineAsync()).Split(new string[] { "?:" }, StringSplitOptions.None); - var filePath = writeData[0]; - var memoryMapName = $"AppContainerNamedObjects\\{packageSID}\\{writeData[1]}"; - - try - { - if (!int.TryParse(writeData[2], out int dataArrayLength)) throw new Exception("Failed to read piped data"); - - // Open the memory-mapped file and read data from it. - using (var reader = new BinaryReader(MemoryMappedFile.OpenExisting(memoryMapName).CreateViewStream())) - { - var data = reader.ReadBytes(dataArrayLength); - - await File.WriteAllBytesAsync(filePath, data); - } - - result = "Success"; - - PrintDebugMessage($"Successfully wrote to \"{filePath}\"."); - } - catch (Exception ex) - { - PrintDebugMessage($"Failed to write to \"{filePath}\"."); - Analytics.TrackEvent("OnWriteToSystemFileRequested", - new Dictionary { - { "Result", result }, - { "Message", ex.Message }, - { "Exception", ex.ToString() }, - { "InnerException", ex.InnerException?.ToString() }, - { "InnerExceptionMessage", ex.InnerException?.Message } - }); - } - finally - { - await pipeWriter.WriteLineAsync(result); - await pipeWriter.FlushAsync(); - - PrintDebugMessage("Waiting on uwp app to send data."); - if ("Success".Equals(result)) - { - Analytics.TrackEvent("OnWriteToSystemFileRequested", new Dictionary { { "Result", result } }); - } - } - } - - public static object ReadSettingsKey(string key) - { - object obj = null; - - ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; - if (localSettings.Values.ContainsKey(key)) - { - obj = localSettings.Values[key]; - } - - return obj; - } - - private static void PrintDebugMessage(string message, int waitAfterPrintingTime = 0) - { -#if DEBUG - Console.WriteLine(message); - Debug.WriteLine(message); - Thread.Sleep(waitAfterPrintingTime); -#endif - } - - private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) - { - var exception = e.ExceptionObject as Exception; - - var diagnosticInfo = new Dictionary() - { - { "Message", exception?.Message }, - { "Exception", exception?.ToString() }, - { "Culture", (GlobalizationPreferences.Languages.Count > 0 ? new CultureInfo(GlobalizationPreferences.Languages.First()) : null).EnglishName }, - { "AvailableMemory", ((float)MemoryManager.AppMemoryUsageLimit / 1024 / 1024).ToString("F0") }, - { "FirstUseTimeUTC", Process.GetCurrentProcess().StartTime.ToUniversalTime().ToString("MM/dd/yyyy HH:mm:ss") }, - { "OSArchitecture", Package.Current.Id.Architecture.ToString() }, - { "OSVersion", Environment.OSVersion.Version.ToString() }, - { "IsElevated", new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator).ToString() } - }; - - var attachment = ErrorAttachmentLog.AttachmentWithText( - $"Exception: {exception}, " + - $"Message: {exception?.Message}, " + - $"InnerException: {exception?.InnerException}, " + - $"InnerExceptionMessage: {exception?.InnerException?.Message}", - "UnhandledException"); - - Analytics.TrackEvent("OnUnhandledException", diagnosticInfo); - Crashes.TrackError(exception, diagnosticInfo, attachment); - - // handle it manually. - if (e.IsTerminating) Application.Restart(); - } - - private static void OnUnobservedException(object sender, UnobservedTaskExceptionEventArgs e) - { - var diagnosticInfo = new Dictionary() - { - { "Message", e.Exception?.Message }, - { "Exception", e.Exception?.ToString() }, - { "InnerException", e.Exception?.InnerException?.ToString() }, - { "InnerExceptionMessage", e.Exception?.InnerException?.Message } - }; - - var attachment = ErrorAttachmentLog.AttachmentWithText( - $"Exception: {e.Exception}, " + - $"Message: {e.Exception?.Message}, " + - $"InnerException: {e.Exception?.InnerException}, " + - $"InnerExceptionMessage: {e.Exception?.InnerException?.Message}, " + - $"IsDesktopExtension: {true}", - "UnobservedException"); - - Analytics.TrackEvent("OnUnobservedException", diagnosticInfo); - Crashes.TrackError(e.Exception, diagnosticInfo, attachment); - - // suppress and handle it manually. - e.SetObserved(); - } - } -} diff --git a/src/Notepads.DesktopExtension/PropertySheet.props b/src/Notepads.DesktopExtension/PropertySheet.props new file mode 100644 index 000000000..b0c622690 --- /dev/null +++ b/src/Notepads.DesktopExtension/PropertySheet.props @@ -0,0 +1,16 @@ + + + + + + + + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp new file mode 100644 index 000000000..06467e3ff --- /dev/null +++ b/src/Notepads.DesktopExtension/main.cpp @@ -0,0 +1,339 @@ +#include "pch.h" + +using namespace std; +using namespace winrt; +using namespace Windows::ApplicationModel; +using namespace Windows::ApplicationModel::AppService; +using namespace Windows::Foundation; +using namespace Windows::Foundation::Collections; +using namespace Windows::Storage; + +constexpr int PIPE_READ_BUFFER = MAX_PATH + 40; + +constexpr LPCTSTR DesktopExtensionMutexName = L"DesktopExtensionMutexName"; +constexpr LPCTSTR AdminExtensionMutexName = L"AdminExtensionMutexName"; + +HANDLE appExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL); +HANDLE childProcessHandle = INVALID_HANDLE_VALUE; + +DWORD sessionId; + +AppServiceConnection interopServiceConnection = { 0 }; + +int releaseResources() +{ + CloseHandle(appExitEvent); + CloseHandle(childProcessHandle); + return 0; +} + +void exitApp() +{ + if(childProcessHandle) TerminateProcess(childProcessHandle, 0); + SetEvent(appExitEvent); +} + +void printDebugMessage(LPCTSTR message, DWORD sleepTime = 0) +{ +#ifdef _DEBUG + wcout << message << endl; + Sleep(sleepTime); +#endif +} + +void printDebugMessage(LPCTSTR message, LPCTSTR parameter) +{ +#ifdef _DEBUG + wcout << message << " \"" << parameter << "\"" << endl; +#endif +} + +void onUnhandledException() +{ + //TODO: Implement exception handling +} + +void onUnexpectedException() +{ + //TODO: Implement exception handling +} + +IInspectable readSettingsKey(hstring key) +{ + return ApplicationData::Current().LocalSettings().Values().TryLookup(key); +} + +hstring packageSid = unbox_value_or(readSettingsKey(L"PackageSidStr"), L""); + +DWORD saveFileFromPipeData(LPVOID param) +{ + LPCSTR result = "Failed"; + + wstringstream pipeName; + pipeName << "\\\\.\\pipe\\Sessions\\" << sessionId << "\\AppContainerNamedObjects\\"<< packageSid.c_str() << "\\" << Package::Current().Id().FamilyName().c_str() << "\\NotepadsAdminWritePipe"; + + HANDLE hPipe = INVALID_HANDLE_VALUE; + while (hPipe == INVALID_HANDLE_VALUE) + { + Sleep(50); + if (WaitNamedPipe(pipeName.str().c_str(), NMPWAIT_WAIT_FOREVER)) + { + hPipe = CreateFile(pipeName.str().c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + } + } + + CreateThread(NULL, 0, saveFileFromPipeData, NULL, 0, NULL); + + char readBuffer[PIPE_READ_BUFFER]; + stringstream bufferStore; + DWORD byteRead; + do + { + if (ReadFile(hPipe, readBuffer, PIPE_READ_BUFFER * sizeof(char), &byteRead, NULL)) + { + bufferStore << readBuffer; + } + } while (byteRead >= PIPE_READ_BUFFER); + + string filePathBuffer; + wstring filePath; + string memoryMapId; + string dataArrayLengthStr; + getline(bufferStore, filePathBuffer, '|'); + getline(bufferStore, memoryMapId, '|'); + getline(bufferStore, dataArrayLengthStr); + int dataArrayLength = stoi(dataArrayLengthStr); + wstringstream memoryMapName; + memoryMapName << "AppContainerNamedObjects\\" << packageSid.c_str() << "\\" << memoryMapId.c_str(); + + HANDLE hMemory = OpenFileMapping(FILE_MAP_READ, FALSE, memoryMapName.str().c_str()); + if (hMemory) + { + LPVOID mapView = MapViewOfFile(hMemory, FILE_MAP_READ, 0, 0, dataArrayLength); + if (mapView) + { + // Need to cnvert file path string to UTF-16 to properly read emoji characters if present + int convertResult = MultiByteToWideChar(CP_UTF8, 0, filePathBuffer.c_str(), (int)strlen(filePathBuffer.c_str()), NULL, 0); + if (convertResult > 0) + { + filePath.resize(convertResult); + MultiByteToWideChar(CP_UTF8, 0, filePathBuffer.c_str(), (int)filePathBuffer.size(), &filePath[0], (int)filePath.size()); + } + + HANDLE hFile = CreateFile( + filePath.c_str(), + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + TRUNCATE_EXISTING, + 0, + NULL); + + if (hFile) + { + DWORD byteWrote; + if (WriteFile(hFile, mapView, dataArrayLength, &byteWrote, NULL) && FlushFileBuffers(hFile)) + { + result = "Success"; + } + + CloseHandle(hFile); + } + + CloseHandle(mapView); + } + + CloseHandle(hMemory); + } + + if (WriteFile(hPipe, result, strlen(result) * sizeof(char), NULL, NULL)) FlushFileBuffers(hPipe); + + CloseHandle(hPipe); + + if (strcmp(result, "Success") == 0) + { + printDebugMessage(L"Successfully wrote to", filePath.c_str()); + } + else + { + printDebugMessage(L"Failed to write to", filePath.c_str()); + } + printDebugMessage(L"Waiting on uwp app to send data."); + + return 0; +} + +void initializeAdminService() +{ + printDebugMessage(L"Successfully started Adminstrator Extension."); + printDebugMessage(L"Waiting on uwp app to send data."); + + saveFileFromPipeData(NULL); +} + +fire_and_forget launchElevatedProcess() +{ + TCHAR fileName[MAX_PATH]; + GetModuleFileName(NULL, fileName, MAX_PATH); + + SHELLEXECUTEINFO shExInfo = { 0 }; + shExInfo.cbSize = sizeof(shExInfo); + shExInfo.fMask = SEE_MASK_NOCLOSEPROCESS; + shExInfo.hwnd = 0; + shExInfo.lpVerb = L"runas"; + shExInfo.lpFile = fileName; + shExInfo.lpParameters = L""; + shExInfo.lpDirectory = 0; + shExInfo.nShow = SW_SHOW; + shExInfo.hInstApp = 0; + + auto message = ValueSet(); + message.Insert(L"Command", box_value(L"CreateElevetedExtension")); + if (ShellExecuteEx(&shExInfo)) + { + childProcessHandle = shExInfo.hProcess; + message.Insert(L"AdminCreated", box_value(true)); + printDebugMessage(L"Adminstrator Extension has been launched."); + } + else + { + message.Insert(L"AdminCreated", box_value(false)); + printDebugMessage(L"User canceled launching of Adminstrator Extension."); + } + co_await interopServiceConnection.SendMessageAsync(message); +} + +void onConnectionServiceRequestRecieved(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) +{ + // Get a deferral because we use an awaitable API below to respond to the message + // and we don't want this call to get canceled while we are waiting. + auto messageDeferral = args.GetDeferral(); + + auto message = args.Request().Message(); + if (!message.HasKey(L"Command")) return; + + auto command = unbox_value_or(message.TryLookup(L"Command"), L""); + if (command == L"CreateElevetedExtension") + { + launchElevatedProcess(); + } + else if (command == L"ExitApp") + { + exitApp(); + } + + messageDeferral.Complete(); +} + +void onConnectionServiceClosed(AppServiceConnection sender, AppServiceClosedEventArgs args) +{ + exitApp(); +} + +fire_and_forget initializeInteropService() +{ + printDebugMessage(L"Successfully started Desktop Extension."); + + interopServiceConnection = AppServiceConnection(); + interopServiceConnection.AppServiceName(L"DesktopExtensionServiceConnection"); + interopServiceConnection.PackageFamilyName(Package::Current().Id().FamilyName()); + + interopServiceConnection.RequestReceived(onConnectionServiceRequestRecieved); + interopServiceConnection.ServiceClosed(onConnectionServiceClosed); + + auto status = co_await interopServiceConnection.OpenAsync(); + if (status != AppServiceConnectionStatus::Success) + { + exitApp(); + } + + auto message = ValueSet(); + message.Insert(L"Command", box_value(L"RegisterExtension")); + co_await interopServiceConnection.SendMessageAsync(message); + + printDebugMessage(L"Successfully created App Service."); +} + +bool isFirstInstance(LPCTSTR mutexName) +{ + bool result = true; + try + { + auto hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, mutexName); + if (!hMutex) + { + CreateMutex(NULL, FALSE, mutexName); + } + else + { + result = false; + exitApp(); + printDebugMessage(L"Closing this instance as another instance is already running.", 5000); + } + ReleaseMutex(hMutex); + } + catch (...) { } + + return result; +} + +bool isElevatedProcess() +{ + bool result = false; + + HANDLE hToken = NULL; + if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) + { + TOKEN_ELEVATION Elevation; + DWORD cbSize = sizeof(TOKEN_ELEVATION); + if (GetTokenInformation(hToken, TokenElevation, &Elevation, sizeof(Elevation), &cbSize)) + { + result = Elevation.TokenIsElevated; + } + } + + if (hToken) + { + CloseHandle(hToken); + } + + return result; +} + +int main() +{ + set_terminate(onUnhandledException); + set_unexpected(onUnexpectedException); + _onexit(releaseResources); + + init_apartment(); + + ProcessIdToSessionId(GetCurrentProcessId(), &sessionId); + + if (isElevatedProcess()) + { + if (isFirstInstance(AdminExtensionMutexName)) + { + initializeAdminService(); + } + } + else + { + if (isFirstInstance(DesktopExtensionMutexName)) + { + initializeInteropService(); + } + } + + WaitForSingleObject(appExitEvent, INFINITE); +} + +#ifndef _DEBUG +int APIENTRY wWinMain(_In_ HINSTANCE hInstance, + _In_opt_ HINSTANCE hPrevInstance, + _In_ LPWSTR lpCmdLine, + _In_ int nCmdShow) +{ + main(); +} +#endif diff --git a/src/Notepads.DesktopExtension/packages.config b/src/Notepads.DesktopExtension/packages.config new file mode 100644 index 000000000..626739c5c --- /dev/null +++ b/src/Notepads.DesktopExtension/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/pch.cpp b/src/Notepads.DesktopExtension/pch.cpp new file mode 100644 index 000000000..bcb5590be --- /dev/null +++ b/src/Notepads.DesktopExtension/pch.cpp @@ -0,0 +1 @@ +#include "pch.h" diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h new file mode 100644 index 000000000..67498e053 --- /dev/null +++ b/src/Notepads.DesktopExtension/pch.h @@ -0,0 +1,11 @@ +#pragma once +#pragma comment(lib, "shell32") +#include +#include +#include +#include +#include +#include +#include +#include +#include diff --git a/src/Notepads.DesktopExtension/resource.h b/src/Notepads.DesktopExtension/resource.h new file mode 100644 index 000000000..17f3b0833 --- /dev/null +++ b/src/Notepads.DesktopExtension/resource.h @@ -0,0 +1,14 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by AssemblyInfo.rc + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 101 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/src/Notepads.Package/Notepads.Package.wapproj b/src/Notepads.Package/Notepads.Package.wapproj index 3c5239cd0..5a7e6beb1 100644 --- a/src/Notepads.Package/Notepads.Package.wapproj +++ b/src/Notepads.Package/Notepads.Package.wapproj @@ -55,10 +55,8 @@ - - True - + \ No newline at end of file diff --git a/src/Notepads.sln b/src/Notepads.sln index e2b7b03cb..4846cd921 100644 --- a/src/Notepads.sln +++ b/src/Notepads.sln @@ -19,7 +19,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Notepads.Services", "Notepa EndProject Project("{C7167F0D-BC9F-4E6E-AFE1-012C56B48DB5}") = "Notepads.Package", "Notepads.Package\Notepads.Package.wapproj", "{F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Notepads.DesktopExtension", "Notepads.DesktopExtension\Notepads.DesktopExtension.csproj", "{6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Notepads.DesktopExtension", "Notepads.DesktopExtension\Notepads.DesktopExtension.vcxproj", "{0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -105,22 +105,22 @@ Global {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|x86.ActiveCfg = Release|x86 {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|x86.Build.0 = Release|x86 {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|x86.Deploy.0 = Release|x86 - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|ARM.ActiveCfg = Debug|ARM - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|ARM.Build.0 = Debug|ARM - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|ARM64.ActiveCfg = Debug|ARM64 - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|ARM64.Build.0 = Debug|ARM64 - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|x64.ActiveCfg = Debug|x64 - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|x64.Build.0 = Debug|x64 - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|x86.ActiveCfg = Debug|x86 - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Debug|x86.Build.0 = Debug|x86 - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|ARM.ActiveCfg = Release|ARM - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|ARM.Build.0 = Release|ARM - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|ARM64.ActiveCfg = Release|ARM64 - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|ARM64.Build.0 = Release|ARM64 - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|x64.ActiveCfg = Release|x64 - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|x64.Build.0 = Release|x64 - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|x86.ActiveCfg = Release|x86 - {6B373CFA-95F2-44E8-A948-CED6E6E0EDA1}.Release|x86.Build.0 = Release|x86 + {0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}.Debug|ARM.ActiveCfg = Debug|ARM + {0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}.Debug|ARM.Build.0 = Debug|ARM + {0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}.Debug|ARM64.Build.0 = Debug|ARM64 + {0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}.Debug|x64.ActiveCfg = Debug|x64 + {0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}.Debug|x64.Build.0 = Debug|x64 + {0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}.Debug|x86.ActiveCfg = Debug|Win32 + {0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}.Debug|x86.Build.0 = Debug|Win32 + {0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}.Release|ARM.ActiveCfg = Release|ARM + {0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}.Release|ARM.Build.0 = Release|ARM + {0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}.Release|ARM64.ActiveCfg = Release|ARM64 + {0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}.Release|ARM64.Build.0 = Release|ARM64 + {0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}.Release|x64.ActiveCfg = Release|x64 + {0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}.Release|x64.Build.0 = Release|x64 + {0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}.Release|x86.ActiveCfg = Release|Win32 + {0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}.Release|x86.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index 40bfd6f8e..77eb943e5 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -58,7 +58,7 @@ private static async void InteropServiceConnection_RequestReceived(AppServiceCon { var message = args.Request.Message; if (!message.ContainsKey(SettingsKey.InteropCommandLabel) || - SettingsKey.CreateElevetedExtensionCommandStr.Equals(message[SettingsKey.InteropCommandLabel])) return; + !SettingsKey.CreateElevetedExtensionCommandStr.Equals(message[SettingsKey.InteropCommandLabel])) return; await CoreApplication.MainView.CoreWindow.Dispatcher.CallOnUIThreadAsync(() => { @@ -115,7 +115,7 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) writer.Flush(); } - await pipeWriter.WriteLineAsync(string.Join("?:", filePath, mapName, data.Length)); + await pipeWriter.WriteLineAsync(string.Join('|', filePath, mapName, data.Length)); await pipeWriter.FlushAsync(); // Wait for desktop extension to send response. From 0c80fd2708ffc34d6465f7389bed25ca6d681493 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Tue, 1 Dec 2020 02:32:48 +0530 Subject: [PATCH 082/181] code refactor. --- src/Notepads.DesktopExtension/main.cpp | 26 +++++++++++++------------- src/Notepads.DesktopExtension/pch.h | 10 ++++++++++ 2 files changed, 23 insertions(+), 13 deletions(-) diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index 06467e3ff..15cdea316 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -8,11 +8,11 @@ using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Storage; -constexpr int PIPE_READ_BUFFER = MAX_PATH + 40; - constexpr LPCTSTR DesktopExtensionMutexName = L"DesktopExtensionMutexName"; constexpr LPCTSTR AdminExtensionMutexName = L"AdminExtensionMutexName"; +constexpr int PIPE_READ_BUFFER = MAX_PATH + 40; + HANDLE appExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL); HANDLE childProcessHandle = INVALID_HANDLE_VALUE; @@ -63,14 +63,14 @@ IInspectable readSettingsKey(hstring key) return ApplicationData::Current().LocalSettings().Values().TryLookup(key); } -hstring packageSid = unbox_value_or(readSettingsKey(L"PackageSidStr"), L""); +hstring packageSid = unbox_value_or(readSettingsKey(PackageSidStr), L""); DWORD saveFileFromPipeData(LPVOID param) { LPCSTR result = "Failed"; wstringstream pipeName; - pipeName << "\\\\.\\pipe\\Sessions\\" << sessionId << "\\AppContainerNamedObjects\\"<< packageSid.c_str() << "\\" << Package::Current().Id().FamilyName().c_str() << "\\NotepadsAdminWritePipe"; + pipeName << "\\\\.\\pipe\\Sessions\\" << sessionId << "\\AppContainerNamedObjects\\"<< packageSid.c_str() << "\\" << Package::Current().Id().FamilyName().c_str() << "\\" << AdminPipeConnectionNameStr; HANDLE hPipe = INVALID_HANDLE_VALUE; while (hPipe == INVALID_HANDLE_VALUE) @@ -96,9 +96,9 @@ DWORD saveFileFromPipeData(LPVOID param) } while (byteRead >= PIPE_READ_BUFFER); string filePathBuffer; - wstring filePath; string memoryMapId; string dataArrayLengthStr; + wstring filePath; getline(bufferStore, filePathBuffer, '|'); getline(bufferStore, memoryMapId, '|'); getline(bufferStore, dataArrayLengthStr); @@ -188,16 +188,16 @@ fire_and_forget launchElevatedProcess() shExInfo.hInstApp = 0; auto message = ValueSet(); - message.Insert(L"Command", box_value(L"CreateElevetedExtension")); + message.Insert(InteropCommandLabel, box_value(CreateElevetedExtensionCommandStr)); if (ShellExecuteEx(&shExInfo)) { childProcessHandle = shExInfo.hProcess; - message.Insert(L"AdminCreated", box_value(true)); + message.Insert(InteropCommandAdminCreatedLabel, box_value(true)); printDebugMessage(L"Adminstrator Extension has been launched."); } else { - message.Insert(L"AdminCreated", box_value(false)); + message.Insert(InteropCommandAdminCreatedLabel, box_value(false)); printDebugMessage(L"User canceled launching of Adminstrator Extension."); } co_await interopServiceConnection.SendMessageAsync(message); @@ -210,14 +210,14 @@ void onConnectionServiceRequestRecieved(AppServiceConnection sender, AppServiceR auto messageDeferral = args.GetDeferral(); auto message = args.Request().Message(); - if (!message.HasKey(L"Command")) return; + if (!message.HasKey(InteropCommandLabel)) return; - auto command = unbox_value_or(message.TryLookup(L"Command"), L""); - if (command == L"CreateElevetedExtension") + auto command = unbox_value_or(message.TryLookup(InteropCommandLabel), L""); + if (command == CreateElevetedExtensionCommandStr) { launchElevatedProcess(); } - else if (command == L"ExitApp") + else if (command == ExitAppCommandStr) { exitApp(); } @@ -248,7 +248,7 @@ fire_and_forget initializeInteropService() } auto message = ValueSet(); - message.Insert(L"Command", box_value(L"RegisterExtension")); + message.Insert(InteropCommandLabel, box_value(RegisterExtensionCommandStr)); co_await interopServiceConnection.SendMessageAsync(message); printDebugMessage(L"Successfully created App Service."); diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h index 67498e053..efb64abb9 100644 --- a/src/Notepads.DesktopExtension/pch.h +++ b/src/Notepads.DesktopExtension/pch.h @@ -9,3 +9,13 @@ #include #include #include + +// These values depend upon constant fields described in ..\Notepads\Settings\SettingsKey.cs. +// Changing value in one place require change in another. +constexpr LPCTSTR PackageSidStr = L"PackageSidStr"; +constexpr LPCTSTR AdminPipeConnectionNameStr = L"NotepadsAdminWritePipe"; +constexpr LPCTSTR InteropCommandLabel = L"Command"; +constexpr LPCTSTR InteropCommandAdminCreatedLabel = L"AdminCreated"; +constexpr LPCTSTR RegisterExtensionCommandStr = L"RegisterExtension"; +constexpr LPCTSTR CreateElevetedExtensionCommandStr = L"CreateElevetedExtension"; +constexpr LPCTSTR ExitAppCommandStr = L"ExitApp"; \ No newline at end of file From 05b04a6ead027ffd824f843d1afaf9eb19d8664d Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Tue, 1 Dec 2020 14:39:17 +0530 Subject: [PATCH 083/181] code refactor. --- src/Notepads.DesktopExtension/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index 15cdea316..41059854f 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -65,7 +65,7 @@ IInspectable readSettingsKey(hstring key) hstring packageSid = unbox_value_or(readSettingsKey(PackageSidStr), L""); -DWORD saveFileFromPipeData(LPVOID param) +DWORD WINAPI saveFileFromPipeData(LPVOID param) { LPCSTR result = "Failed"; From a474d5fe08a3f448036625fecd8c816e350e5467 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Tue, 1 Dec 2020 16:34:43 +0530 Subject: [PATCH 084/181] code refactor. --- src/Notepads.DesktopExtension/main.cpp | 18 +++++++++++++++++- src/Notepads.DesktopExtension/pch.h | 1 + .../Services/DesktopExtensionService.cs | 3 ++- src/Notepads/Settings/SettingsKey.cs | 9 +++++++-- 4 files changed, 27 insertions(+), 4 deletions(-) diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index 41059854f..372f7a7e5 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -235,7 +235,7 @@ fire_and_forget initializeInteropService() printDebugMessage(L"Successfully started Desktop Extension."); interopServiceConnection = AppServiceConnection(); - interopServiceConnection.AppServiceName(L"DesktopExtensionServiceConnection"); + interopServiceConnection.AppServiceName(InteropServiceName); interopServiceConnection.PackageFamilyName(Package::Current().Id().FamilyName()); interopServiceConnection.RequestReceived(onConnectionServiceRequestRecieved); @@ -254,6 +254,21 @@ fire_and_forget initializeInteropService() printDebugMessage(L"Successfully created App Service."); } +bool isElevetedProcessLaunchRequested() +{ + bool result = false; + + LPTSTR* argList; + int argCount; + argList = CommandLineToArgvW(GetCommandLine(), &argCount); + if (argCount > 3 && wcscmp(argList[3], L"/admin") == 0) + { + result = true; + } + + return result; +} + bool isFirstInstance(LPCTSTR mutexName) { bool result = true; @@ -322,6 +337,7 @@ int main() if (isFirstInstance(DesktopExtensionMutexName)) { initializeInteropService(); + if (isElevetedProcessLaunchRequested()) launchElevatedProcess(); } } diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h index efb64abb9..5c2a1f6ed 100644 --- a/src/Notepads.DesktopExtension/pch.h +++ b/src/Notepads.DesktopExtension/pch.h @@ -12,6 +12,7 @@ // These values depend upon constant fields described in ..\Notepads\Settings\SettingsKey.cs. // Changing value in one place require change in another. +constexpr LPCTSTR InteropServiceName = L"DesktopExtensionServiceConnection"; constexpr LPCTSTR PackageSidStr = L"PackageSidStr"; constexpr LPCTSTR AdminPipeConnectionNameStr = L"NotepadsAdminWritePipe"; constexpr LPCTSTR InteropCommandLabel = L"Command"; diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index 77eb943e5..8e28bd84f 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -38,7 +38,7 @@ public static async Task Initialize() InteropServiceConnection = new AppServiceConnection() { - AppServiceName = "DesktopExtensionServiceConnection", + AppServiceName = SettingsKey.InteropServiceName, PackageFamilyName = Package.Current.Id.FamilyName }; @@ -148,6 +148,7 @@ public static async Task CreateElevetedExtension() if (message.ContainsKey(SettingsKey.InteropCommandFailedLabel) && (bool)message[SettingsKey.InteropCommandFailedLabel]) { + // Pass the group id that describes the correct parameter for prompting admin process launch await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync("LaunchAdmin"); } } diff --git a/src/Notepads/Settings/SettingsKey.cs b/src/Notepads/Settings/SettingsKey.cs index c7953d948..632979501 100644 --- a/src/Notepads/Settings/SettingsKey.cs +++ b/src/Notepads/Settings/SettingsKey.cs @@ -2,6 +2,7 @@ { internal static class SettingsKey { +#if DISABLE_XAML_GENERATED_MAIN // App related internal const string AppVersionStr = "AppVersionStr"; internal const string IsJumpListOutOfDateBool = "IsJumpListOutOfDateBool"; @@ -36,14 +37,18 @@ internal static class SettingsKey internal const string EditorEnableSmartCopyBool = "EditorEnableSmartCopyBool"; // Interop related + // These values depend upon constant fields described in ..\Notepads.DesktopExtension\pch.h. + // Changing value in one place require change in another. + internal const string AppCenterSecret = null; + internal const string InteropServiceName = "DesktopExtensionServiceConnection"; // Keep this same as AppSeviceName in manifest internal const string PackageSidStr = "PackageSidStr"; internal const string AdminPipeConnectionNameStr = "NotepadsAdminWritePipe"; + internal const string InteropCommandAdminCreatedLabel = "AdminCreated"; +#endif internal const string InteropCommandLabel = "Command"; internal const string InteropCommandFailedLabel = "Failed"; - internal const string InteropCommandAdminCreatedLabel = "AdminCreated"; internal const string RegisterExtensionCommandStr = "RegisterExtension"; internal const string CreateElevetedExtensionCommandStr = "CreateElevetedExtension"; internal const string ExitAppCommandStr = "ExitApp"; - internal const string AppCenterSecret = null; } } \ No newline at end of file From 78bacec014417a849e8d6de43606b5405a288343 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 3 Dec 2020 17:05:35 +0530 Subject: [PATCH 085/181] Implemented error logging. --- .../Notepads.DesktopExtension.vcxproj.filters | 34 +++- src/Notepads.DesktopExtension/main.cpp | 147 +++++++++++++----- .../Services/DesktopExtensionService.cs | 2 +- 3 files changed, 141 insertions(+), 42 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters index 146b6ea89..c376924f8 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters @@ -1,18 +1,42 @@  - - + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + - - + + Source Files + + + Source Files + + + + + Header Files + + + Header Files + - + + Resource Files + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index 372f7a7e5..d49c91987 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -11,25 +11,28 @@ using namespace Windows::Storage; constexpr LPCTSTR DesktopExtensionMutexName = L"DesktopExtensionMutexName"; constexpr LPCTSTR AdminExtensionMutexName = L"AdminExtensionMutexName"; -constexpr int PIPE_READ_BUFFER = MAX_PATH + 40; +constexpr int PIPE_READ_BUFFER = MAX_PATH + 240; +constexpr int MAX_TIME_STR = 9; +constexpr int MAX_DATE_STR = 11; HANDLE appExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL); -HANDLE childProcessHandle = INVALID_HANDLE_VALUE; +HANDLE appExitJob = NULL; DWORD sessionId; AppServiceConnection interopServiceConnection = { 0 }; +StorageFile logFile = nullptr; + int releaseResources() { CloseHandle(appExitEvent); - CloseHandle(childProcessHandle); + CloseHandle(appExitJob); return 0; } void exitApp() { - if(childProcessHandle) TerminateProcess(childProcessHandle, 0); SetEvent(appExitEvent); } @@ -41,21 +44,65 @@ void printDebugMessage(LPCTSTR message, DWORD sleepTime = 0) #endif } -void printDebugMessage(LPCTSTR message, LPCTSTR parameter) +void printDebugMessage(LPCTSTR message, LPCTSTR parameter, DWORD sleepTime = 0) { #ifdef _DEBUG wcout << message << " \"" << parameter << "\"" << endl; + Sleep(sleepTime); #endif } +fire_and_forget logLastError(LPCTSTR errorTitle) +{ + if (logFile != nullptr) + { + LPVOID msgBuf; + DWORD errorCode = GetLastError(); + + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + errorCode, + 0, + (LPTSTR)&msgBuf, + 0, + NULL); + + wstringstream msgStrm; + wstring msg; + msgStrm << (LPCTSTR)msgBuf; + LocalFree(msgBuf); + getline(msgStrm, msg, L'\r'); + + SYSTEMTIME systemTime; + GetSystemTime(&systemTime); + TCHAR timeStr[MAX_TIME_STR]; + GetTimeFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, NULL, timeStr, MAX_TIME_STR); + TCHAR dateStr[MAX_DATE_STR]; + GetDateFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, NULL, dateStr, MAX_DATE_STR, NULL); + wstringstream debugMsg; + debugMsg << dateStr << " " << timeStr << " " << "[" << "Error" << "]" << " " << "[" << "Error Code: " << errorCode << "]" << " " << errorTitle << msg << endl; + + co_await PathIO::AppendTextAsync(logFile.Path(), debugMsg.str().c_str()); + } +} + void onUnhandledException() { - //TODO: Implement exception handling + logLastError(L"OnUnhandledException: "); + exitApp(); } void onUnexpectedException() { - //TODO: Implement exception handling + logLastError(L"OnUnexpectedException: "); + exitApp(); +} + +void setExceptionHandling() +{ + set_terminate(onUnhandledException); + set_unexpected(onUnexpectedException); } IInspectable readSettingsKey(hstring key) @@ -67,6 +114,8 @@ hstring packageSid = unbox_value_or(readSettingsKey(PackageSidStr), L"" DWORD WINAPI saveFileFromPipeData(LPVOID param) { + setExceptionHandling(); + LPCSTR result = "Failed"; wstringstream pipeName; @@ -168,7 +217,7 @@ void initializeAdminService() printDebugMessage(L"Successfully started Adminstrator Extension."); printDebugMessage(L"Waiting on uwp app to send data."); - saveFileFromPipeData(NULL); + CreateThread(NULL, 0, saveFileFromPipeData, NULL, 0, NULL); } fire_and_forget launchElevatedProcess() @@ -191,7 +240,14 @@ fire_and_forget launchElevatedProcess() message.Insert(InteropCommandLabel, box_value(CreateElevetedExtensionCommandStr)); if (ShellExecuteEx(&shExInfo)) { - childProcessHandle = shExInfo.hProcess; + // Create Job to close child process when parent exits/crashes. + if (appExitJob) CloseHandle(appExitJob); + appExitJob = CreateJobObject(NULL, NULL); + JOBOBJECT_EXTENDED_LIMIT_INFORMATION info = { 0 }; + info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + SetInformationJobObject(appExitJob, JobObjectExtendedLimitInformation, &info, sizeof(info)); + AssignProcessToJobObject(appExitJob, shExInfo.hProcess); + message.Insert(InteropCommandAdminCreatedLabel, box_value(true)); printDebugMessage(L"Adminstrator Extension has been launched."); } @@ -208,6 +264,7 @@ void onConnectionServiceRequestRecieved(AppServiceConnection sender, AppServiceR // Get a deferral because we use an awaitable API below to respond to the message // and we don't want this call to get canceled while we are waiting. auto messageDeferral = args.GetDeferral(); + setExceptionHandling(); auto message = args.Request().Message(); if (!message.HasKey(InteropCommandLabel)) return; @@ -254,6 +311,21 @@ fire_and_forget initializeInteropService() printDebugMessage(L"Successfully created App Service."); } +fire_and_forget initializeLogging(LPCTSTR trailStr) +{ + auto localFolder = ApplicationData::Current().LocalFolder(); + auto logFolder = co_await localFolder.CreateFolderAsync(L"Logs", CreationCollisionOption::OpenIfExists); + SYSTEMTIME systemTime; + GetSystemTime(&systemTime); + TCHAR timeStr[MAX_TIME_STR]; + GetTimeFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, L"HHmmss", timeStr, MAX_TIME_STR); + TCHAR dateStr[MAX_DATE_STR]; + GetDateFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, L"yyyyMMdd", dateStr, MAX_DATE_STR, NULL); + wstringstream logFilePath; + logFilePath << dateStr << "T" << timeStr << trailStr; + logFile = co_await logFolder.CreateFileAsync(logFilePath.str(), CreationCollisionOption::OpenIfExists); +} + bool isElevetedProcessLaunchRequested() { bool result = false; @@ -272,22 +344,19 @@ bool isElevetedProcessLaunchRequested() bool isFirstInstance(LPCTSTR mutexName) { bool result = true; - try + + auto hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, mutexName); + if (!hMutex) { - auto hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, mutexName); - if (!hMutex) - { - CreateMutex(NULL, FALSE, mutexName); - } - else - { - result = false; - exitApp(); - printDebugMessage(L"Closing this instance as another instance is already running.", 5000); - } - ReleaseMutex(hMutex); + CreateMutex(NULL, FALSE, mutexName); } - catch (...) { } + else + { + result = false; + printDebugMessage(L"Closing this instance as another instance is already running.", 5000); + exitApp(); + } + ReleaseMutex(hMutex); return result; } @@ -317,31 +386,37 @@ bool isElevatedProcess() int main() { - set_terminate(onUnhandledException); - set_unexpected(onUnexpectedException); + setExceptionHandling(); + SetErrorMode(SEM_NOGPFAULTERRORBOX); _onexit(releaseResources); init_apartment(); - ProcessIdToSessionId(GetCurrentProcessId(), &sessionId); - if (isElevatedProcess()) { - if (isFirstInstance(AdminExtensionMutexName)) - { - initializeAdminService(); - } + if (!isFirstInstance(AdminExtensionMutexName)) return 0; + +#ifdef _DEBUG + initializeLogging(L"-elevated-extension.log"); +#endif + + ProcessIdToSessionId(GetCurrentProcessId(), &sessionId); + initializeAdminService(); } else { - if (isFirstInstance(DesktopExtensionMutexName)) - { - initializeInteropService(); - if (isElevetedProcessLaunchRequested()) launchElevatedProcess(); - } + if (!isFirstInstance(DesktopExtensionMutexName)) return 0; + +#ifdef _DEBUG + initializeLogging(L"-extension.log"); +#endif + + initializeInteropService(); + if (isElevetedProcessLaunchRequested()) launchElevatedProcess(); } WaitForSingleObject(appExitEvent, INFINITE); + exit(0); } #ifndef _DEBUG diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index 8e28bd84f..ce645731e 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -146,7 +146,7 @@ public static async Task CreateElevetedExtension() var response = await InteropServiceConnection.SendMessageAsync(message); message = response.Message; - if (message.ContainsKey(SettingsKey.InteropCommandFailedLabel) && (bool)message[SettingsKey.InteropCommandFailedLabel]) + if (message?.ContainsKey(SettingsKey.InteropCommandFailedLabel) ?? false && (bool)message[SettingsKey.InteropCommandFailedLabel]) { // Pass the group id that describes the correct parameter for prompting admin process launch await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync("LaunchAdmin"); From 845bad6825fd4ef0c9990b6a4b97240c839f6ce3 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 3 Dec 2020 23:06:53 +0530 Subject: [PATCH 086/181] Fixed github action. --- .github/workflows/Build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 5a1b1d3e3..6c3270dd2 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -21,8 +21,8 @@ jobs: fetch-depth: 0 # Add MSBuild to the PATH: https://github.com/microsoft/setup-msbuild - - name: Setup MSBuild.exe - uses: microsoft/setup-msbuild@2008f912f56e61277eefaac6d1888b750582aa16 + - name: Setup MSBuild + uses: microsoft/setup-msbuild@v1 - name: Restore the application run: msbuild $env:Solution_Name /t:Restore /p:Configuration=$env:Configuration From 21dfdce469f480c74327b72e8cd65bc16732815a Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 3 Dec 2020 23:38:42 +0530 Subject: [PATCH 087/181] Fixed github action. --- .github/workflows/Build.yml | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 6c3270dd2..cba1fac16 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -24,10 +24,9 @@ jobs: - name: Setup MSBuild uses: microsoft/setup-msbuild@v1 - - name: Restore the application - run: msbuild $env:Solution_Name /t:Restore /p:Configuration=$env:Configuration - env: - Configuration: ${{ matrix.configuration }} + - name: Restore NuGet packages + uses: NuGet/setup-nuget@v1.0.5 + run: nuget restore $env:Solution_Name - name: Build run: | From 7e293b86f6fa757e0f11b1f30d1eff5b95020afb Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 3 Dec 2020 23:48:06 +0530 Subject: [PATCH 088/181] Fixed Github task. --- .github/workflows/Build.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index cba1fac16..b51181a5e 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -24,8 +24,10 @@ jobs: - name: Setup MSBuild uses: microsoft/setup-msbuild@v1 - - name: Restore NuGet packages + - name: Setup NuGet uses: NuGet/setup-nuget@v1.0.5 + + - name: Restore NuGet packages run: nuget restore $env:Solution_Name - name: Build From a9d21debcc467ff04e32bcab5efdf3bb8b7c64ca Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 4 Dec 2020 15:33:49 +0530 Subject: [PATCH 089/181] code refactor. --- src/Notepads.DesktopExtension/main.cpp | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index d49c91987..a79f39395 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -384,7 +384,11 @@ bool isElevatedProcess() return result; } +#ifndef _DEBUG +int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) +#else int main() +#endif { setExceptionHandling(); SetErrorMode(SEM_NOGPFAULTERRORBOX); @@ -417,14 +421,4 @@ int main() WaitForSingleObject(appExitEvent, INFINITE); exit(0); -} - -#ifndef _DEBUG -int APIENTRY wWinMain(_In_ HINSTANCE hInstance, - _In_opt_ HINSTANCE hPrevInstance, - _In_ LPWSTR lpCmdLine, - _In_ int nCmdShow) -{ - main(); -} -#endif +} \ No newline at end of file From b4e7d64c1957204c7e910ac2f173edd3a4146cb7 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 5 Dec 2020 10:55:09 +0530 Subject: [PATCH 090/181] Fixed reading from pipe in some cases. --- src/Notepads.DesktopExtension/main.cpp | 43 ++++++++++++++------------ 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index a79f39395..f98cafa07 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -133,27 +133,38 @@ DWORD WINAPI saveFileFromPipeData(LPVOID param) CreateThread(NULL, 0, saveFileFromPipeData, NULL, 0, NULL); - char readBuffer[PIPE_READ_BUFFER]; - stringstream bufferStore; + char readBuffer[PIPE_READ_BUFFER] = { 0 }; + string pipeDataStr; DWORD byteRead; do { - if (ReadFile(hPipe, readBuffer, PIPE_READ_BUFFER * sizeof(char), &byteRead, NULL)) + if (ReadFile(hPipe, readBuffer, (PIPE_READ_BUFFER - 1) * sizeof(char), &byteRead, NULL)) { - bufferStore << readBuffer; + pipeDataStr.append(readBuffer); + fill(begin(readBuffer), end(readBuffer), '\0'); } - } while (byteRead >= PIPE_READ_BUFFER); + } while (byteRead >= (PIPE_READ_BUFFER - 1) * sizeof(char)); + + // Need to cnvert pipe data string to UTF-16 to properly read unicode characters + wstring pipeDataWstr; + int convertResult = MultiByteToWideChar(CP_UTF8, 0, pipeDataStr.c_str(), (int)strlen(pipeDataStr.c_str()), NULL, 0); + if (convertResult > 0) + { + pipeDataWstr.resize(convertResult); + MultiByteToWideChar(CP_UTF8, 0, pipeDataStr.c_str(), (int)pipeDataStr.size(), &pipeDataWstr[0], (int)pipeDataWstr.size()); + } + wstringstream pipeData(pipeDataWstr); - string filePathBuffer; - string memoryMapId; - string dataArrayLengthStr; wstring filePath; - getline(bufferStore, filePathBuffer, '|'); - getline(bufferStore, memoryMapId, '|'); - getline(bufferStore, dataArrayLengthStr); + wstring memoryMapId; + wstring dataArrayLengthStr; + getline(pipeData, filePath, L'|'); + getline(pipeData, memoryMapId, L'|'); + getline(pipeData, dataArrayLengthStr); + int dataArrayLength = stoi(dataArrayLengthStr); wstringstream memoryMapName; - memoryMapName << "AppContainerNamedObjects\\" << packageSid.c_str() << "\\" << memoryMapId.c_str(); + memoryMapName << "AppContainerNamedObjects\\" << packageSid.c_str() << "\\" << memoryMapId; HANDLE hMemory = OpenFileMapping(FILE_MAP_READ, FALSE, memoryMapName.str().c_str()); if (hMemory) @@ -161,14 +172,6 @@ DWORD WINAPI saveFileFromPipeData(LPVOID param) LPVOID mapView = MapViewOfFile(hMemory, FILE_MAP_READ, 0, 0, dataArrayLength); if (mapView) { - // Need to cnvert file path string to UTF-16 to properly read emoji characters if present - int convertResult = MultiByteToWideChar(CP_UTF8, 0, filePathBuffer.c_str(), (int)strlen(filePathBuffer.c_str()), NULL, 0); - if (convertResult > 0) - { - filePath.resize(convertResult); - MultiByteToWideChar(CP_UTF8, 0, filePathBuffer.c_str(), (int)filePathBuffer.size(), &filePath[0], (int)filePath.size()); - } - HANDLE hFile = CreateFile( filePath.c_str(), GENERIC_READ | GENERIC_WRITE, From 0ea00b15d83ec03939508504f28c3abdf2aac7f5 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sun, 6 Dec 2020 12:02:47 +0530 Subject: [PATCH 091/181] code refactor. --- src/Notepads.DesktopExtension/main.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index f98cafa07..16e596d8b 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -12,8 +12,8 @@ constexpr LPCTSTR DesktopExtensionMutexName = L"DesktopExtensionMutexName"; constexpr LPCTSTR AdminExtensionMutexName = L"AdminExtensionMutexName"; constexpr int PIPE_READ_BUFFER = MAX_PATH + 240; -constexpr int MAX_TIME_STR = 9; -constexpr int MAX_DATE_STR = 11; +constexpr int MAX_TIME_STR = 10; +constexpr int MAX_DATE_STR = 20; HANDLE appExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL); HANDLE appExitJob = NULL; @@ -52,7 +52,7 @@ void printDebugMessage(LPCTSTR message, LPCTSTR parameter, DWORD sleepTime = 0) #endif } -fire_and_forget logLastError(LPCTSTR errorTitle) +IAsyncAction logLastError(LPCTSTR errorTitle) { if (logFile != nullptr) { @@ -89,13 +89,13 @@ fire_and_forget logLastError(LPCTSTR errorTitle) void onUnhandledException() { - logLastError(L"OnUnhandledException: "); + logLastError(L"OnUnhandledException: ").get(); exitApp(); } void onUnexpectedException() { - logLastError(L"OnUnexpectedException: "); + logLastError(L"OnUnexpectedException: ").get(); exitApp(); } @@ -321,11 +321,11 @@ fire_and_forget initializeLogging(LPCTSTR trailStr) SYSTEMTIME systemTime; GetSystemTime(&systemTime); TCHAR timeStr[MAX_TIME_STR]; - GetTimeFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, L"HHmmss", timeStr, MAX_TIME_STR); + GetTimeFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, L"THHmmss", timeStr, MAX_TIME_STR); TCHAR dateStr[MAX_DATE_STR]; GetDateFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, L"yyyyMMdd", dateStr, MAX_DATE_STR, NULL); wstringstream logFilePath; - logFilePath << dateStr << "T" << timeStr << trailStr; + logFilePath << dateStr << timeStr << trailStr; logFile = co_await logFolder.CreateFileAsync(logFilePath.str(), CreationCollisionOption::OpenIfExists); } From 1442d260062b8233e83eadcd1780a149adfde85f Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Tue, 8 Dec 2020 15:45:49 +0530 Subject: [PATCH 092/181] Initial commit to integrate AppCenter crashanalytics. --- .github/workflows/Build.yml | 10 + azure-pipelines.yml | 19 +- src/Notepads.DesktopExtension/AssemblyInfo.rc | 5 + .../Notepads.DesktopExtension.vcxproj | 8 + .../Notepads.DesktopExtension.vcxproj.filters | 15 + src/Notepads.DesktopExtension/appcenter.cpp | 160 ++++++++++ src/Notepads.DesktopExtension/appcenter.json | 73 +++++ src/Notepads.DesktopExtension/build.ps1 | 23 ++ src/Notepads.DesktopExtension/debug.cpp | 133 ++++++++ src/Notepads.DesktopExtension/elevated.cpp | 131 ++++++++ src/Notepads.DesktopExtension/extension.cpp | 102 ++++++ src/Notepads.DesktopExtension/main.cpp | 295 +----------------- src/Notepads.DesktopExtension/pch.h | 63 +++- src/Notepads.DesktopExtension/resource.h | 5 +- src/Notepads.Package/Package.appxmanifest | 2 +- src/Notepads/App.xaml.cs | 2 + src/Notepads/Program.cs | 13 - .../Services/DesktopExtensionService.cs | 13 + src/Notepads/Settings/SettingsKey.cs | 5 +- .../Views/MainPage/NotepadsMainPage.xaml.cs | 9 +- 20 files changed, 751 insertions(+), 335 deletions(-) create mode 100644 src/Notepads.DesktopExtension/appcenter.cpp create mode 100644 src/Notepads.DesktopExtension/appcenter.json create mode 100644 src/Notepads.DesktopExtension/build.ps1 create mode 100644 src/Notepads.DesktopExtension/debug.cpp create mode 100644 src/Notepads.DesktopExtension/elevated.cpp create mode 100644 src/Notepads.DesktopExtension/extension.cpp diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index b51181a5e..2f9b60597 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -30,6 +30,16 @@ jobs: - name: Restore NuGet packages run: nuget restore $env:Solution_Name + # Restore from cache ,if cache-miss, download and build vcpkg: https://github.com/lukka/run-vcpkg + - name: Setup vcpkg + uses: lukka/run-vcpkg@v6.0 + with: + setupOnly: true + + - name: Restore vcpkg packages + run: | + $VCPKG_ROOT/vcpkg install rapidjson:arm-windows rapidjson:arm64-windows rapidjson:x86-windows rapidjson:x64-windows curl:arm-windows curl:arm64-windows curl:x86-windows curl:x64-windows + - name: Build run: | msbuild $env:Project_Path /p:Configuration=$env:Configuration /p:UapAppxPackageBuildMode=$env:Appx_Package_Build_Mode /p:AppxBundle=$env:Appx_Bundle /p:AppxPackageSigningEnabled=false /p:AppxBundlePlatforms="$env:Appx_Bundle_Platforms" diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 0cac1f6bc..d7a6ee905 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -13,24 +13,19 @@ variables: appxPackageDir: '$(build.artifactStagingDirectory)\AppxPackages\\' steps: -- task: PowerShell@2 - displayName: 'Update appxmanifest' - inputs: - targetType: 'inline' - script: | - [xml]$manifest = Get-Content $(Build.SourcesDirectory)\src\Notepads.Package\Package.appxmanifest - $manifest.Package.Identity.Name="Notepads" - $manifest.Package.Applications.Application.VisualElements.DisplayName="Notepads" - $manifest.Package.Applications.Application.Extensions.Extension.AppExecutionAlias.ExecutionAlias.Alias="Notepads.exe" - $manifest.Save('$(Build.SourcesDirectory)\src\Notepads.Package\Package.appxmanifest') - failOnStderr: true - - task: NuGetToolInstaller@1 - task: NuGetCommand@2 inputs: restoreSolution: '$(solution)' +- task: PowerShell@2 + inputs: + targetType: 'inline' + script: | + $VCPKG_ROOT/vcpkg install rapidjson:arm-windows rapidjson:arm64-windows rapidjson:x86-windows rapidjson:x64-windows curl:arm-windows curl:arm64-windows curl:x86-windows curl:x64-windows + failOnStderr: true + - task: MSBuild@1 inputs: platform: 'x86' diff --git a/src/Notepads.DesktopExtension/AssemblyInfo.rc b/src/Notepads.DesktopExtension/AssemblyInfo.rc index a49b38dfb..63b4cc474 100644 --- a/src/Notepads.DesktopExtension/AssemblyInfo.rc +++ b/src/Notepads.DesktopExtension/AssemblyInfo.rc @@ -97,3 +97,8 @@ END ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Custom json file for AppCenter data upload. +// +APPCENTER_JSON JSONFILE "appcenter.json" \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index 6aa74fe5b..8d2a23fd9 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -89,6 +89,9 @@ Level4 %(AdditionalOptions) /permissive- /bigobj + + powershell -ExecutionPolicy Bypass $(ProjectDir)build.ps1 -project_dir $(ProjectDir) + @@ -124,12 +127,17 @@ + + + + Create + diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters index c376924f8..5a17c00d6 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters @@ -21,6 +21,18 @@ Source Files + + Source Files + + + Source Files + + + Source Files + + + Source Files + @@ -33,6 +45,9 @@ + + Resource Files + diff --git a/src/Notepads.DesktopExtension/appcenter.cpp b/src/Notepads.DesktopExtension/appcenter.cpp new file mode 100644 index 000000000..e1b81b340 --- /dev/null +++ b/src/Notepads.DesktopExtension/appcenter.cpp @@ -0,0 +1,160 @@ +#include "pch.h" +#include "resource.h" +#include "combaseapi.h" +#include "rapidjson/document.h" +#include "rapidjson/writer.h" +#include "rapidjson/stringbuffer.h" + +using namespace std; +using namespace rapidjson; +using namespace winrt; +using namespace Windows::ApplicationModel; +using namespace Windows::Foundation; +using namespace Windows::Security::ExchangeActiveSyncProvisioning; +using namespace Windows::Storage; +using namespace Windows::System; +using namespace Windows::System::Profile; + +void AppCenter::start() +{ + if (!AppCenterSecret) return; + + launchTimeStamp = getTimeStamp(); + + HMODULE handle = ::GetModuleHandle(NULL); + HRSRC rc = FindResource(handle, MAKEINTRESOURCE(APPCENTER_JSON), MAKEINTRESOURCE(JSONFILE)); + HGLOBAL rcData = LoadResource(handle, rc); + DWORD size = SizeofResource(handle, rc); + appCenterJSON = static_cast(LockResource(rcData)); + + headerList = curl_slist_append(headerList, "Content-Type: application/json"); + + stringstream appSecretHeader; + appSecretHeader << "app-secret: " << AppCenterSecret; + headerList = curl_slist_append(headerList, appSecretHeader.str().c_str()); + + hstring installId = unbox_value_or(readSettingsKey(AppCenterInstallIdStr), L""); + if (installId == L"") return; + stringstream installIdHeader; + installIdHeader << "install-id: " << installId.c_str(); + headerList = curl_slist_append(headerList, installIdHeader.str().c_str()); +} + +void AppCenter::trackError(DWORD errorCode, string message, bool isFatal) +{ + if (!AppCenterSecret) return; + + string timeStamp = getTimeStamp(); + + Document errorReportForm; + errorReportForm.Parse(appCenterJSON); + + string crashReportId = to_string(to_hstring(GuidHelper::CreateNewGuid())); + crashReportId.erase(0, crashReportId.find_first_not_of('{')).erase(crashReportId.find_last_not_of('}') + 1); + string errorAttachmentId = to_string(to_hstring(GuidHelper::CreateNewGuid())); + errorAttachmentId.erase(0, errorAttachmentId.find_first_not_of('{')).erase(errorAttachmentId.find_last_not_of('}') + 1); + + ULONGLONG version = stoull(AnalyticsInfo::VersionInfo().DeviceFamilyVersion().c_str()); + ULONGLONG major = (version & 0xFFFF000000000000L) >> 48; + ULONGLONG minor = (version & 0x0000FFFF00000000L) >> 32; + ULONGLONG build = (version & 0x00000000FFFF0000L) >> 16; + ULONGLONG revision = (version & 0x000000000000FFFFL); + stringstream osVersionBuilder; + osVersionBuilder << major << "." << minor << "." << build; + string osVersion = osVersionBuilder.str(); + osVersionBuilder << "." << revision; + string osBuild = osVersionBuilder.str(); + + EasClientDeviceInformation oemInfo = EasClientDeviceInformation(); + + stringstream screenSize; + RECT desktop; + GetWindowRect(GetDesktopWindow(), &desktop); + screenSize << desktop.right << "x" << desktop.bottom; + + WCHAR locale[LOCALE_NAME_MAX_LENGTH + 1]; + LCIDToLocaleName(GetThreadLocale(), locale, LOCALE_NAME_MAX_LENGTH, 0); + WCHAR localeDisplayName[LOCALE_NAME_MAX_LENGTH + 1]; + GetLocaleInfoEx(locale, LOCALE_SENGLISHDISPLAYNAME, localeDisplayName, LOCALE_NAME_MAX_LENGTH); + + TIME_ZONE_INFORMATION timeZoneInfo; + GetTimeZoneInformation(&timeZoneInfo); + + stringstream exceptionProp; + exceptionProp << "Win32Exception: Exception of code no. " << errorCode << " was thrown."; + + stringstream errorAttachmentBuilder; + errorAttachmentBuilder + << "Exception: Win32Exception code no. " << errorCode << ", " + << "Message: " << message << ", " + << "IsDesktopExtension: True" << ", " + << "IsElevated: " << (isElevatedProcess() ? "True" : "False"); + string errorAttachment = base64_encode(errorAttachmentBuilder.str()); + + Value& logReports = errorReportForm["logs"]; + for (int i = 0; i < logReports.GetArray().Size(); i++) + { + logReports[i]["timestamp"].SetString(timeStamp.c_str(), errorReportForm.GetAllocator()); + + logReports[i]["device"]["osName"].SetString(to_string(oemInfo.OperatingSystem()).c_str(), errorReportForm.GetAllocator()); + logReports[i]["device"]["osVersion"].SetString(osVersion.c_str(), errorReportForm.GetAllocator()); + logReports[i]["device"]["osBuild"].SetString(osBuild.c_str(), errorReportForm.GetAllocator()); + logReports[i]["device"]["model"].SetString(to_string(oemInfo.SystemProductName()).c_str(), errorReportForm.GetAllocator()); + logReports[i]["device"]["oemName"].SetString(to_string(oemInfo.SystemManufacturer()).c_str(), errorReportForm.GetAllocator()); + logReports[i]["device"]["screenSize"].SetString(screenSize.str().c_str(), errorReportForm.GetAllocator()); + logReports[i]["device"]["locale"].SetString(to_string(locale).c_str(), errorReportForm.GetAllocator()); + logReports[i]["device"]["timeZoneOffset"].SetInt(-1 * timeZoneInfo.Bias); + + if (i == 0) + { + logReports[i]["appLaunchTimestamp"].SetString(launchTimeStamp.c_str(), errorReportForm.GetAllocator()); + logReports[i]["processId"].SetString(to_string(GetCurrentProcessId()).c_str(), errorReportForm.GetAllocator()); + logReports[i]["id"].SetString(crashReportId.c_str(), errorReportForm.GetAllocator()); + logReports[i]["fatal"].SetBool(isFatal); + logReports[i]["errorThreadId"].SetInt(GetCurrentThreadId()); + + logReports[i]["exception"]["message"].SetString(message.c_str(), errorReportForm.GetAllocator()); + logReports[i]["exception"]["innerExceptions"][0]["type"].SetString(exceptionProp.str().c_str(), errorReportForm.GetAllocator()); + + logReports[i]["properties"]["exception"].SetString(exceptionProp.str().c_str(), errorReportForm.GetAllocator()); + logReports[i]["properties"]["message"].SetString(message.c_str(), errorReportForm.GetAllocator()); + logReports[i]["properties"]["culture"].SetString(to_string(localeDisplayName).c_str(), errorReportForm.GetAllocator()); + logReports[i]["properties"]["availableMemory"].SetString(to_string((FLOAT)MemoryManager::AppMemoryUsageLimit() / 1024 / 1024).c_str(), errorReportForm.GetAllocator()); + logReports[i]["properties"]["firstUseTimeUTC"].SetString(getTimeStamp("%m/%d/%Y %T").c_str(), errorReportForm.GetAllocator()); + logReports[i]["properties"]["osArchitecture"].SetString(to_string(Package::Current().Id().Architecture()).c_str(), errorReportForm.GetAllocator()); + logReports[i]["properties"]["osVersion"].SetString(osBuild.c_str(), errorReportForm.GetAllocator()); + logReports[i]["properties"]["isElevated"].SetString(isElevatedProcess() ? "True" : "False", errorReportForm.GetAllocator()); + } + else if (i == 1) + { + logReports[i]["data"].SetString(errorAttachment.c_str(), errorReportForm.GetAllocator()); + logReports[i]["errorId"].SetString(crashReportId.c_str(), errorReportForm.GetAllocator()); + logReports[i]["id"].SetString(errorAttachmentId.c_str(), errorReportForm.GetAllocator()); + } + } + + + StringBuffer errorReport; + Writer writer(errorReport); + errorReportForm.Accept(writer); + + cout << errorReport.GetString() << endl; + + /*CURL* curl = curl_easy_init(); + if (curl) { + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerList); + curl_easy_setopt(curl, CURLOPT_URL, "https://in.appcenter.ms/logs?Api-Version=1.0.0"); + curl_easy_setopt(curl, CURLOPT_POSTFIELDS, errorReport.GetString()); + +#ifdef _DEBUG + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); +#endif + + CURLcode res = curl_easy_perform(curl); + if (res != CURLE_OK) + fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); + else + fprintf(stderr, "curl_easy_perform() succeded: %s\n", curl_easy_strerror(res)); + } + curl_easy_cleanup(curl);*/ +} \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/appcenter.json b/src/Notepads.DesktopExtension/appcenter.json new file mode 100644 index 000000000..f975a4270 --- /dev/null +++ b/src/Notepads.DesktopExtension/appcenter.json @@ -0,0 +1,73 @@ +{ + "logs": [ + { + "type": "managedError", + "timestamp": "", + "appLaunchTimestamp": "", + "processId": "", + "id": "", + "fatal": false, + "processName": "Notepads32.exe", + "errorThreadId": 0, + "device": { + "appNamespace": "Notepads.DesktopExtension", + "appVersion": "1.4.2.0", + "appBuild": "1.4.2.0", + "sdkName": "appcenter.uwp", + "sdkVersion": "3.4.1", + "osName": "", + "osVersion": "", + "osBuild": "", + "model": "", + "oemName": "", + "screenSize": "", + "locale": "", + "timeZoneOffset": 0 + }, + "exception": { + "type": "Win32Exception", + "message": "", + "stackTrace": "", + "innerExceptions": [ + { + "type": "" + } + ] + }, + "properties": { + "exception": "", + "message": "", + "culture": "", + "availableMemory": "", + "firstUseTimeUTC": "", + "osArchitecture": "", + "osVersion": "", + "isDesktopExtension": "True", + "isElevated": "False" + } + }, + { + "type": "errorAttachment", + "contentType": "text/plain", + "timestamp": "", + "data": "", + "errorId": "", + "id": "", + "device": { + "appNamespace": "Notepads.DesktopExtension", + "appVersion": "1.4.2.0", + "appBuild": "1.4.2.0", + "sdkName": "appcenter.uwp", + "sdkVersion": "3.4.1", + "osName": "", + "osVersion": "", + "osBuild": "", + "model": "", + "oemName": "", + "screenSize": "", + "locale": "", + "timeZoneOffset": 0 + } + } + ] +} diff --git a/src/Notepads.DesktopExtension/build.ps1 b/src/Notepads.DesktopExtension/build.ps1 new file mode 100644 index 000000000..7217625c3 --- /dev/null +++ b/src/Notepads.DesktopExtension/build.ps1 @@ -0,0 +1,23 @@ +param ( + [string]$project_dir = $(throw "-project_dir= is required") +) + +$project_dir = Resolve-Path $project_dir.TrimEnd("\") +$appcenter_file = "${project_dir}\appcenter.json" +$manifest_file = "${project_dir}\..\Notepads.Package\Package.appxmanifest" +$uwp_project_file = "${project_dir}\..\Notepads\Notepads.csproj" + +$appcenter_format = Get-Content $appcenter_file -raw | ConvertFrom-Json +[xml]$manifest = Get-Content $manifest_file +[xml]$sdk_target = Get-Content $uwp_project_file + +# Keep version string in format json same as package version +$appcenter_format.logs.device | ForEach-Object {$_.appVersion = $manifest.Package.Identity.Version} +$appcenter_format.logs.device | ForEach-Object {$_.appBuild = $manifest.Package.Identity.Version} + +# Keep appcenter sdk version same as nuget package version +$appcenter_sdk_version = $appcenter_format.logs.device.sdkVersion[0] +$sdk_target.Project.ItemGroup.PackageReference | ForEach-Object {if($_.Include -eq 'Microsoft.AppCenter.Crashes'){$appcenter_sdk_version = $_.Version}} +$appcenter_format.logs.device | ForEach-Object {$_.sdkVersion = $appcenter_sdk_version} + +$appcenter_format | ConvertTo-Json -depth 10| Set-Content $appcenter_file \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/debug.cpp b/src/Notepads.DesktopExtension/debug.cpp new file mode 100644 index 000000000..27a1ce272 --- /dev/null +++ b/src/Notepads.DesktopExtension/debug.cpp @@ -0,0 +1,133 @@ +#include "pch.h" + +using namespace std; +using namespace winrt; +using namespace Windows::Foundation; +using namespace Windows::Storage; +using namespace Windows::System; + +constexpr int MAX_TIME_STR = 20; +constexpr int MAX_DATE_STR = 20; +constexpr int MAX_DATETIME_STR = 100; + +StorageFile logFile = nullptr; + +void printDebugMessage(LPCTSTR message, DWORD sleepTime) +{ +#ifdef _DEBUG + wcout << message << endl; + Sleep(sleepTime); +#endif +} + +void printDebugMessage(LPCTSTR message, LPCTSTR parameter, DWORD sleepTime) +{ +#ifdef _DEBUG + wcout << message << " \"" << parameter << "\"" << endl; + Sleep(sleepTime); +#endif +} + +string to_string(ProcessorArchitecture arch) +{ + switch (arch) + { + case ProcessorArchitecture::Arm: + return "Arm"; + case ProcessorArchitecture::Arm64: + return "Arm64"; + case ProcessorArchitecture::X86OnArm64: + return "X86OnArm64"; + case ProcessorArchitecture::X86: + return "X86"; + case ProcessorArchitecture::X64: + return "X64"; + case ProcessorArchitecture::Neutral: + return "Neutral"; + default: + return "Unknown"; + } +} + +string getTimeStamp() +{ + SYSTEMTIME systemTime; + GetSystemTime(&systemTime); + stringstream timeStamp; + timeStamp << getTimeStamp("%FT%T") << "." << systemTime.wMilliseconds << "Z"; + return timeStamp.str(); +} + +string getTimeStamp(const char* format) +{ + time_t timePast = time(NULL); + tm* utcTime = gmtime(&timePast); + CHAR timeStamp[MAX_DATETIME_STR]; + strftime(timeStamp, sizeof(timeStamp), format, utcTime); + return timeStamp; +} + +//From https://stackoverflow.com/a/34571089/5155484 +typedef unsigned char uchar; +static const string b = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +string base64_encode(const string& in) +{ + string out; + + int val = 0, valb = -6; + for (uchar c : in) { + val = (val << 8) + c; + valb += 8; + while (valb >= 0) { + out.push_back(b[(val >> valb) & 0x3F]); + valb -= 6; + } + } + if (valb > -6) out.push_back(b[((val << 8) >> (valb + 8)) & 0x3F]); + while (out.size() % 4) out.push_back('='); + return out; +} + +IAsyncAction logLastError(LPCTSTR errorTitle) +{ + LPVOID msgBuf; + DWORD errorCode = GetLastError(); + + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + errorCode, + 0, + (LPTSTR)&msgBuf, + 0, + NULL); + + wstringstream msgStrm; + wstring msg; + msgStrm << (LPCTSTR)msgBuf; + LocalFree(msgBuf); + getline(msgStrm, msg, L'\r'); + + AppCenter::trackError(errorCode, to_string(msg), wcscmp(errorTitle, L"OnUnhandledException: ") == 0); + + if (logFile != nullptr) + { + SYSTEMTIME systemTime; + GetSystemTime(&systemTime); + TCHAR timeStr[MAX_TIME_STR]; + GetTimeFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, NULL, timeStr, MAX_TIME_STR); + TCHAR dateStr[MAX_DATE_STR]; + GetDateFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, NULL, dateStr, MAX_DATE_STR, NULL); + wstringstream debugMsg; + debugMsg << dateStr << " " << timeStr << " " << "[" << "Error" << "]" << " " << "[" << "Error Code: " << errorCode << "]" << " " << errorTitle << msg << endl; + + co_await PathIO::AppendTextAsync(logFile.Path(), debugMsg.str().c_str()); + } +} + +fire_and_forget initializeLogging(LPCTSTR trailStr) +{ + auto localFolder = ApplicationData::Current().LocalFolder(); + auto logFolder = co_await localFolder.CreateFolderAsync(L"Logs", CreationCollisionOption::OpenIfExists); + logFile = co_await logFolder.CreateFileAsync(to_hstring(getTimeStamp("%Y%m%dT%H%M%S")) + to_hstring(trailStr), CreationCollisionOption::OpenIfExists); +} \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/elevated.cpp b/src/Notepads.DesktopExtension/elevated.cpp new file mode 100644 index 000000000..e5b37a78c --- /dev/null +++ b/src/Notepads.DesktopExtension/elevated.cpp @@ -0,0 +1,131 @@ +#include "pch.h" + +using namespace std; +using namespace winrt; +using namespace Windows::ApplicationModel; +using namespace Windows::Foundation; +using namespace Windows::Storage; + +constexpr int PIPE_READ_BUFFER = MAX_PATH + 240; + +DWORD sessionId; + +IInspectable readSettingsKey(hstring key) +{ + return ApplicationData::Current().LocalSettings().Values().TryLookup(key); +} + +hstring packageSid = unbox_value_or(readSettingsKey(PackageSidStr), L""); + +DWORD WINAPI saveFileFromPipeData(LPVOID param) +{ + setExceptionHandling(); + + LPCSTR result = "Failed"; + + wstringstream pipeName; + pipeName << "\\\\.\\pipe\\Sessions\\" << sessionId << "\\AppContainerNamedObjects\\" << packageSid.c_str() << "\\" << Package::Current().Id().FamilyName().c_str() << "\\" << AdminPipeConnectionNameStr; + + HANDLE hPipe = INVALID_HANDLE_VALUE; + while (hPipe == INVALID_HANDLE_VALUE) + { + Sleep(50); + if (WaitNamedPipe(pipeName.str().c_str(), NMPWAIT_WAIT_FOREVER)) + { + hPipe = CreateFile(pipeName.str().c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + } + } + + CreateThread(NULL, 0, saveFileFromPipeData, NULL, 0, NULL); + + char readBuffer[PIPE_READ_BUFFER] = { 0 }; + string pipeDataStr; + DWORD byteRead; + do + { + if (ReadFile(hPipe, readBuffer, (PIPE_READ_BUFFER - 1) * sizeof(char), &byteRead, NULL)) + { + pipeDataStr.append(readBuffer); + fill(begin(readBuffer), end(readBuffer), '\0'); + } + } while (byteRead >= (PIPE_READ_BUFFER - 1) * sizeof(char)); + + // Need to cnvert pipe data string to UTF-16 to properly read unicode characters + wstring pipeDataWstr; + int convertResult = MultiByteToWideChar(CP_UTF8, 0, pipeDataStr.c_str(), (int)strlen(pipeDataStr.c_str()), NULL, 0); + if (convertResult > 0) + { + pipeDataWstr.resize(convertResult); + MultiByteToWideChar(CP_UTF8, 0, pipeDataStr.c_str(), (int)pipeDataStr.size(), &pipeDataWstr[0], (int)pipeDataWstr.size()); + } + wstringstream pipeData(pipeDataWstr); + + wstring filePath; + wstring memoryMapId; + wstring dataArrayLengthStr; + getline(pipeData, filePath, L'|'); + getline(pipeData, memoryMapId, L'|'); + getline(pipeData, dataArrayLengthStr); + + int dataArrayLength = stoi(dataArrayLengthStr); + wstringstream memoryMapName; + memoryMapName << "AppContainerNamedObjects\\" << packageSid.c_str() << "\\" << memoryMapId; + + HANDLE hMemory = OpenFileMapping(FILE_MAP_READ, FALSE, memoryMapName.str().c_str()); + if (hMemory) + { + LPVOID mapView = MapViewOfFile(hMemory, FILE_MAP_READ, 0, 0, dataArrayLength); + if (mapView) + { + HANDLE hFile = CreateFile( + filePath.c_str(), + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + TRUNCATE_EXISTING, + 0, + NULL); + + if (hFile) + { + DWORD byteWrote; + if (WriteFile(hFile, mapView, dataArrayLength, &byteWrote, NULL) && FlushFileBuffers(hFile)) + { + result = "Success"; + } + + CloseHandle(hFile); + } + + CloseHandle(mapView); + } + + CloseHandle(hMemory); + } + + if (WriteFile(hPipe, result, strlen(result) * sizeof(char), NULL, NULL)) FlushFileBuffers(hPipe); + + CloseHandle(hPipe); + + if (strcmp(result, "Success") == 0) + { + printDebugMessage(L"Successfully wrote to", filePath.c_str()); + } + else + { + printDebugMessage(L"Failed to write to", filePath.c_str()); + } + printDebugMessage(L"Waiting on uwp app to send data."); + + return 0; +} + +void initializeAdminService() +{ + ProcessIdToSessionId(GetCurrentProcessId(), &sessionId); + + printDebugMessage(L"Successfully started Adminstrator Extension."); + printDebugMessage(L"Waiting on uwp app to send data."); + + CreateThread(NULL, 0, saveFileFromPipeData, NULL, 0, NULL); +} \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/extension.cpp b/src/Notepads.DesktopExtension/extension.cpp new file mode 100644 index 000000000..5250b4975 --- /dev/null +++ b/src/Notepads.DesktopExtension/extension.cpp @@ -0,0 +1,102 @@ +#include "pch.h" + +using namespace winrt; +using namespace Windows::ApplicationModel; +using namespace Windows::ApplicationModel::AppService; +using namespace Windows::Foundation; +using namespace Windows::Foundation::Collections; + +HANDLE appExitJob = NULL; + +AppServiceConnection interopServiceConnection = { 0 }; + +fire_and_forget launchElevatedProcess() +{ + TCHAR fileName[MAX_PATH]; + GetModuleFileName(NULL, fileName, MAX_PATH); + + SHELLEXECUTEINFO shExInfo = { 0 }; + shExInfo.cbSize = sizeof(shExInfo); + shExInfo.fMask = SEE_MASK_NOCLOSEPROCESS; + shExInfo.hwnd = 0; + shExInfo.lpVerb = L"runas"; + shExInfo.lpFile = fileName; + shExInfo.lpParameters = L""; + shExInfo.lpDirectory = 0; + shExInfo.nShow = SW_SHOW; + shExInfo.hInstApp = 0; + + auto message = ValueSet(); + message.Insert(InteropCommandLabel, box_value(CreateElevetedExtensionCommandStr)); + if (ShellExecuteEx(&shExInfo)) + { + // Create Job to close child process when parent exits/crashes. + if (appExitJob) CloseHandle(appExitJob); + appExitJob = CreateJobObject(NULL, NULL); + JOBOBJECT_EXTENDED_LIMIT_INFORMATION info = { 0 }; + info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + SetInformationJobObject(appExitJob, JobObjectExtendedLimitInformation, &info, sizeof(info)); + AssignProcessToJobObject(appExitJob, shExInfo.hProcess); + + message.Insert(InteropCommandAdminCreatedLabel, box_value(true)); + printDebugMessage(L"Adminstrator Extension has been launched."); + } + else + { + message.Insert(InteropCommandAdminCreatedLabel, box_value(false)); + printDebugMessage(L"User canceled launching of Adminstrator Extension."); + } + co_await interopServiceConnection.SendMessageAsync(message); +} + +void onConnectionServiceRequestRecieved(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) +{ + // Get a deferral because we use an awaitable API below to respond to the message + // and we don't want this call to get canceled while we are waiting. + auto messageDeferral = args.GetDeferral(); + setExceptionHandling(); + + auto message = args.Request().Message(); + if (!message.HasKey(InteropCommandLabel)) return; + + auto command = unbox_value_or(message.TryLookup(InteropCommandLabel), L""); + if (command == CreateElevetedExtensionCommandStr) + { + launchElevatedProcess(); + } + else if (command == ExitAppCommandStr) + { + exitApp(); + } + + messageDeferral.Complete(); +} + +void onConnectionServiceClosed(AppServiceConnection sender, AppServiceClosedEventArgs args) +{ + exitApp(); +} + +fire_and_forget initializeInteropService() +{ + printDebugMessage(L"Successfully started Desktop Extension."); + + interopServiceConnection = AppServiceConnection(); + interopServiceConnection.AppServiceName(InteropServiceName); + interopServiceConnection.PackageFamilyName(Package::Current().Id().FamilyName()); + + interopServiceConnection.RequestReceived(onConnectionServiceRequestRecieved); + interopServiceConnection.ServiceClosed(onConnectionServiceClosed); + + auto status = co_await interopServiceConnection.OpenAsync(); + if (status != AppServiceConnectionStatus::Success) + { + exitApp(); + } + + auto message = ValueSet(); + message.Insert(InteropCommandLabel, box_value(RegisterExtensionCommandStr)); + co_await interopServiceConnection.SendMessageAsync(message); + + printDebugMessage(L"Successfully created App Service."); +} \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index 16e596d8b..af3d26647 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -2,27 +2,12 @@ using namespace std; using namespace winrt; -using namespace Windows::ApplicationModel; -using namespace Windows::ApplicationModel::AppService; -using namespace Windows::Foundation; -using namespace Windows::Foundation::Collections; -using namespace Windows::Storage; constexpr LPCTSTR DesktopExtensionMutexName = L"DesktopExtensionMutexName"; constexpr LPCTSTR AdminExtensionMutexName = L"AdminExtensionMutexName"; -constexpr int PIPE_READ_BUFFER = MAX_PATH + 240; -constexpr int MAX_TIME_STR = 10; -constexpr int MAX_DATE_STR = 20; - HANDLE appExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL); -HANDLE appExitJob = NULL; - -DWORD sessionId; - -AppServiceConnection interopServiceConnection = { 0 }; - -StorageFile logFile = nullptr; +extern HANDLE appExitJob; int releaseResources() { @@ -36,57 +21,6 @@ void exitApp() SetEvent(appExitEvent); } -void printDebugMessage(LPCTSTR message, DWORD sleepTime = 0) -{ -#ifdef _DEBUG - wcout << message << endl; - Sleep(sleepTime); -#endif -} - -void printDebugMessage(LPCTSTR message, LPCTSTR parameter, DWORD sleepTime = 0) -{ -#ifdef _DEBUG - wcout << message << " \"" << parameter << "\"" << endl; - Sleep(sleepTime); -#endif -} - -IAsyncAction logLastError(LPCTSTR errorTitle) -{ - if (logFile != nullptr) - { - LPVOID msgBuf; - DWORD errorCode = GetLastError(); - - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - errorCode, - 0, - (LPTSTR)&msgBuf, - 0, - NULL); - - wstringstream msgStrm; - wstring msg; - msgStrm << (LPCTSTR)msgBuf; - LocalFree(msgBuf); - getline(msgStrm, msg, L'\r'); - - SYSTEMTIME systemTime; - GetSystemTime(&systemTime); - TCHAR timeStr[MAX_TIME_STR]; - GetTimeFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, NULL, timeStr, MAX_TIME_STR); - TCHAR dateStr[MAX_DATE_STR]; - GetDateFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, NULL, dateStr, MAX_DATE_STR, NULL); - wstringstream debugMsg; - debugMsg << dateStr << " " << timeStr << " " << "[" << "Error" << "]" << " " << "[" << "Error Code: " << errorCode << "]" << " " << errorTitle << msg << endl; - - co_await PathIO::AppendTextAsync(logFile.Path(), debugMsg.str().c_str()); - } -} - void onUnhandledException() { logLastError(L"OnUnhandledException: ").get(); @@ -105,230 +39,6 @@ void setExceptionHandling() set_unexpected(onUnexpectedException); } -IInspectable readSettingsKey(hstring key) -{ - return ApplicationData::Current().LocalSettings().Values().TryLookup(key); -} - -hstring packageSid = unbox_value_or(readSettingsKey(PackageSidStr), L""); - -DWORD WINAPI saveFileFromPipeData(LPVOID param) -{ - setExceptionHandling(); - - LPCSTR result = "Failed"; - - wstringstream pipeName; - pipeName << "\\\\.\\pipe\\Sessions\\" << sessionId << "\\AppContainerNamedObjects\\"<< packageSid.c_str() << "\\" << Package::Current().Id().FamilyName().c_str() << "\\" << AdminPipeConnectionNameStr; - - HANDLE hPipe = INVALID_HANDLE_VALUE; - while (hPipe == INVALID_HANDLE_VALUE) - { - Sleep(50); - if (WaitNamedPipe(pipeName.str().c_str(), NMPWAIT_WAIT_FOREVER)) - { - hPipe = CreateFile(pipeName.str().c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); - } - } - - CreateThread(NULL, 0, saveFileFromPipeData, NULL, 0, NULL); - - char readBuffer[PIPE_READ_BUFFER] = { 0 }; - string pipeDataStr; - DWORD byteRead; - do - { - if (ReadFile(hPipe, readBuffer, (PIPE_READ_BUFFER - 1) * sizeof(char), &byteRead, NULL)) - { - pipeDataStr.append(readBuffer); - fill(begin(readBuffer), end(readBuffer), '\0'); - } - } while (byteRead >= (PIPE_READ_BUFFER - 1) * sizeof(char)); - - // Need to cnvert pipe data string to UTF-16 to properly read unicode characters - wstring pipeDataWstr; - int convertResult = MultiByteToWideChar(CP_UTF8, 0, pipeDataStr.c_str(), (int)strlen(pipeDataStr.c_str()), NULL, 0); - if (convertResult > 0) - { - pipeDataWstr.resize(convertResult); - MultiByteToWideChar(CP_UTF8, 0, pipeDataStr.c_str(), (int)pipeDataStr.size(), &pipeDataWstr[0], (int)pipeDataWstr.size()); - } - wstringstream pipeData(pipeDataWstr); - - wstring filePath; - wstring memoryMapId; - wstring dataArrayLengthStr; - getline(pipeData, filePath, L'|'); - getline(pipeData, memoryMapId, L'|'); - getline(pipeData, dataArrayLengthStr); - - int dataArrayLength = stoi(dataArrayLengthStr); - wstringstream memoryMapName; - memoryMapName << "AppContainerNamedObjects\\" << packageSid.c_str() << "\\" << memoryMapId; - - HANDLE hMemory = OpenFileMapping(FILE_MAP_READ, FALSE, memoryMapName.str().c_str()); - if (hMemory) - { - LPVOID mapView = MapViewOfFile(hMemory, FILE_MAP_READ, 0, 0, dataArrayLength); - if (mapView) - { - HANDLE hFile = CreateFile( - filePath.c_str(), - GENERIC_READ | GENERIC_WRITE, - 0, - NULL, - TRUNCATE_EXISTING, - 0, - NULL); - - if (hFile) - { - DWORD byteWrote; - if (WriteFile(hFile, mapView, dataArrayLength, &byteWrote, NULL) && FlushFileBuffers(hFile)) - { - result = "Success"; - } - - CloseHandle(hFile); - } - - CloseHandle(mapView); - } - - CloseHandle(hMemory); - } - - if (WriteFile(hPipe, result, strlen(result) * sizeof(char), NULL, NULL)) FlushFileBuffers(hPipe); - - CloseHandle(hPipe); - - if (strcmp(result, "Success") == 0) - { - printDebugMessage(L"Successfully wrote to", filePath.c_str()); - } - else - { - printDebugMessage(L"Failed to write to", filePath.c_str()); - } - printDebugMessage(L"Waiting on uwp app to send data."); - - return 0; -} - -void initializeAdminService() -{ - printDebugMessage(L"Successfully started Adminstrator Extension."); - printDebugMessage(L"Waiting on uwp app to send data."); - - CreateThread(NULL, 0, saveFileFromPipeData, NULL, 0, NULL); -} - -fire_and_forget launchElevatedProcess() -{ - TCHAR fileName[MAX_PATH]; - GetModuleFileName(NULL, fileName, MAX_PATH); - - SHELLEXECUTEINFO shExInfo = { 0 }; - shExInfo.cbSize = sizeof(shExInfo); - shExInfo.fMask = SEE_MASK_NOCLOSEPROCESS; - shExInfo.hwnd = 0; - shExInfo.lpVerb = L"runas"; - shExInfo.lpFile = fileName; - shExInfo.lpParameters = L""; - shExInfo.lpDirectory = 0; - shExInfo.nShow = SW_SHOW; - shExInfo.hInstApp = 0; - - auto message = ValueSet(); - message.Insert(InteropCommandLabel, box_value(CreateElevetedExtensionCommandStr)); - if (ShellExecuteEx(&shExInfo)) - { - // Create Job to close child process when parent exits/crashes. - if (appExitJob) CloseHandle(appExitJob); - appExitJob = CreateJobObject(NULL, NULL); - JOBOBJECT_EXTENDED_LIMIT_INFORMATION info = { 0 }; - info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; - SetInformationJobObject(appExitJob, JobObjectExtendedLimitInformation, &info, sizeof(info)); - AssignProcessToJobObject(appExitJob, shExInfo.hProcess); - - message.Insert(InteropCommandAdminCreatedLabel, box_value(true)); - printDebugMessage(L"Adminstrator Extension has been launched."); - } - else - { - message.Insert(InteropCommandAdminCreatedLabel, box_value(false)); - printDebugMessage(L"User canceled launching of Adminstrator Extension."); - } - co_await interopServiceConnection.SendMessageAsync(message); -} - -void onConnectionServiceRequestRecieved(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) -{ - // Get a deferral because we use an awaitable API below to respond to the message - // and we don't want this call to get canceled while we are waiting. - auto messageDeferral = args.GetDeferral(); - setExceptionHandling(); - - auto message = args.Request().Message(); - if (!message.HasKey(InteropCommandLabel)) return; - - auto command = unbox_value_or(message.TryLookup(InteropCommandLabel), L""); - if (command == CreateElevetedExtensionCommandStr) - { - launchElevatedProcess(); - } - else if (command == ExitAppCommandStr) - { - exitApp(); - } - - messageDeferral.Complete(); -} - -void onConnectionServiceClosed(AppServiceConnection sender, AppServiceClosedEventArgs args) -{ - exitApp(); -} - -fire_and_forget initializeInteropService() -{ - printDebugMessage(L"Successfully started Desktop Extension."); - - interopServiceConnection = AppServiceConnection(); - interopServiceConnection.AppServiceName(InteropServiceName); - interopServiceConnection.PackageFamilyName(Package::Current().Id().FamilyName()); - - interopServiceConnection.RequestReceived(onConnectionServiceRequestRecieved); - interopServiceConnection.ServiceClosed(onConnectionServiceClosed); - - auto status = co_await interopServiceConnection.OpenAsync(); - if (status != AppServiceConnectionStatus::Success) - { - exitApp(); - } - - auto message = ValueSet(); - message.Insert(InteropCommandLabel, box_value(RegisterExtensionCommandStr)); - co_await interopServiceConnection.SendMessageAsync(message); - - printDebugMessage(L"Successfully created App Service."); -} - -fire_and_forget initializeLogging(LPCTSTR trailStr) -{ - auto localFolder = ApplicationData::Current().LocalFolder(); - auto logFolder = co_await localFolder.CreateFolderAsync(L"Logs", CreationCollisionOption::OpenIfExists); - SYSTEMTIME systemTime; - GetSystemTime(&systemTime); - TCHAR timeStr[MAX_TIME_STR]; - GetTimeFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, L"THHmmss", timeStr, MAX_TIME_STR); - TCHAR dateStr[MAX_DATE_STR]; - GetDateFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, L"yyyyMMdd", dateStr, MAX_DATE_STR, NULL); - wstringstream logFilePath; - logFilePath << dateStr << timeStr << trailStr; - logFile = co_await logFolder.CreateFileAsync(logFilePath.str(), CreationCollisionOption::OpenIfExists); -} - bool isElevetedProcessLaunchRequested() { bool result = false; @@ -398,6 +108,8 @@ int main() _onexit(releaseResources); init_apartment(); + AppCenter::start(); + AppCenter::trackError(6, "Test message", true); if (isElevatedProcess()) { @@ -407,7 +119,6 @@ int main() initializeLogging(L"-elevated-extension.log"); #endif - ProcessIdToSessionId(GetCurrentProcessId(), &sessionId); initializeAdminService(); } else diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h index 5c2a1f6ed..7538f7218 100644 --- a/src/Notepads.DesktopExtension/pch.h +++ b/src/Notepads.DesktopExtension/pch.h @@ -1,17 +1,24 @@ #pragma once #pragma comment(lib, "shell32") -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include "iostream" +#include "sstream" +#include "Windows.h" +#include "shellapi.h" +#include "winrt/Windows.ApplicationModel.h" +#include "winrt/Windows.ApplicationModel.AppService.h" +#include "winrt/Windows.Foundation.h" +#include "winrt/Windows.Foundation.Collections.h" +#include "winrt/Windows.Security.ExchangeActiveSyncProvisioning.h" +#include "winrt/Windows.Storage.h" +#include "winrt/Windows.System.h" +#include "winrt/Windows.System.Profile.h" +#include "curl/curl.h" // These values depend upon constant fields described in ..\Notepads\Settings\SettingsKey.cs. -// Changing value in one place require change in another. +// Changing value in one place require changing variable with similar name in another. +///////////////////////////////////////////////////////////////////////////////////////////// +constexpr LPCTSTR AppCenterSecret = NULL; +constexpr LPCTSTR AppCenterInstallIdStr = L"AppCenterInstallIdStr"; constexpr LPCTSTR InteropServiceName = L"DesktopExtensionServiceConnection"; constexpr LPCTSTR PackageSidStr = L"PackageSidStr"; constexpr LPCTSTR AdminPipeConnectionNameStr = L"NotepadsAdminWritePipe"; @@ -19,4 +26,38 @@ constexpr LPCTSTR InteropCommandLabel = L"Command"; constexpr LPCTSTR InteropCommandAdminCreatedLabel = L"AdminCreated"; constexpr LPCTSTR RegisterExtensionCommandStr = L"RegisterExtension"; constexpr LPCTSTR CreateElevetedExtensionCommandStr = L"CreateElevetedExtension"; -constexpr LPCTSTR ExitAppCommandStr = L"ExitApp"; \ No newline at end of file +constexpr LPCTSTR ExitAppCommandStr = L"ExitApp"; +///////////////////////////////////////////////////////////////////////////////////////////// + +bool isElevatedProcess(); +void setExceptionHandling(); +void exitApp(); + +void printDebugMessage(LPCTSTR message, DWORD sleepTime = 0); +void printDebugMessage(LPCTSTR message, LPCTSTR parameter, DWORD sleepTime = 0); +std::string getTimeStamp(); +std::string getTimeStamp(const char* format); +std::string to_string(winrt::Windows::System::ProcessorArchitecture arch); +std::string base64_encode(const std::string& in); + +winrt::fire_and_forget initializeInteropService(); +winrt::fire_and_forget launchElevatedProcess(); + +void initializeAdminService(); +winrt::Windows::Foundation::IInspectable readSettingsKey(winrt::hstring key); + +winrt::Windows::Foundation::IAsyncAction logLastError(LPCTSTR errorTitle); +winrt::fire_and_forget initializeLogging(LPCTSTR trailStr); + +namespace AppCenter +{ + namespace + { + static std::string launchTimeStamp; + static char* appCenterJSON; + static struct curl_slist* headerList; + } + + void start(); + void trackError(DWORD errorCode, std::string message, bool isFatal); +} \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/resource.h b/src/Notepads.DesktopExtension/resource.h index 17f3b0833..60f181539 100644 --- a/src/Notepads.DesktopExtension/resource.h +++ b/src/Notepads.DesktopExtension/resource.h @@ -1,6 +1,9 @@ //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by AssemblyInfo.rc +// +#define APPCENTER_JSON 101 +#define JSONFILE 256 // Next default values for new objects // @@ -9,6 +12,6 @@ #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 +#define _APS_NEXT_SYMED_VALUE 103 #endif #endif diff --git a/src/Notepads.Package/Package.appxmanifest b/src/Notepads.Package/Package.appxmanifest index d18c61c92..6f86ab73c 100644 --- a/src/Notepads.Package/Package.appxmanifest +++ b/src/Notepads.Package/Package.appxmanifest @@ -16,7 +16,7 @@ + Version="1.4.2.0" /> diff --git a/src/Notepads/App.xaml.cs b/src/Notepads/App.xaml.cs index 9a9082b85..41bc7623e 100644 --- a/src/Notepads/App.xaml.cs +++ b/src/Notepads/App.xaml.cs @@ -49,6 +49,8 @@ public App() InitializeComponent(); Suspending += OnSuspending; + + DesktopExtensionService.InitializeDesktopExtension(); } /// diff --git a/src/Notepads/Program.cs b/src/Notepads/Program.cs index 7b035b65e..545ec65ae 100644 --- a/src/Notepads/Program.cs +++ b/src/Notepads/Program.cs @@ -46,8 +46,6 @@ static void Main(string[] args) InstanceHandlerMutex.Close(); } - OpenDesktopExtension(); - if (activatedArgs is FileActivatedEventArgs) { RedirectOrCreateNewInstance(); @@ -155,16 +153,5 @@ private static AppInstance GetLastActiveInstance() // activeInstance might be closed already, let's return the first instance in this case return instances.FirstOrDefault(); } - - private static async void OpenDesktopExtension() - { - if (ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0) && - !new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) - { - ApplicationSettingsStore.Write(SettingsKey.PackageSidStr, WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host.ToUpper()); - - await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); - } - } } } \ No newline at end of file diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index ce645731e..21dbc5514 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -1,5 +1,6 @@ namespace Notepads.Services { + using Microsoft.AppCenter; using Notepads.Extensions; using Notepads.Settings; using System; @@ -14,6 +15,7 @@ using Windows.ApplicationModel.Resources; using Windows.Foundation.Collections; using Windows.Foundation.Metadata; + using Windows.Security.Authentication.Web; using Windows.UI.ViewManagement; using Windows.UI.Xaml; @@ -32,6 +34,17 @@ public static class DesktopExtensionService !new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); private static readonly ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView(); + public static async void InitializeDesktopExtension() + { + if (!ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0) || + new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) return; + + ApplicationSettingsStore.Write(SettingsKey.PackageSidStr, WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host.ToUpper()); + var appcenterInstallidstr = (await AppCenter.GetInstallIdAsync())?.ToString(); + ApplicationSettingsStore.Write(SettingsKey.AppCenterInstallIdStr, appcenterInstallidstr); + await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); + } + public static async Task Initialize() { if (!ShouldUseDesktopExtension) return false; diff --git a/src/Notepads/Settings/SettingsKey.cs b/src/Notepads/Settings/SettingsKey.cs index 632979501..b02a32b3b 100644 --- a/src/Notepads/Settings/SettingsKey.cs +++ b/src/Notepads/Settings/SettingsKey.cs @@ -38,9 +38,10 @@ internal static class SettingsKey // Interop related // These values depend upon constant fields described in ..\Notepads.DesktopExtension\pch.h. - // Changing value in one place require change in another. + // Changing value in one place require changing variable with similar name in another. internal const string AppCenterSecret = null; - internal const string InteropServiceName = "DesktopExtensionServiceConnection"; // Keep this same as AppSeviceName in manifest + internal const string AppCenterInstallIdStr = "AppCenterInstallIdStr"; + internal const string InteropServiceName = "DesktopExtensionServiceConnection"; // Keep this same as AppSeviceName value in manifest internal const string PackageSidStr = "PackageSidStr"; internal const string AdminPipeConnectionNameStr = "NotepadsAdminWritePipe"; internal const string InteropCommandAdminCreatedLabel = "AdminCreated"; diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs index e7c3cb10b..339aa01ce 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs @@ -285,19 +285,22 @@ private async void App_EnteredBackground(object sender, Windows.ApplicationModel { var deferral = e.GetDeferral(); + DesktopExtensionService.InteropServiceConnection?.Dispose(); + if (AppSettingsService.IsSessionSnapshotEnabled) { await SessionManager.SaveSessionAsync(); } - DesktopExtensionService.InteropServiceConnection.Dispose(); deferral.Complete(); } private async void App_LeavingBackground(object sender, LeavingBackgroundEventArgs e) { - await DesktopExtensionService.Initialize(); - await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); + if (await DesktopExtensionService.Initialize()) + { + await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); + } } public void ExecuteProtocol(Uri uri) From 68a368dc2cb596768856e9310db19aeb3cbbad9d Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Tue, 8 Dec 2020 15:53:55 +0530 Subject: [PATCH 093/181] Fix github workflow. --- .github/workflows/Build.yml | 2 +- azure-pipelines.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 2f9b60597..a1983cf61 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -38,7 +38,7 @@ jobs: - name: Restore vcpkg packages run: | - $VCPKG_ROOT/vcpkg install rapidjson:arm-windows rapidjson:arm64-windows rapidjson:x86-windows rapidjson:x64-windows curl:arm-windows curl:arm64-windows curl:x86-windows curl:x64-windows + $VCPKG_ROOT\vcpkg install rapidjson:arm-windows rapidjson:arm64-windows rapidjson:x86-windows rapidjson:x64-windows curl:arm-windows curl:arm64-windows curl:x86-windows curl:x64-windows - name: Build run: | diff --git a/azure-pipelines.yml b/azure-pipelines.yml index d7a6ee905..d5e0416b4 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -23,7 +23,7 @@ steps: inputs: targetType: 'inline' script: | - $VCPKG_ROOT/vcpkg install rapidjson:arm-windows rapidjson:arm64-windows rapidjson:x86-windows rapidjson:x64-windows curl:arm-windows curl:arm64-windows curl:x86-windows curl:x64-windows + $VCPKG_ROOT\vcpkg install rapidjson:arm-windows rapidjson:arm64-windows rapidjson:x86-windows rapidjson:x64-windows curl:arm-windows curl:arm64-windows curl:x86-windows curl:x64-windows failOnStderr: true - task: MSBuild@1 From 7bfc5f29251a3985e69e9a1244a728bb2d2d9d52 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Tue, 8 Dec 2020 23:35:39 +0530 Subject: [PATCH 094/181] code refactor. --- src/Notepads.DesktopExtension/appcenter.cpp | 18 ++++++++---------- src/Notepads.DesktopExtension/appcenter.json | 7 +------ src/Notepads.DesktopExtension/main.cpp | 1 - 3 files changed, 9 insertions(+), 17 deletions(-) diff --git a/src/Notepads.DesktopExtension/appcenter.cpp b/src/Notepads.DesktopExtension/appcenter.cpp index e1b81b340..b046ee60f 100644 --- a/src/Notepads.DesktopExtension/appcenter.cpp +++ b/src/Notepads.DesktopExtension/appcenter.cpp @@ -1,3 +1,4 @@ +// Documentation is at https://docs.microsoft.com/en-us/appcenter/diagnostics/upload-crashes #include "pch.h" #include "resource.h" #include "combaseapi.h" @@ -5,6 +6,8 @@ #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" +#define APPCENTER_ENDPOINT "https://in.appcenter.ms/logs?Api-Version=1.0.0" + using namespace std; using namespace rapidjson; using namespace winrt; @@ -30,13 +33,13 @@ void AppCenter::start() headerList = curl_slist_append(headerList, "Content-Type: application/json"); stringstream appSecretHeader; - appSecretHeader << "app-secret: " << AppCenterSecret; + appSecretHeader << "app-secret: " << to_string(AppCenterSecret); headerList = curl_slist_append(headerList, appSecretHeader.str().c_str()); hstring installId = unbox_value_or(readSettingsKey(AppCenterInstallIdStr), L""); if (installId == L"") return; stringstream installIdHeader; - installIdHeader << "install-id: " << installId.c_str(); + installIdHeader << "install-id: " << to_string(installId); headerList = curl_slist_append(headerList, installIdHeader.str().c_str()); } @@ -114,7 +117,6 @@ void AppCenter::trackError(DWORD errorCode, string message, bool isFatal) logReports[i]["errorThreadId"].SetInt(GetCurrentThreadId()); logReports[i]["exception"]["message"].SetString(message.c_str(), errorReportForm.GetAllocator()); - logReports[i]["exception"]["innerExceptions"][0]["type"].SetString(exceptionProp.str().c_str(), errorReportForm.GetAllocator()); logReports[i]["properties"]["exception"].SetString(exceptionProp.str().c_str(), errorReportForm.GetAllocator()); logReports[i]["properties"]["message"].SetString(message.c_str(), errorReportForm.GetAllocator()); @@ -138,12 +140,10 @@ void AppCenter::trackError(DWORD errorCode, string message, bool isFatal) Writer writer(errorReport); errorReportForm.Accept(writer); - cout << errorReport.GetString() << endl; - - /*CURL* curl = curl_easy_init(); + CURL* curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerList); - curl_easy_setopt(curl, CURLOPT_URL, "https://in.appcenter.ms/logs?Api-Version=1.0.0"); + curl_easy_setopt(curl, CURLOPT_URL, APPCENTER_ENDPOINT); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, errorReport.GetString()); #ifdef _DEBUG @@ -153,8 +153,6 @@ void AppCenter::trackError(DWORD errorCode, string message, bool isFatal) CURLcode res = curl_easy_perform(curl); if (res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); - else - fprintf(stderr, "curl_easy_perform() succeded: %s\n", curl_easy_strerror(res)); } - curl_easy_cleanup(curl);*/ + curl_easy_cleanup(curl); } \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/appcenter.json b/src/Notepads.DesktopExtension/appcenter.json index f975a4270..5ddc45d46 100644 --- a/src/Notepads.DesktopExtension/appcenter.json +++ b/src/Notepads.DesktopExtension/appcenter.json @@ -27,12 +27,7 @@ "exception": { "type": "Win32Exception", "message": "", - "stackTrace": "", - "innerExceptions": [ - { - "type": "" - } - ] + "stackTrace": "" }, "properties": { "exception": "", diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index af3d26647..4e8f8181e 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -109,7 +109,6 @@ int main() init_apartment(); AppCenter::start(); - AppCenter::trackError(6, "Test message", true); if (isElevatedProcess()) { From 6e3e8905a2e5a8aa9ba5a03966942839dcf85b10 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Wed, 9 Dec 2020 09:33:31 +0530 Subject: [PATCH 095/181] Fix workflow. --- .github/workflows/Build.yml | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index a1983cf61..880d68e7b 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -9,6 +9,7 @@ jobs: strategy: matrix: configuration: [Debug, Release] + platform: [x86, x64] env: Solution_Name: src\Notepads.sln Project_Path: src\Notepads.Package\Notepads.Package.wapproj @@ -31,20 +32,17 @@ jobs: run: nuget restore $env:Solution_Name # Restore from cache ,if cache-miss, download and build vcpkg: https://github.com/lukka/run-vcpkg - - name: Setup vcpkg + - name: Setup vcpkg and restore packages uses: lukka/run-vcpkg@v6.0 with: - setupOnly: true - - - name: Restore vcpkg packages - run: | - $VCPKG_ROOT\vcpkg install rapidjson:arm-windows rapidjson:arm64-windows rapidjson:x86-windows rapidjson:x64-windows curl:arm-windows curl:arm64-windows curl:x86-windows curl:x64-windows + vcpkgArguments: rapidjson:arm-windows rapidjson:arm64-windows rapidjson:x86-windows rapidjson:x64-windows curl:arm-windows curl:arm64-windows curl:x86-windows curl:x64-windows + vcpkgDirectory: ${{ runner.workspace }}/vcpkg/ - name: Build run: | msbuild $env:Project_Path /p:Configuration=$env:Configuration /p:UapAppxPackageBuildMode=$env:Appx_Package_Build_Mode /p:AppxBundle=$env:Appx_Bundle /p:AppxPackageSigningEnabled=false /p:AppxBundlePlatforms="$env:Appx_Bundle_Platforms" env: Appx_Bundle: Always - Appx_Bundle_Platforms: x86|x64 + Appx_Bundle_Platforms: ${{ matrix.platform }} Appx_Package_Build_Mode: StoreUpload Configuration: ${{ matrix.configuration }} From 236e63589c7e9e77fae3543fbf57ab648bdd32a6 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Wed, 9 Dec 2020 09:49:39 +0530 Subject: [PATCH 096/181] Fixed workflow. --- .github/workflows/Build.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 880d68e7b..adc096c6a 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -9,7 +9,6 @@ jobs: strategy: matrix: configuration: [Debug, Release] - platform: [x86, x64] env: Solution_Name: src\Notepads.sln Project_Path: src\Notepads.Package\Notepads.Package.wapproj @@ -43,6 +42,6 @@ jobs: msbuild $env:Project_Path /p:Configuration=$env:Configuration /p:UapAppxPackageBuildMode=$env:Appx_Package_Build_Mode /p:AppxBundle=$env:Appx_Bundle /p:AppxPackageSigningEnabled=false /p:AppxBundlePlatforms="$env:Appx_Bundle_Platforms" env: Appx_Bundle: Always - Appx_Bundle_Platforms: ${{ matrix.platform }} + Appx_Bundle_Platforms: x86|x64 Appx_Package_Build_Mode: StoreUpload Configuration: ${{ matrix.configuration }} From 0074b3909f27bff0b0d64f2e68a3e30a341b9dd6 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Wed, 9 Dec 2020 10:01:54 +0530 Subject: [PATCH 097/181] Fix workflow. --- .github/workflows/Build.yml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index adc096c6a..5e7edfef6 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -31,12 +31,16 @@ jobs: run: nuget restore $env:Solution_Name # Restore from cache ,if cache-miss, download and build vcpkg: https://github.com/lukka/run-vcpkg - - name: Setup vcpkg and restore packages + - name: Setup vcpkg uses: lukka/run-vcpkg@v6.0 with: - vcpkgArguments: rapidjson:arm-windows rapidjson:arm64-windows rapidjson:x86-windows rapidjson:x64-windows curl:arm-windows curl:arm64-windows curl:x86-windows curl:x64-windows + setupOnly: true vcpkgDirectory: ${{ runner.workspace }}/vcpkg/ + - name: Restore vcpkg packages + run: | + ${{ runner.workspace }}/vcpkg/vcpkg install rapidjson:arm-windows rapidjson:arm64-windows rapidjson:x86-windows rapidjson:x64-windows curl:arm-windows curl:arm64-windows curl:x86-windows curl:x64-windows + - name: Build run: | msbuild $env:Project_Path /p:Configuration=$env:Configuration /p:UapAppxPackageBuildMode=$env:Appx_Package_Build_Mode /p:AppxBundle=$env:Appx_Bundle /p:AppxPackageSigningEnabled=false /p:AppxBundlePlatforms="$env:Appx_Bundle_Platforms" From b958c49764181d451c705dc84c62ac34b571843a Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Wed, 9 Dec 2020 10:09:37 +0530 Subject: [PATCH 098/181] Fix workflow. --- .github/workflows/Build.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 5e7edfef6..a1983cf61 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -35,11 +35,10 @@ jobs: uses: lukka/run-vcpkg@v6.0 with: setupOnly: true - vcpkgDirectory: ${{ runner.workspace }}/vcpkg/ - name: Restore vcpkg packages run: | - ${{ runner.workspace }}/vcpkg/vcpkg install rapidjson:arm-windows rapidjson:arm64-windows rapidjson:x86-windows rapidjson:x64-windows curl:arm-windows curl:arm64-windows curl:x86-windows curl:x64-windows + $VCPKG_ROOT\vcpkg install rapidjson:arm-windows rapidjson:arm64-windows rapidjson:x86-windows rapidjson:x64-windows curl:arm-windows curl:arm64-windows curl:x86-windows curl:x64-windows - name: Build run: | From 03eaed92226874d96e728a93bad308e81f87ee68 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Wed, 9 Dec 2020 13:00:17 +0530 Subject: [PATCH 099/181] Fix workflow. --- .github/workflows/Build.yml | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index a1983cf61..51293d90a 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -31,14 +31,12 @@ jobs: run: nuget restore $env:Solution_Name # Restore from cache ,if cache-miss, download and build vcpkg: https://github.com/lukka/run-vcpkg - - name: Setup vcpkg + - name: Setup vcpkg and restore packages uses: lukka/run-vcpkg@v6.0 with: - setupOnly: true - - - name: Restore vcpkg packages - run: | - $VCPKG_ROOT\vcpkg install rapidjson:arm-windows rapidjson:arm64-windows rapidjson:x86-windows rapidjson:x64-windows curl:arm-windows curl:arm64-windows curl:x86-windows curl:x64-windows + vcpkgArguments: rapidjson:arm-windows rapidjson:arm64-windows rapidjson:x86-windows rapidjson:x64-windows curl:arm-windows curl:arm64-windows curl:x86-windows curl:x64-windows + vcpkgDirectory: ${{ runner.workspace }}/vcpkg/ + vcpkgGitCommitId: a2135fd97e834e83a705b1cff0d91a0e45a0fb00 - name: Build run: | From 4620473046c81a554cb1f38e14e27ffa51b6f33e Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Wed, 9 Dec 2020 22:03:28 +0530 Subject: [PATCH 100/181] Fix workflow. --- .github/workflows/Build.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 51293d90a..d4e4f7a78 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -38,6 +38,9 @@ jobs: vcpkgDirectory: ${{ runner.workspace }}/vcpkg/ vcpkgGitCommitId: a2135fd97e834e83a705b1cff0d91a0e45a0fb00 + - name: Integrate vcpkg with msbuild + run: ${{ runner.workspace }}/vcpkg/vcpkg integrate install + - name: Build run: | msbuild $env:Project_Path /p:Configuration=$env:Configuration /p:UapAppxPackageBuildMode=$env:Appx_Package_Build_Mode /p:AppxBundle=$env:Appx_Bundle /p:AppxPackageSigningEnabled=false /p:AppxBundlePlatforms="$env:Appx_Bundle_Platforms" From f415f70b070a581b0e21ad37ed3c11862a770f21 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 10 Dec 2020 09:28:36 +0530 Subject: [PATCH 101/181] Fix workflow. --- .github/workflows/Build.yml | 2 -- .gitmodules | 3 +++ vcpkg | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) create mode 100644 .gitmodules create mode 160000 vcpkg diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index d4e4f7a78..2587bbb69 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -35,8 +35,6 @@ jobs: uses: lukka/run-vcpkg@v6.0 with: vcpkgArguments: rapidjson:arm-windows rapidjson:arm64-windows rapidjson:x86-windows rapidjson:x64-windows curl:arm-windows curl:arm64-windows curl:x86-windows curl:x64-windows - vcpkgDirectory: ${{ runner.workspace }}/vcpkg/ - vcpkgGitCommitId: a2135fd97e834e83a705b1cff0d91a0e45a0fb00 - name: Integrate vcpkg with msbuild run: ${{ runner.workspace }}/vcpkg/vcpkg integrate install diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 000000000..fe07c999a --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "vcpkg"] + path = vcpkg + url = https://github.com/microsoft/vcpkg diff --git a/vcpkg b/vcpkg new file mode 160000 index 000000000..1d8728ae1 --- /dev/null +++ b/vcpkg @@ -0,0 +1 @@ +Subproject commit 1d8728ae1ba66ad94b344708cf8d0ace1a6330b8 From 1a652337b8f84e84bf86af7a958fb7f9abd37286 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 10 Dec 2020 09:51:33 +0530 Subject: [PATCH 102/181] Workflow fix. --- .github/workflows/Build.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 2587bbb69..e4291b208 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -35,6 +35,7 @@ jobs: uses: lukka/run-vcpkg@v6.0 with: vcpkgArguments: rapidjson:arm-windows rapidjson:arm64-windows rapidjson:x86-windows rapidjson:x64-windows curl:arm-windows curl:arm64-windows curl:x86-windows curl:x64-windows + vcpkgDirectory: ${{ runner.workspace }}/vcpkg/ - name: Integrate vcpkg with msbuild run: ${{ runner.workspace }}/vcpkg/vcpkg integrate install From fe4a0fdf0cad59bc2dcd340d18d709de81a15268 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 10 Dec 2020 12:22:10 +0530 Subject: [PATCH 103/181] Fix workflow. --- .github/workflows/Build.yml | 10 --------- azure-pipelines.yml | 7 ------ .../Notepads.DesktopExtension.vcxproj | 2 +- src/Notepads.DesktopExtension/build.ps1 | 22 +++++++++++++++++-- 4 files changed, 21 insertions(+), 20 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index e4291b208..b51181a5e 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -30,16 +30,6 @@ jobs: - name: Restore NuGet packages run: nuget restore $env:Solution_Name - # Restore from cache ,if cache-miss, download and build vcpkg: https://github.com/lukka/run-vcpkg - - name: Setup vcpkg and restore packages - uses: lukka/run-vcpkg@v6.0 - with: - vcpkgArguments: rapidjson:arm-windows rapidjson:arm64-windows rapidjson:x86-windows rapidjson:x64-windows curl:arm-windows curl:arm64-windows curl:x86-windows curl:x64-windows - vcpkgDirectory: ${{ runner.workspace }}/vcpkg/ - - - name: Integrate vcpkg with msbuild - run: ${{ runner.workspace }}/vcpkg/vcpkg integrate install - - name: Build run: | msbuild $env:Project_Path /p:Configuration=$env:Configuration /p:UapAppxPackageBuildMode=$env:Appx_Package_Build_Mode /p:AppxBundle=$env:Appx_Bundle /p:AppxPackageSigningEnabled=false /p:AppxBundlePlatforms="$env:Appx_Bundle_Platforms" diff --git a/azure-pipelines.yml b/azure-pipelines.yml index d5e0416b4..dc86a0b06 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -19,13 +19,6 @@ steps: inputs: restoreSolution: '$(solution)' -- task: PowerShell@2 - inputs: - targetType: 'inline' - script: | - $VCPKG_ROOT\vcpkg install rapidjson:arm-windows rapidjson:arm64-windows rapidjson:x86-windows rapidjson:x64-windows curl:arm-windows curl:arm64-windows curl:x86-windows curl:x64-windows - failOnStderr: true - - task: MSBuild@1 inputs: platform: 'x86' diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index 8d2a23fd9..96b16bf22 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -90,7 +90,7 @@ %(AdditionalOptions) /permissive- /bigobj - powershell -ExecutionPolicy Bypass $(ProjectDir)build.ps1 -project_dir $(ProjectDir) + powershell -ExecutionPolicy Bypass $(ProjectDir)build.ps1 -project_dir $(ProjectDir) -platform $(Platform) diff --git a/src/Notepads.DesktopExtension/build.ps1 b/src/Notepads.DesktopExtension/build.ps1 index 7217625c3..058bb1943 100644 --- a/src/Notepads.DesktopExtension/build.ps1 +++ b/src/Notepads.DesktopExtension/build.ps1 @@ -1,5 +1,6 @@ param ( - [string]$project_dir = $(throw "-project_dir= is required") + [string]$project_dir = $(throw "-project_dir= is required"), + [string]$platform = "x86" ) $project_dir = Resolve-Path $project_dir.TrimEnd("\") @@ -20,4 +21,21 @@ $appcenter_sdk_version = $appcenter_format.logs.device.sdkVersion[0] $sdk_target.Project.ItemGroup.PackageReference | ForEach-Object {if($_.Include -eq 'Microsoft.AppCenter.Crashes'){$appcenter_sdk_version = $_.Version}} $appcenter_format.logs.device | ForEach-Object {$_.sdkVersion = $appcenter_sdk_version} -$appcenter_format | ConvertTo-Json -depth 10| Set-Content $appcenter_file \ No newline at end of file +$appcenter_format | ConvertTo-Json -depth 10| Set-Content $appcenter_file + +# Set up vcpkg and packages +git submodule update --init --recursive + +$vcpkg_root_dir = "${project_dir}\..\..\vcpkg" + +$vcpkg_triplet = "${platform}-windows" +If ($platform -eq "Win32") { + $vcpkg_triplet = "x86-windows" +} + +If (!(Test-Path -Path "${vcpkg_root_dir}\vcpkg.exe")) { + & ${vcpkg_root_dir}\bootstrap-vcpkg.bat +} + +& ${vcpkg_root_dir}\vcpkg integrate install +& ${vcpkg_root_dir}\vcpkg install rapidjson curl --triplet=$vcpkg_triplet \ No newline at end of file From 3e81308f33b34e1e923d8622356544b41aeac57e Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 10 Dec 2020 16:15:26 +0530 Subject: [PATCH 104/181] Fix workflow. --- .github/workflows/Build.yml | 4 ++++ azure-pipelines.yml | 7 +++++++ setup-vcpkg.ps1 | 12 ++++++++++++ src/Notepads.DesktopExtension/build.ps1 | 7 +------ 4 files changed, 24 insertions(+), 6 deletions(-) create mode 100644 setup-vcpkg.ps1 diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index b51181a5e..6893d1595 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -12,6 +12,7 @@ jobs: env: Solution_Name: src\Notepads.sln Project_Path: src\Notepads.Package\Notepads.Package.wapproj + Vcpkg_Root: vcpkg runs-on: windows-latest steps: @@ -30,6 +31,9 @@ jobs: - name: Restore NuGet packages run: nuget restore $env:Solution_Name + - name: Setup vcpkg + run: .\setup-vcpkg.ps1 -vcpkg_root $env:Vcpkg_Root + - name: Build run: | msbuild $env:Project_Path /p:Configuration=$env:Configuration /p:UapAppxPackageBuildMode=$env:Appx_Package_Build_Mode /p:AppxBundle=$env:Appx_Bundle /p:AppxPackageSigningEnabled=false /p:AppxBundlePlatforms="$env:Appx_Bundle_Platforms" diff --git a/azure-pipelines.yml b/azure-pipelines.yml index dc86a0b06..5ca7c8312 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -19,6 +19,13 @@ steps: inputs: restoreSolution: '$(solution)' +- task: PowerShell@2 + inputs: + targetType: 'filePath' + filePath: '.\setup-vcpkg.ps1' + arguments: '-vcpkg_root $(system.defaultworkingdirectory)\vcpkg' + failOnStderr: true + - task: MSBuild@1 inputs: platform: 'x86' diff --git a/setup-vcpkg.ps1 b/setup-vcpkg.ps1 new file mode 100644 index 000000000..51ffae93c --- /dev/null +++ b/setup-vcpkg.ps1 @@ -0,0 +1,12 @@ +param ( + [string]$vcpkg_root = $(throw "-vcpkg_root= is required") +) + +git submodule update --init --recursive + +# Set up vcpkg +If (!(Test-Path -Path "${vcpkg_root}\vcpkg.exe")) { + & ${vcpkg_root}\bootstrap-vcpkg.bat +} + +& ${vcpkg_root}\vcpkg integrate install \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/build.ps1 b/src/Notepads.DesktopExtension/build.ps1 index 058bb1943..4ded2e530 100644 --- a/src/Notepads.DesktopExtension/build.ps1 +++ b/src/Notepads.DesktopExtension/build.ps1 @@ -24,8 +24,6 @@ $appcenter_format.logs.device | ForEach-Object {$_.sdkVersion = $appcenter_sdk_v $appcenter_format | ConvertTo-Json -depth 10| Set-Content $appcenter_file # Set up vcpkg and packages -git submodule update --init --recursive - $vcpkg_root_dir = "${project_dir}\..\..\vcpkg" $vcpkg_triplet = "${platform}-windows" @@ -33,9 +31,6 @@ If ($platform -eq "Win32") { $vcpkg_triplet = "x86-windows" } -If (!(Test-Path -Path "${vcpkg_root_dir}\vcpkg.exe")) { - & ${vcpkg_root_dir}\bootstrap-vcpkg.bat -} +& ${project_dir}\..\..\setup-vcpkg.ps1 -vcpkg_root ${vcpkg_root_dir} -& ${vcpkg_root_dir}\vcpkg integrate install & ${vcpkg_root_dir}\vcpkg install rapidjson curl --triplet=$vcpkg_triplet \ No newline at end of file From 34b36eeff0a9ec65fa65009566aa1895c92f3cfc Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 10 Dec 2020 17:44:00 +0530 Subject: [PATCH 105/181] Fix workflow. --- .github/workflows/Build.yml | 5 ++++- src/Notepads.DesktopExtension/build.ps1 | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 6893d1595..67594504e 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -32,7 +32,10 @@ jobs: run: nuget restore $env:Solution_Name - name: Setup vcpkg - run: .\setup-vcpkg.ps1 -vcpkg_root $env:Vcpkg_Root + run: | + git submodule update --init --recursive + $env:Vcpkg_Root\bootstrap-vcpkg.bat + $env:Vcpkg_Root\vcpkg integrate install - name: Build run: | diff --git a/src/Notepads.DesktopExtension/build.ps1 b/src/Notepads.DesktopExtension/build.ps1 index 4ded2e530..fa3b58d47 100644 --- a/src/Notepads.DesktopExtension/build.ps1 +++ b/src/Notepads.DesktopExtension/build.ps1 @@ -31,6 +31,6 @@ If ($platform -eq "Win32") { $vcpkg_triplet = "x86-windows" } -& ${project_dir}\..\..\setup-vcpkg.ps1 -vcpkg_root ${vcpkg_root_dir} +#& ${project_dir}\..\..\setup-vcpkg.ps1 -vcpkg_root ${vcpkg_root_dir} & ${vcpkg_root_dir}\vcpkg install rapidjson curl --triplet=$vcpkg_triplet \ No newline at end of file From e47cd29a293b74bb5194a7b638dda65899a2b70f Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 10 Dec 2020 17:51:15 +0530 Subject: [PATCH 106/181] Fix workflow. --- .github/workflows/Build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 67594504e..92900f638 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -34,8 +34,8 @@ jobs: - name: Setup vcpkg run: | git submodule update --init --recursive - $env:Vcpkg_Root\bootstrap-vcpkg.bat - $env:Vcpkg_Root\vcpkg integrate install + $env:Vcpkg_Root/bootstrap-vcpkg.bat + $env:Vcpkg_Root/vcpkg integrate install - name: Build run: | From 661751e4dbff83cc5fbfdbcf475bf58c899ad89a Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 10 Dec 2020 18:02:18 +0530 Subject: [PATCH 107/181] Fix workflow. --- .github/workflows/Build.yml | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 92900f638..8577e52d4 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -32,10 +32,7 @@ jobs: run: nuget restore $env:Solution_Name - name: Setup vcpkg - run: | - git submodule update --init --recursive - $env:Vcpkg_Root/bootstrap-vcpkg.bat - $env:Vcpkg_Root/vcpkg integrate install + run: powershell -ExecutionPolicy Bypass .\setup-vcpkg.ps1 -vcpkg_root $env:Vcpkg_Root - name: Build run: | From 5ecc8e85fd7ff4c871c12c2017ef0de2bafb210a Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 10 Dec 2020 20:20:48 +0530 Subject: [PATCH 108/181] Fix workflow. --- .github/workflows/Build.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 8577e52d4..5a1dc3f61 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -32,7 +32,10 @@ jobs: run: nuget restore $env:Solution_Name - name: Setup vcpkg - run: powershell -ExecutionPolicy Bypass .\setup-vcpkg.ps1 -vcpkg_root $env:Vcpkg_Root + run: | + git submodule update --init --recursive + vcpkg\bootstrap-vcpkg.bat + vcpkg\vcpkg integrate install - name: Build run: | From d00a40da3d4f00e3a2b29506a65d067845865497 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 10 Dec 2020 22:22:22 +0530 Subject: [PATCH 109/181] Fix workflow. --- .github/workflows/Build.yml | 7 ------- azure-pipelines.yml | 7 ------- .../Notepads.DesktopExtension.vcxproj | 7 ++++++- src/Notepads.DesktopExtension/build.ps1 | 4 +--- 4 files changed, 7 insertions(+), 18 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 5a1dc3f61..b51181a5e 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -12,7 +12,6 @@ jobs: env: Solution_Name: src\Notepads.sln Project_Path: src\Notepads.Package\Notepads.Package.wapproj - Vcpkg_Root: vcpkg runs-on: windows-latest steps: @@ -31,12 +30,6 @@ jobs: - name: Restore NuGet packages run: nuget restore $env:Solution_Name - - name: Setup vcpkg - run: | - git submodule update --init --recursive - vcpkg\bootstrap-vcpkg.bat - vcpkg\vcpkg integrate install - - name: Build run: | msbuild $env:Project_Path /p:Configuration=$env:Configuration /p:UapAppxPackageBuildMode=$env:Appx_Package_Build_Mode /p:AppxBundle=$env:Appx_Bundle /p:AppxPackageSigningEnabled=false /p:AppxBundlePlatforms="$env:Appx_Bundle_Platforms" diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 5ca7c8312..dc86a0b06 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -19,13 +19,6 @@ steps: inputs: restoreSolution: '$(solution)' -- task: PowerShell@2 - inputs: - targetType: 'filePath' - filePath: '.\setup-vcpkg.ps1' - arguments: '-vcpkg_root $(system.defaultworkingdirectory)\vcpkg' - failOnStderr: true - - task: MSBuild@1 inputs: platform: 'x86' diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index 96b16bf22..b36fe41f0 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -1,5 +1,5 @@ - + true @@ -147,6 +147,7 @@ + @@ -155,4 +156,8 @@ + + + + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/build.ps1 b/src/Notepads.DesktopExtension/build.ps1 index fa3b58d47..28e53bbe9 100644 --- a/src/Notepads.DesktopExtension/build.ps1 +++ b/src/Notepads.DesktopExtension/build.ps1 @@ -23,7 +23,7 @@ $appcenter_format.logs.device | ForEach-Object {$_.sdkVersion = $appcenter_sdk_v $appcenter_format | ConvertTo-Json -depth 10| Set-Content $appcenter_file -# Set up vcpkg and packages +# Set up vcpkg packages $vcpkg_root_dir = "${project_dir}\..\..\vcpkg" $vcpkg_triplet = "${platform}-windows" @@ -31,6 +31,4 @@ If ($platform -eq "Win32") { $vcpkg_triplet = "x86-windows" } -#& ${project_dir}\..\..\setup-vcpkg.ps1 -vcpkg_root ${vcpkg_root_dir} - & ${vcpkg_root_dir}\vcpkg install rapidjson curl --triplet=$vcpkg_triplet \ No newline at end of file From ce21e0cde00f4d9dc43c20f25601d76f3acdd0e6 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 10 Dec 2020 23:59:20 +0530 Subject: [PATCH 110/181] code refactor. --- .../Notepads.DesktopExtension.vcxproj | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index b36fe41f0..8b6152e7f 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -159,5 +159,10 @@ + + This project uses vcpkg that is missing on this computer. Manually download from https://github.com/microsoft/vcpkg and place it in {0}. Or install git and add it to your path, for more information see https://git-scm.com. The missing file is {1}. + + + \ No newline at end of file From 728e758bc6dbdae85b05a52969e6853d4e8818f7 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 11 Dec 2020 01:48:34 +0530 Subject: [PATCH 111/181] code refactor. --- setup-vcpkg.ps1 | 12 ------------ src/Notepads.DesktopExtension/appcenter.json | 4 ++-- 2 files changed, 2 insertions(+), 14 deletions(-) delete mode 100644 setup-vcpkg.ps1 diff --git a/setup-vcpkg.ps1 b/setup-vcpkg.ps1 deleted file mode 100644 index 51ffae93c..000000000 --- a/setup-vcpkg.ps1 +++ /dev/null @@ -1,12 +0,0 @@ -param ( - [string]$vcpkg_root = $(throw "-vcpkg_root= is required") -) - -git submodule update --init --recursive - -# Set up vcpkg -If (!(Test-Path -Path "${vcpkg_root}\vcpkg.exe")) { - & ${vcpkg_root}\bootstrap-vcpkg.bat -} - -& ${vcpkg_root}\vcpkg integrate install \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/appcenter.json b/src/Notepads.DesktopExtension/appcenter.json index 5ddc45d46..58f9a8f2e 100644 --- a/src/Notepads.DesktopExtension/appcenter.json +++ b/src/Notepads.DesktopExtension/appcenter.json @@ -14,7 +14,7 @@ "appVersion": "1.4.2.0", "appBuild": "1.4.2.0", "sdkName": "appcenter.uwp", - "sdkVersion": "3.4.1", + "sdkVersion": "4.0.0", "osName": "", "osVersion": "", "osBuild": "", @@ -53,7 +53,7 @@ "appVersion": "1.4.2.0", "appBuild": "1.4.2.0", "sdkName": "appcenter.uwp", - "sdkVersion": "3.4.1", + "sdkVersion": "4.0.0", "osName": "", "osVersion": "", "osBuild": "", From 6ebbef155d0750576a1b5cedf0479cc807aaab65 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 11 Dec 2020 17:04:45 +0530 Subject: [PATCH 112/181] code refactor. --- .gitignore | 5 ++++ .gitmodules | 3 --- .../Notepads.DesktopExtension.vcxproj | 23 +++++++++++++------ .../Notepads.DesktopExtension.vcxproj.filters | 1 + src/Notepads.DesktopExtension/build.ps1 | 12 +--------- src/Notepads.DesktopExtension/vcpkg.json | 8 +++++++ vcpkg | 1 - 7 files changed, 31 insertions(+), 22 deletions(-) delete mode 100644 .gitmodules create mode 100644 src/Notepads.DesktopExtension/vcpkg.json delete mode 160000 vcpkg diff --git a/.gitignore b/.gitignore index d0ac7f165..f0028dea9 100644 --- a/.gitignore +++ b/.gitignore @@ -354,3 +354,8 @@ healthchecksdb .Trashes ehthumbs.db Thumbs.db + +# vcpkg generated files # +######################### +**/toolsrc/ +**/vcpkg_installed/ \ No newline at end of file diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index fe07c999a..000000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "vcpkg"] - path = vcpkg - url = https://github.com/microsoft/vcpkg diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index 8b6152e7f..346101b1b 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -80,6 +80,12 @@ + + + c30903782c88967652178486a5f3e490fb2e8143 + + true + Use @@ -140,6 +146,7 @@ + @@ -147,7 +154,7 @@ - + @@ -156,13 +163,15 @@ - - - + + + + + - This project uses vcpkg that is missing on this computer. Manually download from https://github.com/microsoft/vcpkg and place it in {0}. Or install git and add it to your path, for more information see https://git-scm.com. The missing file is {1}. + This project uses vcpkg that is missing on this computer. Manually download from https://github.com/microsoft/vcpkg and place the contents in {0}. Or install git and add it to your path, for more information see https://git-scm.com. The missing file is {1}. - - + + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters index 5a17c00d6..66ef2ac7a 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters @@ -48,6 +48,7 @@ Resource Files + diff --git a/src/Notepads.DesktopExtension/build.ps1 b/src/Notepads.DesktopExtension/build.ps1 index 28e53bbe9..ed4f9b482 100644 --- a/src/Notepads.DesktopExtension/build.ps1 +++ b/src/Notepads.DesktopExtension/build.ps1 @@ -21,14 +21,4 @@ $appcenter_sdk_version = $appcenter_format.logs.device.sdkVersion[0] $sdk_target.Project.ItemGroup.PackageReference | ForEach-Object {if($_.Include -eq 'Microsoft.AppCenter.Crashes'){$appcenter_sdk_version = $_.Version}} $appcenter_format.logs.device | ForEach-Object {$_.sdkVersion = $appcenter_sdk_version} -$appcenter_format | ConvertTo-Json -depth 10| Set-Content $appcenter_file - -# Set up vcpkg packages -$vcpkg_root_dir = "${project_dir}\..\..\vcpkg" - -$vcpkg_triplet = "${platform}-windows" -If ($platform -eq "Win32") { - $vcpkg_triplet = "x86-windows" -} - -& ${vcpkg_root_dir}\vcpkg install rapidjson curl --triplet=$vcpkg_triplet \ No newline at end of file +$appcenter_format | ConvertTo-Json -depth 10| Set-Content $appcenter_file \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/vcpkg.json b/src/Notepads.DesktopExtension/vcpkg.json new file mode 100644 index 000000000..3c4196fdf --- /dev/null +++ b/src/Notepads.DesktopExtension/vcpkg.json @@ -0,0 +1,8 @@ +{ + "name": "notepads-desktopextension", + "version-string": "1.0.0.0", + "dependencies": [ + "rapidjson", + "curl" + ] +} \ No newline at end of file diff --git a/vcpkg b/vcpkg deleted file mode 160000 index 1d8728ae1..000000000 --- a/vcpkg +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 1d8728ae1ba66ad94b344708cf8d0ace1a6330b8 From 777cce7200538695947334a380821c3d23170c5d Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Tue, 15 Dec 2020 00:43:07 +0530 Subject: [PATCH 113/181] Implemented custom event tracking. --- .gitignore | 1 + .../Notepads.DesktopExtension.vcxproj | 32 +-- .../Notepads.DesktopExtension.vcxproj.filters | 20 +- src/Notepads.DesktopExtension/appcenter.cpp | 183 ++++++++-------- src/Notepads.DesktopExtension/appcenter.h | 23 ++ src/Notepads.DesktopExtension/appcenter.json | 69 +----- src/Notepads.DesktopExtension/build.ps1 | 17 +- src/Notepads.DesktopExtension/debug.cpp | 32 ++- src/Notepads.DesktopExtension/elevated.cpp | 24 ++- src/Notepads.DesktopExtension/extension.cpp | 6 + src/Notepads.DesktopExtension/log.h | 201 ++++++++++++++++++ src/Notepads.DesktopExtension/main.cpp | 6 +- src/Notepads.DesktopExtension/models.h | 183 ++++++++++++++++ src/Notepads.DesktopExtension/packages.config | 2 +- src/Notepads.DesktopExtension/pch.h | 20 +- src/Notepads.DesktopExtension/vcpkg.json | 5 +- 16 files changed, 581 insertions(+), 243 deletions(-) create mode 100644 src/Notepads.DesktopExtension/appcenter.h create mode 100644 src/Notepads.DesktopExtension/log.h create mode 100644 src/Notepads.DesktopExtension/models.h diff --git a/.gitignore b/.gitignore index f0028dea9..1d03e007d 100644 --- a/.gitignore +++ b/.gitignore @@ -357,5 +357,6 @@ Thumbs.db # vcpkg generated files # ######################### +**/ports/ **/toolsrc/ **/vcpkg_installed/ \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index 346101b1b..fc68e7663 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -1,6 +1,6 @@ - + true true @@ -94,9 +94,10 @@ _CONSOLE;WIN32_LEAN_AND_MEAN;WINRT_LEAN_AND_MEAN;%(PreprocessorDefinitions) Level4 %(AdditionalOptions) /permissive- /bigobj + stdcpp17 - powershell -ExecutionPolicy Bypass $(ProjectDir)build.ps1 -project_dir $(ProjectDir) -platform $(Platform) + powershell -ExecutionPolicy Bypass $(ProjectDir)build.ps1 -project_dir $(ProjectDir) @@ -129,6 +130,9 @@ + + + @@ -153,25 +157,25 @@ - + - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - - - - + + + + This project uses vcpkg that is missing on this computer. Manually download from https://github.com/microsoft/vcpkg and place the contents in {0}. Or install git and add it to your path, for more information see https://git-scm.com. The missing file is {1}. + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters index 66ef2ac7a..820cd8db0 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters @@ -13,6 +13,9 @@ {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + {de4d9f33-9346-4bce-97fe-469f12bf39a5} + @@ -21,9 +24,6 @@ Source Files - - Source Files - Source Files @@ -33,6 +33,9 @@ Source Files + + AppCenter + @@ -41,14 +44,23 @@ Header Files + + AppCenter + + + AppCenter + + + AppCenter + - Resource Files + diff --git a/src/Notepads.DesktopExtension/appcenter.cpp b/src/Notepads.DesktopExtension/appcenter.cpp index b046ee60f..e9d435297 100644 --- a/src/Notepads.DesktopExtension/appcenter.cpp +++ b/src/Notepads.DesktopExtension/appcenter.cpp @@ -1,16 +1,16 @@ // Documentation is at https://docs.microsoft.com/en-us/appcenter/diagnostics/upload-crashes #include "pch.h" -#include "resource.h" -#include "combaseapi.h" -#include "rapidjson/document.h" -#include "rapidjson/writer.h" +#include "appcenter.h" +#include "log.h" #include "rapidjson/stringbuffer.h" #define APPCENTER_ENDPOINT "https://in.appcenter.ms/logs?Api-Version=1.0.0" -using namespace std; +using namespace fmt; using namespace rapidjson; +using namespace std; using namespace winrt; +using namespace AppCenter; using namespace Windows::ApplicationModel; using namespace Windows::Foundation; using namespace Windows::Security::ExchangeActiveSyncProvisioning; @@ -24,127 +24,114 @@ void AppCenter::start() launchTimeStamp = getTimeStamp(); - HMODULE handle = ::GetModuleHandle(NULL); - HRSRC rc = FindResource(handle, MAKEINTRESOURCE(APPCENTER_JSON), MAKEINTRESOURCE(JSONFILE)); - HGLOBAL rcData = LoadResource(handle, rc); - DWORD size = SizeofResource(handle, rc); - appCenterJSON = static_cast(LockResource(rcData)); + hstring installId = unbox_value_or(readSettingsKey(AppCenterInstallIdStr), L""); + if (installId.empty()) return; headerList = curl_slist_append(headerList, "Content-Type: application/json"); - - stringstream appSecretHeader; - appSecretHeader << "app-secret: " << to_string(AppCenterSecret); - headerList = curl_slist_append(headerList, appSecretHeader.str().c_str()); - - hstring installId = unbox_value_or(readSettingsKey(AppCenterInstallIdStr), L""); - if (installId == L"") return; - stringstream installIdHeader; - installIdHeader << "install-id: " << to_string(installId); - headerList = curl_slist_append(headerList, installIdHeader.str().c_str()); + headerList = curl_slist_append(headerList, format("app-secret: {}", to_string(AppCenterSecret)).c_str()); + headerList = curl_slist_append(headerList, format("install-id: {}", to_string(installId)).c_str()); } -void AppCenter::trackError(DWORD errorCode, string message, bool isFatal) +void AppCenter::trackError(DWORD errorCode, const string& message, bool isFatal) { if (!AppCenterSecret) return; - string timeStamp = getTimeStamp(); - - Document errorReportForm; - errorReportForm.Parse(appCenterJSON); - string crashReportId = to_string(to_hstring(GuidHelper::CreateNewGuid())); crashReportId.erase(0, crashReportId.find_first_not_of('{')).erase(crashReportId.find_last_not_of('}') + 1); + string crashReportSid = to_string(to_hstring(GuidHelper::CreateNewGuid())); + crashReportSid.erase(0, crashReportSid.find_first_not_of('{')).erase(crashReportSid.find_last_not_of('}') + 1); string errorAttachmentId = to_string(to_hstring(GuidHelper::CreateNewGuid())); errorAttachmentId.erase(0, errorAttachmentId.find_first_not_of('{')).erase(errorAttachmentId.find_last_not_of('}') + 1); - ULONGLONG version = stoull(AnalyticsInfo::VersionInfo().DeviceFamilyVersion().c_str()); - ULONGLONG major = (version & 0xFFFF000000000000L) >> 48; - ULONGLONG minor = (version & 0x0000FFFF00000000L) >> 32; - ULONGLONG build = (version & 0x00000000FFFF0000L) >> 16; - ULONGLONG revision = (version & 0x000000000000FFFFL); - stringstream osVersionBuilder; - osVersionBuilder << major << "." << minor << "." << build; - string osVersion = osVersionBuilder.str(); - osVersionBuilder << "." << revision; - string osBuild = osVersionBuilder.str(); - - EasClientDeviceInformation oemInfo = EasClientDeviceInformation(); - - stringstream screenSize; - RECT desktop; - GetWindowRect(GetDesktopWindow(), &desktop); - screenSize << desktop.right << "x" << desktop.bottom; - WCHAR locale[LOCALE_NAME_MAX_LENGTH + 1]; LCIDToLocaleName(GetThreadLocale(), locale, LOCALE_NAME_MAX_LENGTH, 0); WCHAR localeDisplayName[LOCALE_NAME_MAX_LENGTH + 1]; GetLocaleInfoEx(locale, LOCALE_SENGLISHDISPLAYNAME, localeDisplayName, LOCALE_NAME_MAX_LENGTH); - TIME_ZONE_INFORMATION timeZoneInfo; - GetTimeZoneInformation(&timeZoneInfo); - - stringstream exceptionProp; - exceptionProp << "Win32Exception: Exception of code no. " << errorCode << " was thrown."; + string isElevated = isElevatedProcess() ? "True" : "False"; + string eventType = isFatal ? "OnWin32UnhandledException" : "OnWin32UnexpectedException"; + + vector> properties; + properties.push_back(pair("Exception", format("Win32Exception: Exception of code no. {} was thrown.", errorCode))); + properties.push_back(pair("Message", message)); + properties.push_back(pair("Culture", to_string(localeDisplayName))); + properties.push_back(pair("AvailableMemory", to_string((FLOAT)MemoryManager::AppMemoryUsageLimit() / 1024 / 1024))); + properties.push_back(pair("FirstUseTimeUTC", getTimeStamp("%m/%d/%Y %T"))); + properties.push_back(pair("OSArchitecture", to_string(Package::Current().Id().Architecture()))); + properties.push_back(pair("OSVersion", deviceInfo.getOsVersion())); + properties.push_back(pair("IsDesktopExtension", "True")); + properties.push_back(pair("IsElevated", isElevated)); + + vector errorReportSet; + errorReportSet.push_back(Log(LogType::managedError, crashReportId, crashReportSid, isFatal, new Exception(message), properties)); + errorReportSet.push_back(Log(LogType::errorAttachment, errorAttachmentId, crashReportId, + base64_encode(format("Exception: Win32Exception code no. {}, Message: {}, IsDesktopExtension: True, IsElevated: {}", + errorCode, message, isElevated)))); - stringstream errorAttachmentBuilder; - errorAttachmentBuilder - << "Exception: Win32Exception code no. " << errorCode << ", " - << "Message: " << message << ", " - << "IsDesktopExtension: True" << ", " - << "IsElevated: " << (isElevatedProcess() ? "True" : "False"); - string errorAttachment = base64_encode(errorAttachmentBuilder.str()); + StringBuffer errorReport; +#ifdef _DEBUG + PrettyWriter writer(errorReport); +#else + Writer writer(errorReport); +#endif - Value& logReports = errorReportForm["logs"]; - for (int i = 0; i < logReports.GetArray().Size(); i++) + writer.StartObject(); + writer.String("logs"); + writer.StartArray(); + for (vector::const_iterator report = errorReportSet.begin(); report != errorReportSet.end(); ++report) { - logReports[i]["timestamp"].SetString(timeStamp.c_str(), errorReportForm.GetAllocator()); - - logReports[i]["device"]["osName"].SetString(to_string(oemInfo.OperatingSystem()).c_str(), errorReportForm.GetAllocator()); - logReports[i]["device"]["osVersion"].SetString(osVersion.c_str(), errorReportForm.GetAllocator()); - logReports[i]["device"]["osBuild"].SetString(osBuild.c_str(), errorReportForm.GetAllocator()); - logReports[i]["device"]["model"].SetString(to_string(oemInfo.SystemProductName()).c_str(), errorReportForm.GetAllocator()); - logReports[i]["device"]["oemName"].SetString(to_string(oemInfo.SystemManufacturer()).c_str(), errorReportForm.GetAllocator()); - logReports[i]["device"]["screenSize"].SetString(screenSize.str().c_str(), errorReportForm.GetAllocator()); - logReports[i]["device"]["locale"].SetString(to_string(locale).c_str(), errorReportForm.GetAllocator()); - logReports[i]["device"]["timeZoneOffset"].SetInt(-1 * timeZoneInfo.Bias); - - if (i == 0) - { - logReports[i]["appLaunchTimestamp"].SetString(launchTimeStamp.c_str(), errorReportForm.GetAllocator()); - logReports[i]["processId"].SetString(to_string(GetCurrentProcessId()).c_str(), errorReportForm.GetAllocator()); - logReports[i]["id"].SetString(crashReportId.c_str(), errorReportForm.GetAllocator()); - logReports[i]["fatal"].SetBool(isFatal); - logReports[i]["errorThreadId"].SetInt(GetCurrentThreadId()); - - logReports[i]["exception"]["message"].SetString(message.c_str(), errorReportForm.GetAllocator()); - - logReports[i]["properties"]["exception"].SetString(exceptionProp.str().c_str(), errorReportForm.GetAllocator()); - logReports[i]["properties"]["message"].SetString(message.c_str(), errorReportForm.GetAllocator()); - logReports[i]["properties"]["culture"].SetString(to_string(localeDisplayName).c_str(), errorReportForm.GetAllocator()); - logReports[i]["properties"]["availableMemory"].SetString(to_string((FLOAT)MemoryManager::AppMemoryUsageLimit() / 1024 / 1024).c_str(), errorReportForm.GetAllocator()); - logReports[i]["properties"]["firstUseTimeUTC"].SetString(getTimeStamp("%m/%d/%Y %T").c_str(), errorReportForm.GetAllocator()); - logReports[i]["properties"]["osArchitecture"].SetString(to_string(Package::Current().Id().Architecture()).c_str(), errorReportForm.GetAllocator()); - logReports[i]["properties"]["osVersion"].SetString(osBuild.c_str(), errorReportForm.GetAllocator()); - logReports[i]["properties"]["isElevated"].SetString(isElevatedProcess() ? "True" : "False", errorReportForm.GetAllocator()); - } - else if (i == 1) + report->Serialize(writer); + } + writer.EndArray(); + writer.EndObject(); + + CURL* curl = curl_easy_init(); + if (curl) { + curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerList); + curl_easy_setopt(curl, CURLOPT_URL, APPCENTER_ENDPOINT); + curl_easy_setopt(curl, CURLOPT_POSTFIELDS, errorReport.GetString()); + +#ifdef _DEBUG + curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); +#endif + + CURLcode res = curl_easy_perform(curl); + if (res != CURLE_OK) { - logReports[i]["data"].SetString(errorAttachment.c_str(), errorReportForm.GetAllocator()); - logReports[i]["errorId"].SetString(crashReportId.c_str(), errorReportForm.GetAllocator()); - logReports[i]["id"].SetString(errorAttachmentId.c_str(), errorReportForm.GetAllocator()); + printDebugMessage(format(L"curl_easy_perform() failed: {}", to_hstring(curl_easy_strerror(res))).c_str()); } } + curl_easy_cleanup(curl); + trackEvent(eventType, properties, crashReportSid); +} - StringBuffer errorReport; - Writer writer(errorReport); - errorReportForm.Accept(writer); +void AppCenter::trackEvent(const string& name, const vector>& properties, const string& sid) +{ + if (!AppCenterSecret) return; + + string eventReportId = to_string(to_hstring(GuidHelper::CreateNewGuid())); + eventReportId.erase(0, eventReportId.find_first_not_of('{')).erase(eventReportId.find_last_not_of('}') + 1); + + StringBuffer eventReport; +#ifdef _DEBUG + PrettyWriter writer(eventReport); +#else + Writer writer(eventReport); +#endif + + writer.StartObject(); + writer.String("logs"); + writer.StartArray(); + Log(LogType::event, eventReportId, sid, name, properties).Serialize(writer); + writer.EndArray(); + writer.EndObject(); CURL* curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerList); curl_easy_setopt(curl, CURLOPT_URL, APPCENTER_ENDPOINT); - curl_easy_setopt(curl, CURLOPT_POSTFIELDS, errorReport.GetString()); + curl_easy_setopt(curl, CURLOPT_POSTFIELDS, eventReport.GetString()); #ifdef _DEBUG curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); @@ -152,7 +139,9 @@ void AppCenter::trackError(DWORD errorCode, string message, bool isFatal) CURLcode res = curl_easy_perform(curl); if (res != CURLE_OK) - fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); + { + printDebugMessage(format(L"curl_easy_perform() failed: {}", to_hstring(curl_easy_strerror(res))).c_str()); + } } curl_easy_cleanup(curl); } \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/appcenter.h b/src/Notepads.DesktopExtension/appcenter.h new file mode 100644 index 000000000..7af2343b3 --- /dev/null +++ b/src/Notepads.DesktopExtension/appcenter.h @@ -0,0 +1,23 @@ +#pragma once +#include "pch.h" +#include "curl/curl.h" + +#ifdef _DEBUG +#include "rapidjson/prettywriter.h" +#else +#include "rapidjson/writer.h" +#endif + +namespace AppCenter +{ + using namespace std; + + namespace + { + static struct curl_slist* headerList = NULL; + } + + void start(); + void trackError(DWORD errorCode, const string& message, bool isFatal); + void trackEvent(const string& name, const vector>& properties, const string& sid = ""); +} \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/appcenter.json b/src/Notepads.DesktopExtension/appcenter.json index 58f9a8f2e..a7436cf1c 100644 --- a/src/Notepads.DesktopExtension/appcenter.json +++ b/src/Notepads.DesktopExtension/appcenter.json @@ -1,68 +1,5 @@ { - "logs": [ - { - "type": "managedError", - "timestamp": "", - "appLaunchTimestamp": "", - "processId": "", - "id": "", - "fatal": false, - "processName": "Notepads32.exe", - "errorThreadId": 0, - "device": { - "appNamespace": "Notepads.DesktopExtension", - "appVersion": "1.4.2.0", - "appBuild": "1.4.2.0", - "sdkName": "appcenter.uwp", - "sdkVersion": "4.0.0", - "osName": "", - "osVersion": "", - "osBuild": "", - "model": "", - "oemName": "", - "screenSize": "", - "locale": "", - "timeZoneOffset": 0 - }, - "exception": { - "type": "Win32Exception", - "message": "", - "stackTrace": "" - }, - "properties": { - "exception": "", - "message": "", - "culture": "", - "availableMemory": "", - "firstUseTimeUTC": "", - "osArchitecture": "", - "osVersion": "", - "isDesktopExtension": "True", - "isElevated": "False" - } - }, - { - "type": "errorAttachment", - "contentType": "text/plain", - "timestamp": "", - "data": "", - "errorId": "", - "id": "", - "device": { - "appNamespace": "Notepads.DesktopExtension", - "appVersion": "1.4.2.0", - "appBuild": "1.4.2.0", - "sdkName": "appcenter.uwp", - "sdkVersion": "4.0.0", - "osName": "", - "osVersion": "", - "osBuild": "", - "model": "", - "oemName": "", - "screenSize": "", - "locale": "", - "timeZoneOffset": 0 - } - } - ] + "appVersion": "1.4.2.0", + "appBuild": "1.4.2.0", + "sdkVersion": "4.0.0" } diff --git a/src/Notepads.DesktopExtension/build.ps1 b/src/Notepads.DesktopExtension/build.ps1 index ed4f9b482..038126dbc 100644 --- a/src/Notepads.DesktopExtension/build.ps1 +++ b/src/Notepads.DesktopExtension/build.ps1 @@ -1,6 +1,5 @@ param ( - [string]$project_dir = $(throw "-project_dir= is required"), - [string]$platform = "x86" + [string]$project_dir = $(throw "-project_dir= is required") ) $project_dir = Resolve-Path $project_dir.TrimEnd("\") @@ -8,17 +7,15 @@ $appcenter_file = "${project_dir}\appcenter.json" $manifest_file = "${project_dir}\..\Notepads.Package\Package.appxmanifest" $uwp_project_file = "${project_dir}\..\Notepads\Notepads.csproj" -$appcenter_format = Get-Content $appcenter_file -raw | ConvertFrom-Json +$appcenter_version_data = Get-Content $appcenter_file -raw | ConvertFrom-Json [xml]$manifest = Get-Content $manifest_file [xml]$sdk_target = Get-Content $uwp_project_file -# Keep version string in format json same as package version -$appcenter_format.logs.device | ForEach-Object {$_.appVersion = $manifest.Package.Identity.Version} -$appcenter_format.logs.device | ForEach-Object {$_.appBuild = $manifest.Package.Identity.Version} +# Keep version string in same as package version +$appcenter_version_data.appVersion = $manifest.Package.Identity.Version +$appcenter_version_data.appBuild = $manifest.Package.Identity.Version # Keep appcenter sdk version same as nuget package version -$appcenter_sdk_version = $appcenter_format.logs.device.sdkVersion[0] -$sdk_target.Project.ItemGroup.PackageReference | ForEach-Object {if($_.Include -eq 'Microsoft.AppCenter.Crashes'){$appcenter_sdk_version = $_.Version}} -$appcenter_format.logs.device | ForEach-Object {$_.sdkVersion = $appcenter_sdk_version} +$sdk_target.Project.ItemGroup.PackageReference | ForEach-Object {if($_.Include -eq 'Microsoft.AppCenter.Crashes'){$appcenter_version_data.sdkVersion = $_.Version}} -$appcenter_format | ConvertTo-Json -depth 10| Set-Content $appcenter_file \ No newline at end of file +$appcenter_version_data | ConvertTo-Json -depth 10| Set-Content $appcenter_file \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/debug.cpp b/src/Notepads.DesktopExtension/debug.cpp index 27a1ce272..01d96fd4c 100644 --- a/src/Notepads.DesktopExtension/debug.cpp +++ b/src/Notepads.DesktopExtension/debug.cpp @@ -1,5 +1,7 @@ #include "pch.h" +#include "appcenter.h" +using namespace fmt; using namespace std; using namespace winrt; using namespace Windows::Foundation; @@ -20,14 +22,6 @@ void printDebugMessage(LPCTSTR message, DWORD sleepTime) #endif } -void printDebugMessage(LPCTSTR message, LPCTSTR parameter, DWORD sleepTime) -{ -#ifdef _DEBUG - wcout << message << " \"" << parameter << "\"" << endl; - Sleep(sleepTime); -#endif -} - string to_string(ProcessorArchitecture arch) { switch (arch) @@ -53,29 +47,27 @@ string getTimeStamp() { SYSTEMTIME systemTime; GetSystemTime(&systemTime); - stringstream timeStamp; - timeStamp << getTimeStamp("%FT%T") << "." << systemTime.wMilliseconds << "Z"; - return timeStamp.str(); + return format("{}.{}Z", getTimeStamp("%FT%T"), systemTime.wMilliseconds); } string getTimeStamp(const char* format) { time_t timePast = time(NULL); - tm* utcTime = gmtime(&timePast); + tm utcTime; + gmtime_s(&utcTime, &timePast); CHAR timeStamp[MAX_DATETIME_STR]; - strftime(timeStamp, sizeof(timeStamp), format, utcTime); + strftime(timeStamp, sizeof(timeStamp), format, &utcTime); return timeStamp; } //From https://stackoverflow.com/a/34571089/5155484 -typedef unsigned char uchar; static const string b = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; string base64_encode(const string& in) { string out; int val = 0, valb = -6; - for (uchar c : in) { + for (UCHAR c : in) { val = (val << 8) + c; valb += 8; while (valb >= 0) { @@ -88,7 +80,7 @@ string base64_encode(const string& in) return out; } -IAsyncAction logLastError(LPCTSTR errorTitle) +IAsyncAction logLastError(bool isFatal) { LPVOID msgBuf; DWORD errorCode = GetLastError(); @@ -108,7 +100,7 @@ IAsyncAction logLastError(LPCTSTR errorTitle) LocalFree(msgBuf); getline(msgStrm, msg, L'\r'); - AppCenter::trackError(errorCode, to_string(msg), wcscmp(errorTitle, L"OnUnhandledException: ") == 0); + AppCenter::trackError(errorCode, to_string(msg), isFatal); if (logFile != nullptr) { @@ -118,10 +110,10 @@ IAsyncAction logLastError(LPCTSTR errorTitle) GetTimeFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, NULL, timeStr, MAX_TIME_STR); TCHAR dateStr[MAX_DATE_STR]; GetDateFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, NULL, dateStr, MAX_DATE_STR, NULL); - wstringstream debugMsg; - debugMsg << dateStr << " " << timeStr << " " << "[" << "Error" << "]" << " " << "[" << "Error Code: " << errorCode << "]" << " " << errorTitle << msg << endl; + wstring debugMsg = format(L"{} {} [Error] [Error Code: {}] {}{}\n", + dateStr, timeStr, errorCode, isFatal ? L"OnUnhandledException: " : L"OnUnexpectedException: ", msg); - co_await PathIO::AppendTextAsync(logFile.Path(), debugMsg.str().c_str()); + co_await PathIO::AppendTextAsync(logFile.Path(), debugMsg); } } diff --git a/src/Notepads.DesktopExtension/elevated.cpp b/src/Notepads.DesktopExtension/elevated.cpp index e5b37a78c..88278973c 100644 --- a/src/Notepads.DesktopExtension/elevated.cpp +++ b/src/Notepads.DesktopExtension/elevated.cpp @@ -1,5 +1,8 @@ #include "pch.h" +#include "appcenter.h" +#include "fmt/format.h" +using namespace fmt; using namespace std; using namespace winrt; using namespace Windows::ApplicationModel; @@ -23,16 +26,16 @@ DWORD WINAPI saveFileFromPipeData(LPVOID param) LPCSTR result = "Failed"; - wstringstream pipeName; - pipeName << "\\\\.\\pipe\\Sessions\\" << sessionId << "\\AppContainerNamedObjects\\" << packageSid.c_str() << "\\" << Package::Current().Id().FamilyName().c_str() << "\\" << AdminPipeConnectionNameStr; + wstring pipeName = format(L"\\\\.\\pipe\\Sessions\\{}\\AppContainerNamedObjects\\{}\\{}\\{}", + sessionId, packageSid, Package::Current().Id().FamilyName(), AdminPipeConnectionNameStr); HANDLE hPipe = INVALID_HANDLE_VALUE; while (hPipe == INVALID_HANDLE_VALUE) { Sleep(50); - if (WaitNamedPipe(pipeName.str().c_str(), NMPWAIT_WAIT_FOREVER)) + if (WaitNamedPipe(pipeName.c_str(), NMPWAIT_WAIT_FOREVER)) { - hPipe = CreateFile(pipeName.str().c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + hPipe = CreateFile(pipeName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); } } @@ -68,10 +71,9 @@ DWORD WINAPI saveFileFromPipeData(LPVOID param) getline(pipeData, dataArrayLengthStr); int dataArrayLength = stoi(dataArrayLengthStr); - wstringstream memoryMapName; - memoryMapName << "AppContainerNamedObjects\\" << packageSid.c_str() << "\\" << memoryMapId; + wstring memoryMapName = format(L"AppContainerNamedObjects\\{}\\{}", packageSid, memoryMapId); - HANDLE hMemory = OpenFileMapping(FILE_MAP_READ, FALSE, memoryMapName.str().c_str()); + HANDLE hMemory = OpenFileMapping(FILE_MAP_READ, FALSE, memoryMapName.c_str()); if (hMemory) { LPVOID mapView = MapViewOfFile(hMemory, FILE_MAP_READ, 0, 0, dataArrayLength); @@ -109,14 +111,18 @@ DWORD WINAPI saveFileFromPipeData(LPVOID param) if (strcmp(result, "Success") == 0) { - printDebugMessage(L"Successfully wrote to", filePath.c_str()); + printDebugMessage(format(L"Successfully wrote to", filePath).c_str()); } else { - printDebugMessage(L"Failed to write to", filePath.c_str()); + printDebugMessage(format(L"Failed to write to", filePath).c_str()); } printDebugMessage(L"Waiting on uwp app to send data."); + vector> properties; + properties.push_back(pair("Result", result)); + AppCenter::trackEvent("OnWriteToSystemFileRequested", properties); + return 0; } diff --git a/src/Notepads.DesktopExtension/extension.cpp b/src/Notepads.DesktopExtension/extension.cpp index 5250b4975..b284f5e70 100644 --- a/src/Notepads.DesktopExtension/extension.cpp +++ b/src/Notepads.DesktopExtension/extension.cpp @@ -1,5 +1,7 @@ #include "pch.h" +#include "appcenter.h" +using namespace std; using namespace winrt; using namespace Windows::ApplicationModel; using namespace Windows::ApplicationModel::AppService; @@ -27,6 +29,7 @@ fire_and_forget launchElevatedProcess() shExInfo.hInstApp = 0; auto message = ValueSet(); + vector> properties; message.Insert(InteropCommandLabel, box_value(CreateElevetedExtensionCommandStr)); if (ShellExecuteEx(&shExInfo)) { @@ -40,13 +43,16 @@ fire_and_forget launchElevatedProcess() message.Insert(InteropCommandAdminCreatedLabel, box_value(true)); printDebugMessage(L"Adminstrator Extension has been launched."); + properties.push_back(pair("Accepted", "True")); } else { message.Insert(InteropCommandAdminCreatedLabel, box_value(false)); printDebugMessage(L"User canceled launching of Adminstrator Extension."); + properties.push_back(pair("Denied", "True")); } co_await interopServiceConnection.SendMessageAsync(message); + AppCenter::trackEvent("OnAdminstratorPrivilageGranted", properties); } void onConnectionServiceRequestRecieved(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) diff --git a/src/Notepads.DesktopExtension/log.h b/src/Notepads.DesktopExtension/log.h new file mode 100644 index 000000000..d293e81fc --- /dev/null +++ b/src/Notepads.DesktopExtension/log.h @@ -0,0 +1,201 @@ +#pragma once +#include "pch.h" +#include "models.h" + +namespace AppCenter +{ + using namespace rapidjson; + using namespace std; + + enum LogType + { + managedError, + errorAttachment, + event + }; + + namespace + { + static const string logTypes[] = { "managedError", "errorAttachment", "event" }; + static string launchTimeStamp; + static Device deviceInfo = Device(); + } + + class Log + { + public: + + #pragma region Constructors for error report + + Log(LogType type, const string& id, const string& sid, bool isFatal, Exception* exception) : + _type(type), _id(id), _sid(sid), _fatal(isFatal), _exception(exception) + { + InitializeLog(); + } + + Log(LogType type, const string& id, const string& sid, bool isFatal, Exception* exception, const vector>& properties) : + _type(type), _id(id), _sid(sid), _fatal(isFatal), _exception(exception), _properties(properties) + { + InitializeLog(); + } + + #pragma endregion + + #pragma region Constructor for error attachment + + Log(LogType type, const string& id, const string& errorId, const string& data) : + _type(type), _id(id), _errorId(errorId), _data(data) + { + InitializeLog(); + } + + #pragma endregion + + #pragma region Constructor for event report + + Log(LogType type, const string& id, const string& sid, const string& name, const vector>& properties) : + _type(type), _id(id), _sid(sid), _name(name), _properties(properties) + { + InitializeLog(); + } + + #pragma endregion + + Log(const Log& log) : + _type(log._type), _name(log._name), _timestamp(log._timestamp), _processId(log._processId), _id(log._id), _sid(log._sid), _fatal(log._fatal), + _processName(log._processName), _errorThreadId(log._errorThreadId), _data(log._data), _errorId(log._errorId), + _exception(NULL), _properties(log._properties) + { + _exception = (log._exception == 0) ? 0 : new Exception(*log._exception); + InitializeLog(); + } + + ~Log() + { + delete _exception; + } + + Log& operator=(const Log& log) + { + if (this == &log) return *this; + + delete _exception; + _type = log._type; + _timestamp = log._timestamp; + _id = log._id; + _sid = log._sid; + _processId = log._processId; + _fatal = log._fatal; + _processName = log._processName; + _errorThreadId = log._errorThreadId; + _exception = (log._exception == 0) ? 0 : new Exception(*log._exception); + _contentType = log._contentType; + _data = log._data; + _errorId = log._errorId; + _name = log._name; + _properties = log._properties; + return *this; + } + + template + void Serialize(Writer& writer) const + { + writer.StartObject(); + + writer.String("type"); + writer.String(logTypes[_type].c_str(), static_cast(logTypes[_type].length())); + writer.String("timestamp"); + writer.String(_timestamp.c_str(), static_cast(_timestamp.length())); + writer.String("appLaunchTimestamp"); + writer.String(launchTimeStamp.c_str(), static_cast(launchTimeStamp.length())); + writer.String("id"); + writer.String(_id.c_str(), static_cast(_id.length())); + + if (!_sid.empty()) + { + writer.String("sid"); + writer.String(_sid.c_str(), static_cast(_sid.length())); + } + + switch (_type) + { + case LogType::managedError: + writer.String("processId"); + writer.Uint(_processId); + writer.String("fatal"); + writer.Bool(_fatal); + writer.String("processName"); + writer.String(_processName.c_str(), static_cast(_processName.length())); + writer.String("errorThreadId"); + writer.Uint(_errorThreadId); + + // Write exception data + writer.String("exception"); + _exception->Serialize(writer); + break; + case LogType::errorAttachment: + writer.String("contentType"); + writer.String(_contentType.c_str(), static_cast(_contentType.length())); + writer.String("data"); + writer.String(_data.c_str(), static_cast(_data.length())); + writer.String("errorId"); + writer.String(_errorId.c_str(), static_cast(_errorId.length())); + break; + case LogType::event: + writer.String("name"); + writer.String(_name.c_str(), static_cast(_name.length())); + break; + } + + // Write device specific data + writer.String("device"); + deviceInfo.Serialize(writer); + + // Write custom properties if available + if (!_properties.empty()) + { + writer.String("properties"); + writer.StartObject(); + for (vector>::const_iterator property = _properties.begin(); property != _properties.end(); ++property) + { + writer.String(property->first); + writer.String(property->second.c_str(), static_cast(property->second.length())); + } + writer.EndObject(); + } + + writer.EndObject(); + } + + private: + LogType _type; + string _contentType = "text/plain"; + string _name; + string _timestamp = getTimeStamp(); + unsigned _processId; + string _id; + string _sid; + bool _fatal = false; + string _processName = "Notepads32.exe"; + unsigned _errorThreadId = 0; + string _data; + string _errorId; + Exception* _exception = NULL; + vector> _properties; + + void InitializeLog() + { + switch (_type) + { + case LogType::managedError: + _processId = GetCurrentProcessId(); + _errorThreadId = GetCurrentThreadId(); + break; + case LogType::errorAttachment: + break; + case LogType::event: + break; + } + } + }; +} \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index 4e8f8181e..6e65527f7 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -1,6 +1,6 @@ #include "pch.h" +#include "appcenter.h" -using namespace std; using namespace winrt; constexpr LPCTSTR DesktopExtensionMutexName = L"DesktopExtensionMutexName"; @@ -23,13 +23,13 @@ void exitApp() void onUnhandledException() { - logLastError(L"OnUnhandledException: ").get(); + logLastError(true).get(); exitApp(); } void onUnexpectedException() { - logLastError(L"OnUnexpectedException: ").get(); + logLastError(false).get(); exitApp(); } diff --git a/src/Notepads.DesktopExtension/models.h b/src/Notepads.DesktopExtension/models.h new file mode 100644 index 000000000..c2a5d4f07 --- /dev/null +++ b/src/Notepads.DesktopExtension/models.h @@ -0,0 +1,183 @@ +#pragma once +#include "pch.h" +#include "resource.h" +#include "rapidjson/document.h" + +namespace AppCenter +{ + using namespace fmt; + using namespace rapidjson; + using namespace std; + using namespace winrt; + using namespace Windows::Security::ExchangeActiveSyncProvisioning; + using namespace Windows::System::Profile; + + class Exception + { + public: + Exception(const string& message) : _message(message) {} + Exception(const string& message, const string& stackTrace) : _message(message), _stackTrace(stackTrace) {} + Exception(const Exception& exception) : _message(exception._message), _stackTrace(exception._stackTrace) {} + Exception(const exception& exception) : _message(exception.what()) {} + + ~Exception() {} + + Exception& operator=(const Exception& exception) + { + if (this == &exception) return *this; + + _type = exception._type; + _message = exception._message; + _stackTrace = exception._stackTrace; + return *this; + } + + template + void Serialize(Writer& writer) const + { + writer.StartObject(); + + writer.String("type"); + writer.String(_type.c_str(), static_cast(_type.length())); + writer.String("message"); + writer.String(_message.c_str(), static_cast(_message.length())); + writer.String("stackTrace"); + writer.String(_stackTrace.c_str(), static_cast(_stackTrace.length())); + + writer.EndObject(); + } + + private: + string _type = "Win32Exception"; + string _message; + string _stackTrace = ""; + }; + + class Device + { + public: + Device() + { + HMODULE handle = ::GetModuleHandle(NULL); + HRSRC rc = FindResource(handle, MAKEINTRESOURCE(APPCENTER_JSON), MAKEINTRESOURCE(JSONFILE)); + HGLOBAL rcData = LoadResource(handle, rc); + DWORD size = SizeofResource(handle, rc); + Document versionData; + versionData.Parse(static_cast(LockResource(rcData))); + _appVersion = versionData["appVersion"].GetString(); + _appBuild = versionData["appBuild"].GetString(); + _sdkVersion = versionData["sdkVersion"].GetString(); + + EasClientDeviceInformation oemInfo = EasClientDeviceInformation(); + _osName = to_string(oemInfo.OperatingSystem()); + + ULONGLONG version = stoull(AnalyticsInfo::VersionInfo().DeviceFamilyVersion().c_str()); + ULONGLONG major = (version & 0xFFFF000000000000L) >> 48; + ULONGLONG minor = (version & 0x0000FFFF00000000L) >> 32; + ULONGLONG build = (version & 0x00000000FFFF0000L) >> 16; + ULONGLONG revision = (version & 0x000000000000FFFFL); + _osVersion = format("{}.{}.{}", major, minor, build); + _osBuild = format("{}.{}.{}.{}", major, minor, build, revision); + + _model = to_string(oemInfo.SystemProductName()); + _oemName = to_string(oemInfo.SystemManufacturer()); + + RECT desktop; + GetWindowRect(GetDesktopWindow(), &desktop); + _screenSize = format("{}x{}", desktop.right, desktop.bottom); + + WCHAR locale[LOCALE_NAME_MAX_LENGTH + 1]; + LCIDToLocaleName(GetThreadLocale(), locale, LOCALE_NAME_MAX_LENGTH, 0); + WCHAR localeDisplayName[LOCALE_NAME_MAX_LENGTH + 1]; + GetLocaleInfoEx(locale, LOCALE_SENGLISHDISPLAYNAME, localeDisplayName, LOCALE_NAME_MAX_LENGTH); + _locale = to_string(locale); + + TIME_ZONE_INFORMATION timeZoneInfo; + GetTimeZoneInformation(&timeZoneInfo); + _timeZoneOffset = -1 * timeZoneInfo.Bias; + } + + Device(const Device& device) : + _appVersion(device._appVersion), _appBuild(device._appBuild), _sdkVersion(device._sdkVersion), + _osName(device._osName), _osVersion(device._osVersion), _osBuild(device._osBuild), + _model(device._model), _oemName(device._oemName), _screenSize(device._screenSize), + _locale(device._locale), _timeZoneOffset(device._timeZoneOffset) {} + + ~Device() {} + + Device& operator=(const Device& device) + { + if (this == &device) return *this; + + _appNamespace = device._appNamespace; + _appVersion = device._appVersion; + _appBuild = device._appBuild; + _sdkName = device._sdkName; + _sdkVersion = device._sdkVersion; + _osName = device._osName; + _osVersion = device._osVersion; + _osBuild = device._osBuild; + _model = device._model; + _oemName = device._oemName; + _screenSize = device._screenSize; + _locale = device._locale; + _timeZoneOffset = device._timeZoneOffset; + return *this; + } + + template + void Serialize(Writer& writer) const + { + writer.StartObject(); + + writer.String("appNamespace"); + writer.String(_appNamespace.c_str(), static_cast(_appNamespace.length())); + writer.String("appVersion"); + writer.String(_appVersion.c_str(), static_cast(_appVersion.length())); + writer.String("appBuild"); + writer.String(_appBuild.c_str(), static_cast(_appBuild.length())); + writer.String("sdkName"); + writer.String(_sdkName.c_str(), static_cast(_sdkName.length())); + writer.String("sdkVersion"); + writer.String(_sdkVersion.c_str(), static_cast(_sdkVersion.length())); + writer.String("osName"); + writer.String(_osName.c_str(), static_cast(_osName.length())); + writer.String("osVersion"); + writer.String(_osVersion.c_str(), static_cast(_osVersion.length())); + writer.String("osBuild"); + writer.String(_osBuild.c_str(), static_cast(_osBuild.length())); + writer.String("model"); + writer.String(_model.c_str(), static_cast(_model.length())); + writer.String("oemName"); + writer.String(_oemName.c_str(), static_cast(_oemName.length())); + writer.String("screenSize"); + writer.String(_screenSize.c_str(), static_cast(_screenSize.length())); + writer.String("locale"); + writer.String(_locale.c_str(), static_cast(_locale.length())); + writer.String("timeZoneOffset"); + writer.Uint(_timeZoneOffset); + + writer.EndObject(); + } + + string getOsVersion() + { + return _osBuild; + } + + private: + string _appNamespace = "Notepads.DesktopExtension"; + string _appVersion; + string _appBuild; + string _sdkName = "appcenter.uwp"; + string _sdkVersion; + string _osName; + string _osVersion; + string _osBuild; + string _model; + string _oemName; + string _screenSize; + string _locale; + unsigned _timeZoneOffset; + }; +} \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/packages.config b/src/Notepads.DesktopExtension/packages.config index 626739c5c..92ff0cc3a 100644 --- a/src/Notepads.DesktopExtension/packages.config +++ b/src/Notepads.DesktopExtension/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h index 7538f7218..4d7a95f46 100644 --- a/src/Notepads.DesktopExtension/pch.h +++ b/src/Notepads.DesktopExtension/pch.h @@ -12,7 +12,7 @@ #include "winrt/Windows.Storage.h" #include "winrt/Windows.System.h" #include "winrt/Windows.System.Profile.h" -#include "curl/curl.h" +#include "fmt/core.h" // These values depend upon constant fields described in ..\Notepads\Settings\SettingsKey.cs. // Changing value in one place require changing variable with similar name in another. @@ -34,7 +34,6 @@ void setExceptionHandling(); void exitApp(); void printDebugMessage(LPCTSTR message, DWORD sleepTime = 0); -void printDebugMessage(LPCTSTR message, LPCTSTR parameter, DWORD sleepTime = 0); std::string getTimeStamp(); std::string getTimeStamp(const char* format); std::string to_string(winrt::Windows::System::ProcessorArchitecture arch); @@ -46,18 +45,5 @@ winrt::fire_and_forget launchElevatedProcess(); void initializeAdminService(); winrt::Windows::Foundation::IInspectable readSettingsKey(winrt::hstring key); -winrt::Windows::Foundation::IAsyncAction logLastError(LPCTSTR errorTitle); -winrt::fire_and_forget initializeLogging(LPCTSTR trailStr); - -namespace AppCenter -{ - namespace - { - static std::string launchTimeStamp; - static char* appCenterJSON; - static struct curl_slist* headerList; - } - - void start(); - void trackError(DWORD errorCode, std::string message, bool isFatal); -} \ No newline at end of file +winrt::Windows::Foundation::IAsyncAction logLastError(bool isFatal); +winrt::fire_and_forget initializeLogging(LPCTSTR trailStr); \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/vcpkg.json b/src/Notepads.DesktopExtension/vcpkg.json index 3c4196fdf..5ff795de6 100644 --- a/src/Notepads.DesktopExtension/vcpkg.json +++ b/src/Notepads.DesktopExtension/vcpkg.json @@ -2,7 +2,8 @@ "name": "notepads-desktopextension", "version-string": "1.0.0.0", "dependencies": [ - "rapidjson", - "curl" + "curl", + "fmt", + "rapidjson" ] } \ No newline at end of file From 3bdbf7067a4cd2e2b904a8c612ea77b8dbf0f47c Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Tue, 15 Dec 2020 11:29:03 +0530 Subject: [PATCH 114/181] code refactor. --- src/Notepads.DesktopExtension/appcenter.cpp | 8 ++++---- src/Notepads.DesktopExtension/appcenter.h | 2 +- src/Notepads.DesktopExtension/debug.cpp | 15 +++++++-------- src/Notepads.DesktopExtension/elevated.cpp | 20 ++++++++++---------- src/Notepads.DesktopExtension/extension.cpp | 4 ++-- src/Notepads.DesktopExtension/log.h | 8 ++++---- src/Notepads.DesktopExtension/main.cpp | 16 ++++++++-------- src/Notepads.DesktopExtension/models.h | 11 ++++------- src/Notepads.DesktopExtension/pch.h | 4 ++-- 9 files changed, 42 insertions(+), 46 deletions(-) diff --git a/src/Notepads.DesktopExtension/appcenter.cpp b/src/Notepads.DesktopExtension/appcenter.cpp index e9d435297..ab3407dd2 100644 --- a/src/Notepads.DesktopExtension/appcenter.cpp +++ b/src/Notepads.DesktopExtension/appcenter.cpp @@ -43,15 +43,15 @@ void AppCenter::trackError(DWORD errorCode, const string& message, bool isFatal) string errorAttachmentId = to_string(to_hstring(GuidHelper::CreateNewGuid())); errorAttachmentId.erase(0, errorAttachmentId.find_first_not_of('{')).erase(errorAttachmentId.find_last_not_of('}') + 1); - WCHAR locale[LOCALE_NAME_MAX_LENGTH + 1]; + TCHAR locale[LOCALE_NAME_MAX_LENGTH + 1]; LCIDToLocaleName(GetThreadLocale(), locale, LOCALE_NAME_MAX_LENGTH, 0); - WCHAR localeDisplayName[LOCALE_NAME_MAX_LENGTH + 1]; + TCHAR localeDisplayName[LOCALE_NAME_MAX_LENGTH + 1]; GetLocaleInfoEx(locale, LOCALE_SENGLISHDISPLAYNAME, localeDisplayName, LOCALE_NAME_MAX_LENGTH); string isElevated = isElevatedProcess() ? "True" : "False"; string eventType = isFatal ? "OnWin32UnhandledException" : "OnWin32UnexpectedException"; - vector> properties; + vector> properties; properties.push_back(pair("Exception", format("Win32Exception: Exception of code no. {} was thrown.", errorCode))); properties.push_back(pair("Message", message)); properties.push_back(pair("Culture", to_string(localeDisplayName))); @@ -106,7 +106,7 @@ void AppCenter::trackError(DWORD errorCode, const string& message, bool isFatal) trackEvent(eventType, properties, crashReportSid); } -void AppCenter::trackEvent(const string& name, const vector>& properties, const string& sid) +void AppCenter::trackEvent(const string& name, const vector>& properties, const string& sid) { if (!AppCenterSecret) return; diff --git a/src/Notepads.DesktopExtension/appcenter.h b/src/Notepads.DesktopExtension/appcenter.h index 7af2343b3..c64bdd69c 100644 --- a/src/Notepads.DesktopExtension/appcenter.h +++ b/src/Notepads.DesktopExtension/appcenter.h @@ -19,5 +19,5 @@ namespace AppCenter void start(); void trackError(DWORD errorCode, const string& message, bool isFatal); - void trackEvent(const string& name, const vector>& properties, const string& sid = ""); + void trackEvent(const string& name, const vector>& properties, const string& sid = ""); } \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/debug.cpp b/src/Notepads.DesktopExtension/debug.cpp index 01d96fd4c..e50b5ca68 100644 --- a/src/Notepads.DesktopExtension/debug.cpp +++ b/src/Notepads.DesktopExtension/debug.cpp @@ -8,14 +8,13 @@ using namespace Windows::Foundation; using namespace Windows::Storage; using namespace Windows::System; -constexpr int MAX_TIME_STR = 20; -constexpr int MAX_DATE_STR = 20; -constexpr int MAX_DATETIME_STR = 100; +constexpr INT MAX_TIME_STR = 20; +constexpr INT MAX_DATE_STR = 20; +constexpr INT MAX_DATETIME_STR = 100; StorageFile logFile = nullptr; -void printDebugMessage(LPCTSTR message, DWORD sleepTime) -{ +void printDebugMessage([[maybe_unused]] LPCTSTR message, [[maybe_unused]] DWORD sleepTime) { #ifdef _DEBUG wcout << message << endl; Sleep(sleepTime); @@ -50,7 +49,7 @@ string getTimeStamp() return format("{}.{}Z", getTimeStamp("%FT%T"), systemTime.wMilliseconds); } -string getTimeStamp(const char* format) +string getTimeStamp(const CHAR* format) { time_t timePast = time(NULL); tm utcTime; @@ -66,7 +65,7 @@ string base64_encode(const string& in) { string out; - int val = 0, valb = -6; + INT val = 0, valb = -6; for (UCHAR c : in) { val = (val << 8) + c; valb += 8; @@ -102,7 +101,7 @@ IAsyncAction logLastError(bool isFatal) AppCenter::trackError(errorCode, to_string(msg), isFatal); - if (logFile != nullptr) + if (logFile) { SYSTEMTIME systemTime; GetSystemTime(&systemTime); diff --git a/src/Notepads.DesktopExtension/elevated.cpp b/src/Notepads.DesktopExtension/elevated.cpp index 88278973c..712f987c8 100644 --- a/src/Notepads.DesktopExtension/elevated.cpp +++ b/src/Notepads.DesktopExtension/elevated.cpp @@ -9,7 +9,7 @@ using namespace Windows::ApplicationModel; using namespace Windows::Foundation; using namespace Windows::Storage; -constexpr int PIPE_READ_BUFFER = MAX_PATH + 240; +constexpr INT PIPE_READ_BUFFER = MAX_PATH + 240; DWORD sessionId; @@ -20,7 +20,7 @@ IInspectable readSettingsKey(hstring key) hstring packageSid = unbox_value_or(readSettingsKey(PackageSidStr), L""); -DWORD WINAPI saveFileFromPipeData(LPVOID param) +DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) { setExceptionHandling(); @@ -41,25 +41,25 @@ DWORD WINAPI saveFileFromPipeData(LPVOID param) CreateThread(NULL, 0, saveFileFromPipeData, NULL, 0, NULL); - char readBuffer[PIPE_READ_BUFFER] = { 0 }; + CHAR readBuffer[PIPE_READ_BUFFER] = { 0 }; string pipeDataStr; DWORD byteRead; do { - if (ReadFile(hPipe, readBuffer, (PIPE_READ_BUFFER - 1) * sizeof(char), &byteRead, NULL)) + if (ReadFile(hPipe, readBuffer, (PIPE_READ_BUFFER - 1) * sizeof(CHAR), &byteRead, NULL)) { pipeDataStr.append(readBuffer); fill(begin(readBuffer), end(readBuffer), '\0'); } - } while (byteRead >= (PIPE_READ_BUFFER - 1) * sizeof(char)); + } while (byteRead >= (PIPE_READ_BUFFER - 1) * sizeof(CHAR)); // Need to cnvert pipe data string to UTF-16 to properly read unicode characters wstring pipeDataWstr; - int convertResult = MultiByteToWideChar(CP_UTF8, 0, pipeDataStr.c_str(), (int)strlen(pipeDataStr.c_str()), NULL, 0); + INT convertResult = MultiByteToWideChar(CP_UTF8, 0, pipeDataStr.c_str(), (INT)strlen(pipeDataStr.c_str()), NULL, 0); if (convertResult > 0) { pipeDataWstr.resize(convertResult); - MultiByteToWideChar(CP_UTF8, 0, pipeDataStr.c_str(), (int)pipeDataStr.size(), &pipeDataWstr[0], (int)pipeDataWstr.size()); + MultiByteToWideChar(CP_UTF8, 0, pipeDataStr.c_str(), (INT)pipeDataStr.size(), &pipeDataWstr[0], (INT)pipeDataWstr.size()); } wstringstream pipeData(pipeDataWstr); @@ -70,7 +70,7 @@ DWORD WINAPI saveFileFromPipeData(LPVOID param) getline(pipeData, memoryMapId, L'|'); getline(pipeData, dataArrayLengthStr); - int dataArrayLength = stoi(dataArrayLengthStr); + INT dataArrayLength = stoi(dataArrayLengthStr); wstring memoryMapName = format(L"AppContainerNamedObjects\\{}\\{}", packageSid, memoryMapId); HANDLE hMemory = OpenFileMapping(FILE_MAP_READ, FALSE, memoryMapName.c_str()); @@ -105,7 +105,7 @@ DWORD WINAPI saveFileFromPipeData(LPVOID param) CloseHandle(hMemory); } - if (WriteFile(hPipe, result, strlen(result) * sizeof(char), NULL, NULL)) FlushFileBuffers(hPipe); + if (WriteFile(hPipe, result, strlen(result) * sizeof(CHAR), NULL, NULL)) FlushFileBuffers(hPipe); CloseHandle(hPipe); @@ -119,7 +119,7 @@ DWORD WINAPI saveFileFromPipeData(LPVOID param) } printDebugMessage(L"Waiting on uwp app to send data."); - vector> properties; + vector> properties; properties.push_back(pair("Result", result)); AppCenter::trackEvent("OnWriteToSystemFileRequested", properties); diff --git a/src/Notepads.DesktopExtension/extension.cpp b/src/Notepads.DesktopExtension/extension.cpp index b284f5e70..64bf40dde 100644 --- a/src/Notepads.DesktopExtension/extension.cpp +++ b/src/Notepads.DesktopExtension/extension.cpp @@ -10,7 +10,7 @@ using namespace Windows::Foundation::Collections; HANDLE appExitJob = NULL; -AppServiceConnection interopServiceConnection = { 0 }; +AppServiceConnection interopServiceConnection = NULL; fire_and_forget launchElevatedProcess() { @@ -29,7 +29,7 @@ fire_and_forget launchElevatedProcess() shExInfo.hInstApp = 0; auto message = ValueSet(); - vector> properties; + vector> properties; message.Insert(InteropCommandLabel, box_value(CreateElevetedExtensionCommandStr)); if (ShellExecuteEx(&shExInfo)) { diff --git a/src/Notepads.DesktopExtension/log.h b/src/Notepads.DesktopExtension/log.h index d293e81fc..864ba8862 100644 --- a/src/Notepads.DesktopExtension/log.h +++ b/src/Notepads.DesktopExtension/log.h @@ -33,7 +33,7 @@ namespace AppCenter InitializeLog(); } - Log(LogType type, const string& id, const string& sid, bool isFatal, Exception* exception, const vector>& properties) : + Log(LogType type, const string& id, const string& sid, bool isFatal, Exception* exception, const vector>& properties) : _type(type), _id(id), _sid(sid), _fatal(isFatal), _exception(exception), _properties(properties) { InitializeLog(); @@ -53,7 +53,7 @@ namespace AppCenter #pragma region Constructor for event report - Log(LogType type, const string& id, const string& sid, const string& name, const vector>& properties) : + Log(LogType type, const string& id, const string& sid, const string& name, const vector>& properties) : _type(type), _id(id), _sid(sid), _name(name), _properties(properties) { InitializeLog(); @@ -156,7 +156,7 @@ namespace AppCenter { writer.String("properties"); writer.StartObject(); - for (vector>::const_iterator property = _properties.begin(); property != _properties.end(); ++property) + for (vector>::const_iterator property = _properties.begin(); property != _properties.end(); ++property) { writer.String(property->first); writer.String(property->second.c_str(), static_cast(property->second.length())); @@ -181,7 +181,7 @@ namespace AppCenter string _data; string _errorId; Exception* _exception = NULL; - vector> _properties; + vector> _properties; void InitializeLog() { diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index 6e65527f7..2b61c536c 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -9,7 +9,7 @@ constexpr LPCTSTR AdminExtensionMutexName = L"AdminExtensionMutexName"; HANDLE appExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL); extern HANDLE appExitJob; -int releaseResources() +INT releaseResources() { CloseHandle(appExitEvent); CloseHandle(appExitJob); @@ -41,10 +41,10 @@ void setExceptionHandling() bool isElevetedProcessLaunchRequested() { - bool result = false; + auto result = false; LPTSTR* argList; - int argCount; + INT argCount; argList = CommandLineToArgvW(GetCommandLine(), &argCount); if (argCount > 3 && wcscmp(argList[3], L"/admin") == 0) { @@ -56,9 +56,9 @@ bool isElevetedProcessLaunchRequested() bool isFirstInstance(LPCTSTR mutexName) { - bool result = true; + auto result = true; - auto hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, mutexName); + HANDLE hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, mutexName); if (!hMutex) { CreateMutex(NULL, FALSE, mutexName); @@ -76,7 +76,7 @@ bool isFirstInstance(LPCTSTR mutexName) bool isElevatedProcess() { - bool result = false; + auto result = false; HANDLE hToken = NULL; if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) @@ -98,9 +98,9 @@ bool isElevatedProcess() } #ifndef _DEBUG -int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) +INT APIENTRY wWinMain(_In_ HINSTANCE /* hInstance */, _In_opt_ HINSTANCE /* hPrevInstance */, _In_ LPWSTR /* lpCmdLine */, _In_ INT /* nCmdShow */) #else -int main() +INT main() #endif { setExceptionHandling(); diff --git a/src/Notepads.DesktopExtension/models.h b/src/Notepads.DesktopExtension/models.h index c2a5d4f07..67ee4ff4b 100644 --- a/src/Notepads.DesktopExtension/models.h +++ b/src/Notepads.DesktopExtension/models.h @@ -58,12 +58,9 @@ namespace AppCenter public: Device() { - HMODULE handle = ::GetModuleHandle(NULL); - HRSRC rc = FindResource(handle, MAKEINTRESOURCE(APPCENTER_JSON), MAKEINTRESOURCE(JSONFILE)); - HGLOBAL rcData = LoadResource(handle, rc); - DWORD size = SizeofResource(handle, rc); Document versionData; - versionData.Parse(static_cast(LockResource(rcData))); + versionData.Parse(static_cast(LockResource(LoadResource(GetModuleHandle(NULL), + FindResource(GetModuleHandle(NULL), MAKEINTRESOURCE(APPCENTER_JSON), MAKEINTRESOURCE(JSONFILE)))))); _appVersion = versionData["appVersion"].GetString(); _appBuild = versionData["appBuild"].GetString(); _sdkVersion = versionData["sdkVersion"].GetString(); @@ -86,9 +83,9 @@ namespace AppCenter GetWindowRect(GetDesktopWindow(), &desktop); _screenSize = format("{}x{}", desktop.right, desktop.bottom); - WCHAR locale[LOCALE_NAME_MAX_LENGTH + 1]; + TCHAR locale[LOCALE_NAME_MAX_LENGTH + 1]; LCIDToLocaleName(GetThreadLocale(), locale, LOCALE_NAME_MAX_LENGTH, 0); - WCHAR localeDisplayName[LOCALE_NAME_MAX_LENGTH + 1]; + TCHAR localeDisplayName[LOCALE_NAME_MAX_LENGTH + 1]; GetLocaleInfoEx(locale, LOCALE_SENGLISHDISPLAYNAME, localeDisplayName, LOCALE_NAME_MAX_LENGTH); _locale = to_string(locale); diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h index 4d7a95f46..1d6e53992 100644 --- a/src/Notepads.DesktopExtension/pch.h +++ b/src/Notepads.DesktopExtension/pch.h @@ -33,9 +33,9 @@ bool isElevatedProcess(); void setExceptionHandling(); void exitApp(); -void printDebugMessage(LPCTSTR message, DWORD sleepTime = 0); +void printDebugMessage([[maybe_unused]] LPCTSTR message, [[maybe_unused]] DWORD sleepTime = 0); std::string getTimeStamp(); -std::string getTimeStamp(const char* format); +std::string getTimeStamp(const CHAR* format); std::string to_string(winrt::Windows::System::ProcessorArchitecture arch); std::string base64_encode(const std::string& in); From df408928b470d490ab36fe13172f215356b2d3b2 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Wed, 16 Dec 2020 12:23:43 +0530 Subject: [PATCH 115/181] Implemented getting stacktrace in appcenter. --- .../Notepads.DesktopExtension.vcxproj | 5 +- .../Notepads.DesktopExtension.vcxproj.filters | 11 +- src/Notepads.DesktopExtension/appcenter.cpp | 9 +- src/Notepads.DesktopExtension/appcenter.h | 3 +- src/Notepads.DesktopExtension/debug.cpp | 13 +- .../{models.h => device.h} | 41 ------- src/Notepads.DesktopExtension/exception.h | 115 ++++++++++++++++++ src/Notepads.DesktopExtension/log.h | 3 +- src/Notepads.DesktopExtension/pch.h | 1 + src/Notepads.DesktopExtension/vcpkg.json | 1 + 10 files changed, 145 insertions(+), 57 deletions(-) rename src/Notepads.DesktopExtension/{models.h => device.h} (80%) create mode 100644 src/Notepads.DesktopExtension/exception.h diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index fc68e7663..8646cbccd 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -131,8 +131,9 @@ - - + + + diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters index 820cd8db0..6d9257866 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters @@ -47,12 +47,15 @@ AppCenter - + AppCenter - - + + AppCenter - + + + AppCenter + diff --git a/src/Notepads.DesktopExtension/appcenter.cpp b/src/Notepads.DesktopExtension/appcenter.cpp index ab3407dd2..728d62943 100644 --- a/src/Notepads.DesktopExtension/appcenter.cpp +++ b/src/Notepads.DesktopExtension/appcenter.cpp @@ -32,7 +32,7 @@ void AppCenter::start() headerList = curl_slist_append(headerList, format("install-id: {}", to_string(installId)).c_str()); } -void AppCenter::trackError(DWORD errorCode, const string& message, bool isFatal) +void AppCenter::trackError(bool isFatal, DWORD errorCode, const string& message, const stacktrace& stackTrace) { if (!AppCenterSecret) return; @@ -42,6 +42,8 @@ void AppCenter::trackError(DWORD errorCode, const string& message, bool isFatal) crashReportSid.erase(0, crashReportSid.find_first_not_of('{')).erase(crashReportSid.find_last_not_of('}') + 1); string errorAttachmentId = to_string(to_hstring(GuidHelper::CreateNewGuid())); errorAttachmentId.erase(0, errorAttachmentId.find_first_not_of('{')).erase(errorAttachmentId.find_last_not_of('}') + 1); + string eventReportId = to_string(to_hstring(GuidHelper::CreateNewGuid())); + eventReportId.erase(0, eventReportId.find_first_not_of('{')).erase(eventReportId.find_last_not_of('}') + 1); TCHAR locale[LOCALE_NAME_MAX_LENGTH + 1]; LCIDToLocaleName(GetThreadLocale(), locale, LOCALE_NAME_MAX_LENGTH, 0); @@ -63,10 +65,11 @@ void AppCenter::trackError(DWORD errorCode, const string& message, bool isFatal) properties.push_back(pair("IsElevated", isElevated)); vector errorReportSet; - errorReportSet.push_back(Log(LogType::managedError, crashReportId, crashReportSid, isFatal, new Exception(message), properties)); + errorReportSet.push_back(Log(LogType::managedError, crashReportId, crashReportSid, isFatal, new Exception(message, stackTrace), properties)); errorReportSet.push_back(Log(LogType::errorAttachment, errorAttachmentId, crashReportId, base64_encode(format("Exception: Win32Exception code no. {}, Message: {}, IsDesktopExtension: True, IsElevated: {}", errorCode, message, isElevated)))); + errorReportSet.push_back(Log(LogType::event, eventReportId, crashReportSid, eventType, properties)); StringBuffer errorReport; #ifdef _DEBUG @@ -102,8 +105,6 @@ void AppCenter::trackError(DWORD errorCode, const string& message, bool isFatal) } } curl_easy_cleanup(curl); - - trackEvent(eventType, properties, crashReportSid); } void AppCenter::trackEvent(const string& name, const vector>& properties, const string& sid) diff --git a/src/Notepads.DesktopExtension/appcenter.h b/src/Notepads.DesktopExtension/appcenter.h index c64bdd69c..c5795d2f8 100644 --- a/src/Notepads.DesktopExtension/appcenter.h +++ b/src/Notepads.DesktopExtension/appcenter.h @@ -10,6 +10,7 @@ namespace AppCenter { + using namespace boost::stacktrace; using namespace std; namespace @@ -18,6 +19,6 @@ namespace AppCenter } void start(); - void trackError(DWORD errorCode, const string& message, bool isFatal); + void trackError(bool isFatal, DWORD errorCode, const string& message, const stacktrace& stackTrace); void trackEvent(const string& name, const vector>& properties, const string& sid = ""); } \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/debug.cpp b/src/Notepads.DesktopExtension/debug.cpp index e50b5ca68..bff6de3f5 100644 --- a/src/Notepads.DesktopExtension/debug.cpp +++ b/src/Notepads.DesktopExtension/debug.cpp @@ -1,6 +1,8 @@ #include "pch.h" #include "appcenter.h" +using namespace boost::stacktrace; +using namespace boost::stacktrace::detail; using namespace fmt; using namespace std; using namespace winrt; @@ -81,9 +83,11 @@ string base64_encode(const string& in) IAsyncAction logLastError(bool isFatal) { + stacktrace st = stacktrace(); + hstring stackTrace = to_hstring(to_string(&st.as_vector()[0], st.size())); + LPVOID msgBuf; DWORD errorCode = GetLastError(); - FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, @@ -99,7 +103,8 @@ IAsyncAction logLastError(bool isFatal) LocalFree(msgBuf); getline(msgStrm, msg, L'\r'); - AppCenter::trackError(errorCode, to_string(msg), isFatal); + printDebugMessage(stackTrace.c_str(), 5000); + AppCenter::trackError(isFatal, errorCode, to_string(msg), st); if (logFile) { @@ -109,8 +114,8 @@ IAsyncAction logLastError(bool isFatal) GetTimeFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, NULL, timeStr, MAX_TIME_STR); TCHAR dateStr[MAX_DATE_STR]; GetDateFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, NULL, dateStr, MAX_DATE_STR, NULL); - wstring debugMsg = format(L"{} {} [Error] [Error Code: {}] {}{}\n", - dateStr, timeStr, errorCode, isFatal ? L"OnUnhandledException: " : L"OnUnexpectedException: ", msg); + wstring debugMsg = format(L"{} {} [Error] [Error Code: {}] {}{}\n{}\n", + dateStr, timeStr, errorCode, isFatal ? L"OnUnhandledException: " : L"OnUnexpectedException: ", msg, stackTrace); co_await PathIO::AppendTextAsync(logFile.Path(), debugMsg); } diff --git a/src/Notepads.DesktopExtension/models.h b/src/Notepads.DesktopExtension/device.h similarity index 80% rename from src/Notepads.DesktopExtension/models.h rename to src/Notepads.DesktopExtension/device.h index 67ee4ff4b..04cf5b1bc 100644 --- a/src/Notepads.DesktopExtension/models.h +++ b/src/Notepads.DesktopExtension/device.h @@ -12,47 +12,6 @@ namespace AppCenter using namespace Windows::Security::ExchangeActiveSyncProvisioning; using namespace Windows::System::Profile; - class Exception - { - public: - Exception(const string& message) : _message(message) {} - Exception(const string& message, const string& stackTrace) : _message(message), _stackTrace(stackTrace) {} - Exception(const Exception& exception) : _message(exception._message), _stackTrace(exception._stackTrace) {} - Exception(const exception& exception) : _message(exception.what()) {} - - ~Exception() {} - - Exception& operator=(const Exception& exception) - { - if (this == &exception) return *this; - - _type = exception._type; - _message = exception._message; - _stackTrace = exception._stackTrace; - return *this; - } - - template - void Serialize(Writer& writer) const - { - writer.StartObject(); - - writer.String("type"); - writer.String(_type.c_str(), static_cast(_type.length())); - writer.String("message"); - writer.String(_message.c_str(), static_cast(_message.length())); - writer.String("stackTrace"); - writer.String(_stackTrace.c_str(), static_cast(_stackTrace.length())); - - writer.EndObject(); - } - - private: - string _type = "Win32Exception"; - string _message; - string _stackTrace = ""; - }; - class Device { public: diff --git a/src/Notepads.DesktopExtension/exception.h b/src/Notepads.DesktopExtension/exception.h new file mode 100644 index 000000000..6655df05a --- /dev/null +++ b/src/Notepads.DesktopExtension/exception.h @@ -0,0 +1,115 @@ +#pragma once +#include "pch.h" + +namespace AppCenter +{ + using namespace boost::stacktrace; + using namespace std; + + class Frame + { + public: + Frame(const frame& frame) : _methodName(frame.name()), _fileName(frame.source_file()), _lineNumber(frame.source_line()) {} + Frame(const Frame& frame) : _methodName(frame._methodName), _fileName(frame._fileName), _lineNumber(frame._lineNumber) {} + + ~Frame() {} + + Frame& operator=(const Frame& frame) + { + if (this == &frame) return *this; + + _methodName = frame._methodName; + _fileName = frame._fileName; + _lineNumber = frame._lineNumber; + return *this; + } + + template + void Serialize(Writer& writer) const + { + if (_lineNumber <= 0 && _fileName.empty()) return; + + writer.StartObject(); + + writer.String("methodName"); + writer.String(_methodName.c_str(), static_cast(_methodName.length())); + writer.String("fileName"); + writer.String(_fileName.c_str(), static_cast(_fileName.length())); + writer.String("lineNumber"); + writer.Uint(_lineNumber); + + writer.EndObject(); + } + + private: + string _methodName; + string _fileName; + unsigned _lineNumber; + }; + + class Exception + { + public: + Exception(const string& message) : _message(message) {} + Exception(const string& message, const string& stackTrace) : _message(message), _stackTrace(stackTrace) {} + Exception(const Exception& exception) : _message(exception._message), _stackTrace(exception._stackTrace), _frames(exception._frames) {} + Exception(const exception& exception) : _message(exception.what()) {} + + Exception(const string& message, const stacktrace& stackTrace) : _message(message) + { + for (frame frame : stackTrace.as_vector()) + { + _frames.push_back(Frame(frame)); + } + } + + ~Exception() {} + + Exception& operator=(const Exception& exception) + { + if (this == &exception) return *this; + + _type = exception._type; + _message = exception._message; + _stackTrace = exception._stackTrace; + _frames = exception._frames; + return *this; + } + + template + void Serialize(Writer& writer) const + { + writer.StartObject(); + + writer.String("type"); + writer.String(_type.c_str(), static_cast(_type.length())); + writer.String("message"); + writer.String(_message.c_str(), static_cast(_message.length())); + + if (!_stackTrace.empty()) + { + writer.String("stackTrace"); + writer.String(_stackTrace.c_str(), static_cast(_stackTrace.length())); + } + + if (!_frames.empty()) + { + writer.String("frames"); + writer.StartArray(); + for (Frame frame : _frames) + { + frame.Serialize(writer); + } + writer.EndArray(); + } + + writer.EndObject(); + } + + private: + string _type = "Win32Exception"; + string _message; + string _stackTrace = ""; + vector _frames; + }; +} \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/log.h b/src/Notepads.DesktopExtension/log.h index 864ba8862..fb23bace5 100644 --- a/src/Notepads.DesktopExtension/log.h +++ b/src/Notepads.DesktopExtension/log.h @@ -1,6 +1,7 @@ #pragma once #include "pch.h" -#include "models.h" +#include "device.h" +#include "exception.h" namespace AppCenter { diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h index 1d6e53992..0cfdd252d 100644 --- a/src/Notepads.DesktopExtension/pch.h +++ b/src/Notepads.DesktopExtension/pch.h @@ -12,6 +12,7 @@ #include "winrt/Windows.Storage.h" #include "winrt/Windows.System.h" #include "winrt/Windows.System.Profile.h" +#include "boost/stacktrace.hpp" #include "fmt/core.h" // These values depend upon constant fields described in ..\Notepads\Settings\SettingsKey.cs. diff --git a/src/Notepads.DesktopExtension/vcpkg.json b/src/Notepads.DesktopExtension/vcpkg.json index 5ff795de6..f9cbc2e38 100644 --- a/src/Notepads.DesktopExtension/vcpkg.json +++ b/src/Notepads.DesktopExtension/vcpkg.json @@ -2,6 +2,7 @@ "name": "notepads-desktopextension", "version-string": "1.0.0.0", "dependencies": [ + "boost-stacktrace", "curl", "fmt", "rapidjson" From c844c49bf25ed2e0984e2d95f1bb4ee156ca6769 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Wed, 16 Dec 2020 20:09:54 +0530 Subject: [PATCH 116/181] code-refactor. --- .gitignore | 2 -- .../Notepads.DesktopExtension.vcxproj | 3 ++- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 1d03e007d..f0f425e17 100644 --- a/.gitignore +++ b/.gitignore @@ -357,6 +357,4 @@ Thumbs.db # vcpkg generated files # ######################### -**/ports/ -**/toolsrc/ **/vcpkg_installed/ \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index 8646cbccd..988524c69 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -163,7 +163,8 @@ - + + From 64df99be25ab371bd6d5728aafdc9105fd690118 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 18 Dec 2020 20:58:39 +0530 Subject: [PATCH 117/181] code refactor. --- .../Notepads.DesktopExtension.vcxproj | 14 ++++++-------- src/Notepads.DesktopExtension/PropertySheet.props | 7 ++++++- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index 988524c69..11f466067 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -81,9 +81,6 @@ - - c30903782c88967652178486a5f3e490fb2e8143 - true @@ -162,13 +159,14 @@ - - - - + + + + + - This project uses vcpkg that is missing on this computer. Manually download from https://github.com/microsoft/vcpkg and place the contents in {0}. Or install git and add it to your path, for more information see https://git-scm.com. The missing file is {1}. + This project uses vcpkg that is missing on this computer. Manually download from $(VcpkgRepo) and place the contents in {0}. Or install git and add it to your path, for more information see https://git-scm.com. The missing file is {1}. diff --git a/src/Notepads.DesktopExtension/PropertySheet.props b/src/Notepads.DesktopExtension/PropertySheet.props index b0c622690..359870bb2 100644 --- a/src/Notepads.DesktopExtension/PropertySheet.props +++ b/src/Notepads.DesktopExtension/PropertySheet.props @@ -11,6 +11,11 @@ For more advanced scenarios, and complete documentation, please see: https://github.com/Microsoft/cppwinrt/tree/master/nuget --> - + + https://github.com/microsoft/vcpkg + + e1417916bc1ed24bacd9cbc54bd42a99f996f618 + + \ No newline at end of file From cfda6d9186d4b2f8f034259c60d70450fb47c743 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 19 Dec 2020 17:38:23 +0530 Subject: [PATCH 118/181] code refactor. --- .gitignore | 6 +----- src/Notepads.DesktopExtension/.gitignore | 7 +++++++ src/Notepads.DesktopExtension/AssemblyInfo.rc | 5 +++-- .../Notepads.DesktopExtension.vcxproj | 2 +- .../Notepads.DesktopExtension.vcxproj.filters | 6 +++--- src/Notepads.DesktopExtension/appcenter.cpp | 2 -- src/Notepads.DesktopExtension/appcenter.json | 5 ----- src/Notepads.DesktopExtension/build.ps1 | 16 +++------------- src/Notepads.DesktopExtension/device.h | 15 ++++++++------- src/Notepads.DesktopExtension/log.h | 2 +- src/Notepads.DesktopExtension/resource.h | 4 ++-- 11 files changed, 29 insertions(+), 41 deletions(-) create mode 100644 src/Notepads.DesktopExtension/.gitignore delete mode 100644 src/Notepads.DesktopExtension/appcenter.json diff --git a/.gitignore b/.gitignore index f0f425e17..219b0c34a 100644 --- a/.gitignore +++ b/.gitignore @@ -353,8 +353,4 @@ healthchecksdb .Spotlight-V100 .Trashes ehthumbs.db -Thumbs.db - -# vcpkg generated files # -######################### -**/vcpkg_installed/ \ No newline at end of file +Thumbs.db \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/.gitignore b/src/Notepads.DesktopExtension/.gitignore new file mode 100644 index 000000000..b44ff4fd5 --- /dev/null +++ b/src/Notepads.DesktopExtension/.gitignore @@ -0,0 +1,7 @@ +# vcpkg generated files # +######################### +**/vcpkg_installed/ + +# AppCenter version file # +########################## +appcenter-sdk-version.txt \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/AssemblyInfo.rc b/src/Notepads.DesktopExtension/AssemblyInfo.rc index 63b4cc474..b55f9362e 100644 --- a/src/Notepads.DesktopExtension/AssemblyInfo.rc +++ b/src/Notepads.DesktopExtension/AssemblyInfo.rc @@ -97,8 +97,9 @@ END ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED + ///////////////////////////////////////////////////////////////////////////// // -// Custom json file for AppCenter data upload. +// TEXTFILE // -APPCENTER_JSON JSONFILE "appcenter.json" \ No newline at end of file +APPCENTER_SDK_VERSION TEXTFILE "appcenter-sdk-version.txt" \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index 11f466067..32764a493 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -145,7 +145,7 @@ - + diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters index 6d9257866..65438ce28 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters @@ -59,11 +59,11 @@ - - Resource Files - + + Resource Files + diff --git a/src/Notepads.DesktopExtension/appcenter.cpp b/src/Notepads.DesktopExtension/appcenter.cpp index 728d62943..1a3643f17 100644 --- a/src/Notepads.DesktopExtension/appcenter.cpp +++ b/src/Notepads.DesktopExtension/appcenter.cpp @@ -22,8 +22,6 @@ void AppCenter::start() { if (!AppCenterSecret) return; - launchTimeStamp = getTimeStamp(); - hstring installId = unbox_value_or(readSettingsKey(AppCenterInstallIdStr), L""); if (installId.empty()) return; diff --git a/src/Notepads.DesktopExtension/appcenter.json b/src/Notepads.DesktopExtension/appcenter.json deleted file mode 100644 index a7436cf1c..000000000 --- a/src/Notepads.DesktopExtension/appcenter.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "appVersion": "1.4.2.0", - "appBuild": "1.4.2.0", - "sdkVersion": "4.0.0" -} diff --git a/src/Notepads.DesktopExtension/build.ps1 b/src/Notepads.DesktopExtension/build.ps1 index 038126dbc..616b1c351 100644 --- a/src/Notepads.DesktopExtension/build.ps1 +++ b/src/Notepads.DesktopExtension/build.ps1 @@ -3,19 +3,9 @@ param ( ) $project_dir = Resolve-Path $project_dir.TrimEnd("\") -$appcenter_file = "${project_dir}\appcenter.json" -$manifest_file = "${project_dir}\..\Notepads.Package\Package.appxmanifest" +$appcenter_file = "${project_dir}\appcenter-sdk-version.txt" $uwp_project_file = "${project_dir}\..\Notepads\Notepads.csproj" -$appcenter_version_data = Get-Content $appcenter_file -raw | ConvertFrom-Json -[xml]$manifest = Get-Content $manifest_file +# Keep appcenter sdk version same as AppCenter nuget package version [xml]$sdk_target = Get-Content $uwp_project_file - -# Keep version string in same as package version -$appcenter_version_data.appVersion = $manifest.Package.Identity.Version -$appcenter_version_data.appBuild = $manifest.Package.Identity.Version - -# Keep appcenter sdk version same as nuget package version -$sdk_target.Project.ItemGroup.PackageReference | ForEach-Object {if($_.Include -eq 'Microsoft.AppCenter.Crashes'){$appcenter_version_data.sdkVersion = $_.Version}} - -$appcenter_version_data | ConvertTo-Json -depth 10| Set-Content $appcenter_file \ No newline at end of file +$sdk_target.Project.ItemGroup.PackageReference | ForEach-Object {if($_.Include -eq 'Microsoft.AppCenter.Crashes'){$_.Version | Set-Content $appcenter_file -NoNewline}} \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/device.h b/src/Notepads.DesktopExtension/device.h index 04cf5b1bc..fcbb654cf 100644 --- a/src/Notepads.DesktopExtension/device.h +++ b/src/Notepads.DesktopExtension/device.h @@ -1,7 +1,6 @@ #pragma once #include "pch.h" #include "resource.h" -#include "rapidjson/document.h" namespace AppCenter { @@ -9,6 +8,7 @@ namespace AppCenter using namespace rapidjson; using namespace std; using namespace winrt; + using namespace Windows::ApplicationModel; using namespace Windows::Security::ExchangeActiveSyncProvisioning; using namespace Windows::System::Profile; @@ -17,12 +17,13 @@ namespace AppCenter public: Device() { - Document versionData; - versionData.Parse(static_cast(LockResource(LoadResource(GetModuleHandle(NULL), - FindResource(GetModuleHandle(NULL), MAKEINTRESOURCE(APPCENTER_JSON), MAKEINTRESOURCE(JSONFILE)))))); - _appVersion = versionData["appVersion"].GetString(); - _appBuild = versionData["appBuild"].GetString(); - _sdkVersion = versionData["sdkVersion"].GetString(); + auto packageVersion = Package::Current().Id().Version(); + _appVersion = format("{}.{}.{}.{}", packageVersion.Major, packageVersion.Minor, packageVersion.Build, packageVersion.Revision); + _appBuild = _appVersion; + + HMODULE appModule = GetModuleHandle(NULL); + _sdkVersion = static_cast(LockResource(LoadResource(appModule, + FindResource(appModule, MAKEINTRESOURCE(APPCENTER_SDK_VERSION), MAKEINTRESOURCE(TEXTFILE))))); EasClientDeviceInformation oemInfo = EasClientDeviceInformation(); _osName = to_string(oemInfo.OperatingSystem()); diff --git a/src/Notepads.DesktopExtension/log.h b/src/Notepads.DesktopExtension/log.h index fb23bace5..b43d9906c 100644 --- a/src/Notepads.DesktopExtension/log.h +++ b/src/Notepads.DesktopExtension/log.h @@ -18,7 +18,7 @@ namespace AppCenter namespace { static const string logTypes[] = { "managedError", "errorAttachment", "event" }; - static string launchTimeStamp; + static string launchTimeStamp = getTimeStamp(); static Device deviceInfo = Device(); } diff --git a/src/Notepads.DesktopExtension/resource.h b/src/Notepads.DesktopExtension/resource.h index 60f181539..72d6e0329 100644 --- a/src/Notepads.DesktopExtension/resource.h +++ b/src/Notepads.DesktopExtension/resource.h @@ -2,8 +2,8 @@ // Microsoft Visual C++ generated include file. // Used by AssemblyInfo.rc // -#define APPCENTER_JSON 101 -#define JSONFILE 256 +#define APPCENTER_SDK_VERSION 101 +#define TEXTFILE 256 // Next default values for new objects // From 4b15f5c1bbad79e6799e53f0c9feb9baef5827ee Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Mon, 21 Dec 2020 00:32:35 +0530 Subject: [PATCH 119/181] Added crash analytics for background task. --- src/Notepads.DesktopExtension/elevated.cpp | 6 +-- .../DesktopExtensionConnectionService.cs | 48 ++++++++++++++++++- .../Notepads.Services.csproj | 8 +++- .../Services/DesktopExtensionService.cs | 8 +++- src/Notepads/Settings/SettingsKey.cs | 2 +- 5 files changed, 64 insertions(+), 8 deletions(-) diff --git a/src/Notepads.DesktopExtension/elevated.cpp b/src/Notepads.DesktopExtension/elevated.cpp index 712f987c8..532f062e2 100644 --- a/src/Notepads.DesktopExtension/elevated.cpp +++ b/src/Notepads.DesktopExtension/elevated.cpp @@ -41,15 +41,15 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) CreateThread(NULL, 0, saveFileFromPipeData, NULL, 0, NULL); - CHAR readBuffer[PIPE_READ_BUFFER] = { 0 }; + CHAR readBuffer[PIPE_READ_BUFFER] = { '\0' }; string pipeDataStr; DWORD byteRead; do { + fill(begin(readBuffer), end(readBuffer), '\0'); if (ReadFile(hPipe, readBuffer, (PIPE_READ_BUFFER - 1) * sizeof(CHAR), &byteRead, NULL)) { pipeDataStr.append(readBuffer); - fill(begin(readBuffer), end(readBuffer), '\0'); } } while (byteRead >= (PIPE_READ_BUFFER - 1) * sizeof(CHAR)); @@ -111,7 +111,7 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) if (strcmp(result, "Success") == 0) { - printDebugMessage(format(L"Successfully wrote to", filePath).c_str()); + printDebugMessage(format(L"Successfully wrote to \"{}\"", filePath).c_str()); } else { diff --git a/src/Notepads.Services/DesktopExtensionConnectionService.cs b/src/Notepads.Services/DesktopExtensionConnectionService.cs index 85ec7e48f..176c531e6 100644 --- a/src/Notepads.Services/DesktopExtensionConnectionService.cs +++ b/src/Notepads.Services/DesktopExtensionConnectionService.cs @@ -1,5 +1,8 @@ namespace Notepads.Services { + using Microsoft.AppCenter; + using Microsoft.AppCenter.Analytics; + using Microsoft.AppCenter.Crashes; using Notepads.Settings; using System; using System.Collections.Generic; @@ -21,6 +24,11 @@ public void Run(IBackgroundTaskInstance taskInstance) // Get a deferral so that the service isn't terminated. this.backgroundTaskDeferral = taskInstance.GetDeferral(); + TaskScheduler.UnobservedTaskException += OnUnobservedException; + + var services = new Type[] { typeof(Crashes), typeof(Analytics) }; + AppCenter.Start(SettingsKey.AppCenterSecret, services); + // Retrieve the app service connection and set up a listener for incoming app service requests. var details = taskInstance.TriggerDetails as AppServiceTriggerDetails; if(details.CallerPackageFamilyName == Package.Current.Id.FamilyName) @@ -90,7 +98,17 @@ private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequ message = response.Message; } } - await args.Request.SendResponseAsync(message); + + var res = await args.Request.SendResponseAsync(message); + if (res != AppServiceResponseStatus.Success) + { + var info = new Dictionary() + { + { "Response", res.ToString() } + }; + + Analytics.TrackEvent("OnAppServiceConnectionResponseToUWPFailed", info); + } } break; } @@ -121,5 +139,33 @@ private async void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTask } } } + + // Occurs when an exception is not handled on a background thread. + // ie. A task is fired and forgotten Task.Run(() => {...}) + private static void OnUnobservedException(object sender, UnobservedTaskExceptionEventArgs e) + { + //LoggingService.LogError($"[{nameof(App)}] OnUnobservedException: {e.Exception}"); + + var diagnosticInfo = new Dictionary() + { + { "Message", e.Exception?.Message }, + { "Exception", e.Exception?.ToString() }, + { "InnerException", e.Exception?.InnerException?.ToString() }, + { "InnerExceptionMessage", e.Exception?.InnerException?.Message } + }; + + var attachment = ErrorAttachmentLog.AttachmentWithText( + $"Exception: {e.Exception}, " + + $"Message: {e.Exception?.Message}, " + + $"InnerException: {e.Exception?.InnerException}, " + + $"InnerExceptionMessage: {e.Exception?.InnerException?.Message}", + "AppServiceUnobservedException"); + + Analytics.TrackEvent("OnAppServiceUnobservedException", diagnosticInfo); + Crashes.TrackError(e.Exception, diagnosticInfo, attachment); + + // suppress and handle it manually. + e.SetObserved(); + } } } diff --git a/src/Notepads.Services/Notepads.Services.csproj b/src/Notepads.Services/Notepads.Services.csproj index eec5069ee..23aea6b3b 100644 --- a/src/Notepads.Services/Notepads.Services.csproj +++ b/src/Notepads.Services/Notepads.Services.csproj @@ -107,8 +107,14 @@ + + 4.0.0 + + + 4.0.0 + - 6.2.10 + 6.2.11 diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index 21dbc5514..ab26eb464 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -103,8 +103,12 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) { if (InteropServiceConnection == null && !(await Initialize())) return; - using (var adminConnectionPipeStream = new NamedPipeServerStream($"Local\\{Package.Current.Id.FamilyName}\\{SettingsKey.AdminPipeConnectionNameStr}", - PipeDirection.InOut, 254, PipeTransmissionMode.Message, PipeOptions.Asynchronous)) + using (var adminConnectionPipeStream = new NamedPipeServerStream( + $"Local\\{Package.Current.Id.FamilyName}\\{SettingsKey.AdminPipeConnectionNameStr}", + PipeDirection.InOut, + NamedPipeServerStream.MaxAllowedServerInstances, + PipeTransmissionMode.Message, + PipeOptions.Asynchronous)) { // Wait for 250 ms for desktop extension to accept request. if (!adminConnectionPipeStream.WaitForConnectionAsync().Wait(250)) diff --git a/src/Notepads/Settings/SettingsKey.cs b/src/Notepads/Settings/SettingsKey.cs index b02a32b3b..771640bf9 100644 --- a/src/Notepads/Settings/SettingsKey.cs +++ b/src/Notepads/Settings/SettingsKey.cs @@ -39,13 +39,13 @@ internal static class SettingsKey // Interop related // These values depend upon constant fields described in ..\Notepads.DesktopExtension\pch.h. // Changing value in one place require changing variable with similar name in another. - internal const string AppCenterSecret = null; internal const string AppCenterInstallIdStr = "AppCenterInstallIdStr"; internal const string InteropServiceName = "DesktopExtensionServiceConnection"; // Keep this same as AppSeviceName value in manifest internal const string PackageSidStr = "PackageSidStr"; internal const string AdminPipeConnectionNameStr = "NotepadsAdminWritePipe"; internal const string InteropCommandAdminCreatedLabel = "AdminCreated"; #endif + internal const string AppCenterSecret = null; internal const string InteropCommandLabel = "Command"; internal const string InteropCommandFailedLabel = "Failed"; internal const string RegisterExtensionCommandStr = "RegisterExtension"; From 2cc55a35cf4ffe98c18479f73105c46375d91248 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Mon, 21 Dec 2020 11:31:36 +0530 Subject: [PATCH 120/181] code refactor. --- .../Notepads.DesktopExtension.vcxproj | 1 - .../Notepads.DesktopExtension.vcxproj.filters | 3 - src/Notepads.DesktopExtension/debug.cpp | 129 ------------------ src/Notepads.DesktopExtension/main.cpp | 14 +- src/Notepads.DesktopExtension/pch.cpp | 128 +++++++++++++++++ src/Notepads.DesktopExtension/pch.h | 2 +- 6 files changed, 134 insertions(+), 143 deletions(-) delete mode 100644 src/Notepads.DesktopExtension/debug.cpp diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index 32764a493..d65751b21 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -136,7 +136,6 @@ - diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters index 65438ce28..2204cd81c 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters @@ -30,9 +30,6 @@ Source Files - - Source Files - AppCenter diff --git a/src/Notepads.DesktopExtension/debug.cpp b/src/Notepads.DesktopExtension/debug.cpp deleted file mode 100644 index bff6de3f5..000000000 --- a/src/Notepads.DesktopExtension/debug.cpp +++ /dev/null @@ -1,129 +0,0 @@ -#include "pch.h" -#include "appcenter.h" - -using namespace boost::stacktrace; -using namespace boost::stacktrace::detail; -using namespace fmt; -using namespace std; -using namespace winrt; -using namespace Windows::Foundation; -using namespace Windows::Storage; -using namespace Windows::System; - -constexpr INT MAX_TIME_STR = 20; -constexpr INT MAX_DATE_STR = 20; -constexpr INT MAX_DATETIME_STR = 100; - -StorageFile logFile = nullptr; - -void printDebugMessage([[maybe_unused]] LPCTSTR message, [[maybe_unused]] DWORD sleepTime) { -#ifdef _DEBUG - wcout << message << endl; - Sleep(sleepTime); -#endif -} - -string to_string(ProcessorArchitecture arch) -{ - switch (arch) - { - case ProcessorArchitecture::Arm: - return "Arm"; - case ProcessorArchitecture::Arm64: - return "Arm64"; - case ProcessorArchitecture::X86OnArm64: - return "X86OnArm64"; - case ProcessorArchitecture::X86: - return "X86"; - case ProcessorArchitecture::X64: - return "X64"; - case ProcessorArchitecture::Neutral: - return "Neutral"; - default: - return "Unknown"; - } -} - -string getTimeStamp() -{ - SYSTEMTIME systemTime; - GetSystemTime(&systemTime); - return format("{}.{}Z", getTimeStamp("%FT%T"), systemTime.wMilliseconds); -} - -string getTimeStamp(const CHAR* format) -{ - time_t timePast = time(NULL); - tm utcTime; - gmtime_s(&utcTime, &timePast); - CHAR timeStamp[MAX_DATETIME_STR]; - strftime(timeStamp, sizeof(timeStamp), format, &utcTime); - return timeStamp; -} - -//From https://stackoverflow.com/a/34571089/5155484 -static const string b = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -string base64_encode(const string& in) -{ - string out; - - INT val = 0, valb = -6; - for (UCHAR c : in) { - val = (val << 8) + c; - valb += 8; - while (valb >= 0) { - out.push_back(b[(val >> valb) & 0x3F]); - valb -= 6; - } - } - if (valb > -6) out.push_back(b[((val << 8) >> (valb + 8)) & 0x3F]); - while (out.size() % 4) out.push_back('='); - return out; -} - -IAsyncAction logLastError(bool isFatal) -{ - stacktrace st = stacktrace(); - hstring stackTrace = to_hstring(to_string(&st.as_vector()[0], st.size())); - - LPVOID msgBuf; - DWORD errorCode = GetLastError(); - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - errorCode, - 0, - (LPTSTR)&msgBuf, - 0, - NULL); - - wstringstream msgStrm; - wstring msg; - msgStrm << (LPCTSTR)msgBuf; - LocalFree(msgBuf); - getline(msgStrm, msg, L'\r'); - - printDebugMessage(stackTrace.c_str(), 5000); - AppCenter::trackError(isFatal, errorCode, to_string(msg), st); - - if (logFile) - { - SYSTEMTIME systemTime; - GetSystemTime(&systemTime); - TCHAR timeStr[MAX_TIME_STR]; - GetTimeFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, NULL, timeStr, MAX_TIME_STR); - TCHAR dateStr[MAX_DATE_STR]; - GetDateFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, NULL, dateStr, MAX_DATE_STR, NULL); - wstring debugMsg = format(L"{} {} [Error] [Error Code: {}] {}{}\n{}\n", - dateStr, timeStr, errorCode, isFatal ? L"OnUnhandledException: " : L"OnUnexpectedException: ", msg, stackTrace); - - co_await PathIO::AppendTextAsync(logFile.Path(), debugMsg); - } -} - -fire_and_forget initializeLogging(LPCTSTR trailStr) -{ - auto localFolder = ApplicationData::Current().LocalFolder(); - auto logFolder = co_await localFolder.CreateFolderAsync(L"Logs", CreationCollisionOption::OpenIfExists); - logFile = co_await logFolder.CreateFileAsync(to_hstring(getTimeStamp("%Y%m%dT%H%M%S")) + to_hstring(trailStr), CreationCollisionOption::OpenIfExists); -} \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index 2b61c536c..303521939 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -62,11 +62,15 @@ bool isFirstInstance(LPCTSTR mutexName) if (!hMutex) { CreateMutex(NULL, FALSE, mutexName); + +#ifdef _DEBUG + initializeLogging(wcscmp(mutexName, DesktopExtensionMutexName) == 0 ? L"-extension.log" : L"-elevated-extension.log"); +#endif } else { result = false; - printDebugMessage(L"Closing this instance as another instance is already running.", 5000); + printDebugMessage(L"Closing this instance as another instance is already running.", 3000); exitApp(); } ReleaseMutex(hMutex); @@ -114,20 +118,12 @@ INT main() { if (!isFirstInstance(AdminExtensionMutexName)) return 0; -#ifdef _DEBUG - initializeLogging(L"-elevated-extension.log"); -#endif - initializeAdminService(); } else { if (!isFirstInstance(DesktopExtensionMutexName)) return 0; -#ifdef _DEBUG - initializeLogging(L"-extension.log"); -#endif - initializeInteropService(); if (isElevetedProcessLaunchRequested()) launchElevatedProcess(); } diff --git a/src/Notepads.DesktopExtension/pch.cpp b/src/Notepads.DesktopExtension/pch.cpp index bcb5590be..a89b2c8ba 100644 --- a/src/Notepads.DesktopExtension/pch.cpp +++ b/src/Notepads.DesktopExtension/pch.cpp @@ -1 +1,129 @@ #include "pch.h" +#include "appcenter.h" + +using namespace boost::stacktrace; +using namespace boost::stacktrace::detail; +using namespace fmt; +using namespace std; +using namespace winrt; +using namespace Windows::Foundation; +using namespace Windows::Storage; +using namespace Windows::System; + +constexpr INT MAX_TIME_STR = 20; +constexpr INT MAX_DATE_STR = 20; +constexpr INT MAX_DATETIME_STR = 100; + +StorageFile logFile = nullptr; + +void printDebugMessage([[maybe_unused]] LPCTSTR message, [[maybe_unused]] DWORD sleepTime) { +#ifdef _DEBUG + wcout << message << endl; + Sleep(sleepTime); +#endif +} + +string to_string(ProcessorArchitecture arch) +{ + switch (arch) + { + case ProcessorArchitecture::Arm: + return "Arm"; + case ProcessorArchitecture::Arm64: + return "Arm64"; + case ProcessorArchitecture::X86OnArm64: + return "X86OnArm64"; + case ProcessorArchitecture::X86: + return "X86"; + case ProcessorArchitecture::X64: + return "X64"; + case ProcessorArchitecture::Neutral: + return "Neutral"; + default: + return "Unknown"; + } +} + +string getTimeStamp() +{ + SYSTEMTIME systemTime; + GetSystemTime(&systemTime); + return format("{}.{}Z", getTimeStamp("%FT%T"), systemTime.wMilliseconds); +} + +string getTimeStamp(const CHAR* format) +{ + time_t timePast = time(NULL); + tm utcTime; + gmtime_s(&utcTime, &timePast); + CHAR timeStamp[MAX_DATETIME_STR]; + strftime(timeStamp, sizeof(timeStamp), format, &utcTime); + return timeStamp; +} + +//From https://stackoverflow.com/a/34571089/5155484 +static const string b = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +string base64_encode(const string& in) +{ + string out; + + INT val = 0, valb = -6; + for (UCHAR c : in) { + val = (val << 8) + c; + valb += 8; + while (valb >= 0) { + out.push_back(b[(val >> valb) & 0x3F]); + valb -= 6; + } + } + if (valb > -6) out.push_back(b[((val << 8) >> (valb + 8)) & 0x3F]); + while (out.size() % 4) out.push_back('='); + return out; +} + +IAsyncAction logLastError(bool isFatal) +{ + stacktrace st = stacktrace(); + hstring stackTrace = to_hstring(to_string(&st.as_vector()[0], st.size())); + + LPVOID msgBuf; + DWORD errorCode = GetLastError(); + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + errorCode, + 0, + (LPTSTR)&msgBuf, + 0, + NULL); + wcout << winrt::hresult_error(errorCode).message().c_str() << endl; + wstringstream msgStrm; + wstring msg; + msgStrm << (LPCTSTR)msgBuf; + LocalFree(msgBuf); + getline(msgStrm, msg, L'\r'); + + printDebugMessage(stackTrace.c_str(), 5000); + AppCenter::trackError(isFatal, errorCode, to_string(msg), st); + + if (logFile) + { + SYSTEMTIME systemTime; + GetSystemTime(&systemTime); + TCHAR timeStr[MAX_TIME_STR]; + GetTimeFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, NULL, timeStr, MAX_TIME_STR); + TCHAR dateStr[MAX_DATE_STR]; + GetDateFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, NULL, dateStr, MAX_DATE_STR, NULL); + wstring debugMsg = format(L"{} {} [Error] [Error Code: {}] {}{}\n{}\n", + dateStr, timeStr, errorCode, isFatal ? L"OnUnhandledException: " : L"OnUnexpectedException: ", msg, stackTrace); + + co_await PathIO::AppendTextAsync(logFile.Path(), debugMsg); + } +} + +fire_and_forget initializeLogging(LPCTSTR trailStr) +{ + auto localFolder = ApplicationData::Current().LocalFolder(); + auto logFolder = co_await localFolder.CreateFolderAsync(L"Logs", CreationCollisionOption::OpenIfExists); + logFile = co_await logFolder.CreateFileAsync(to_hstring(getTimeStamp("%Y%m%dT%H%M%S")) + to_hstring(trailStr), CreationCollisionOption::OpenIfExists); +} \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h index 0cfdd252d..b7ca0bc40 100644 --- a/src/Notepads.DesktopExtension/pch.h +++ b/src/Notepads.DesktopExtension/pch.h @@ -2,7 +2,7 @@ #pragma comment(lib, "shell32") #include "iostream" #include "sstream" -#include "Windows.h" +#include "windows.h" #include "shellapi.h" #include "winrt/Windows.ApplicationModel.h" #include "winrt/Windows.ApplicationModel.AppService.h" From 3104d2823084dad7544e6f30660791c4e6605687 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Mon, 21 Dec 2020 19:26:10 +0530 Subject: [PATCH 121/181] code refactor. --- src/Notepads/Services/DesktopExtensionService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index ab26eb464..3ab817948 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -132,7 +132,7 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) writer.Flush(); } - await pipeWriter.WriteLineAsync(string.Join('|', filePath, mapName, data.Length)); + await pipeWriter.WriteAsync($"{filePath}|{mapName}|{data.Length}"); await pipeWriter.FlushAsync(); // Wait for desktop extension to send response. From 10cb5cdbe37af85e332975f4160dfc0e35096c24 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Tue, 22 Dec 2020 21:13:12 +0530 Subject: [PATCH 122/181] code refactor. --- src/Notepads.DesktopExtension/elevated.cpp | 16 ++++++++-------- src/Notepads/Services/DesktopExtensionService.cs | 4 ++-- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Notepads.DesktopExtension/elevated.cpp b/src/Notepads.DesktopExtension/elevated.cpp index 532f062e2..68ba36b6b 100644 --- a/src/Notepads.DesktopExtension/elevated.cpp +++ b/src/Notepads.DesktopExtension/elevated.cpp @@ -9,7 +9,7 @@ using namespace Windows::ApplicationModel; using namespace Windows::Foundation; using namespace Windows::Storage; -constexpr INT PIPE_READ_BUFFER = MAX_PATH + 240; +constexpr INT PIPE_READ_BUFFER = 2 * MAX_PATH + 10; DWORD sessionId; @@ -24,7 +24,7 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) { setExceptionHandling(); - LPCSTR result = "Failed"; + LPCTSTR result = L"Failed"; wstring pipeName = format(L"\\\\.\\pipe\\Sessions\\{}\\AppContainerNamedObjects\\{}\\{}\\{}", sessionId, packageSid, Package::Current().Id().FamilyName(), AdminPipeConnectionNameStr); @@ -53,7 +53,7 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) } } while (byteRead >= (PIPE_READ_BUFFER - 1) * sizeof(CHAR)); - // Need to cnvert pipe data string to UTF-16 to properly read unicode characters + // Need to convert pipe data string to UTF-16 to properly read unicode characters wstring pipeDataWstr; INT convertResult = MultiByteToWideChar(CP_UTF8, 0, pipeDataStr.c_str(), (INT)strlen(pipeDataStr.c_str()), NULL, 0); if (convertResult > 0) @@ -93,7 +93,7 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) DWORD byteWrote; if (WriteFile(hFile, mapView, dataArrayLength, &byteWrote, NULL) && FlushFileBuffers(hFile)) { - result = "Success"; + result = L"Success"; } CloseHandle(hFile); @@ -105,22 +105,22 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) CloseHandle(hMemory); } - if (WriteFile(hPipe, result, strlen(result) * sizeof(CHAR), NULL, NULL)) FlushFileBuffers(hPipe); + if (WriteFile(hPipe, result, wcslen(result) * sizeof(TCHAR), NULL, NULL)) FlushFileBuffers(hPipe); CloseHandle(hPipe); - if (strcmp(result, "Success") == 0) + if (wcscmp(result, L"Success") == 0) { printDebugMessage(format(L"Successfully wrote to \"{}\"", filePath).c_str()); } else { - printDebugMessage(format(L"Failed to write to", filePath).c_str()); + printDebugMessage(format(L"Failed to write to \"{}\"", filePath).c_str()); } printDebugMessage(L"Waiting on uwp app to send data."); vector> properties; - properties.push_back(pair("Result", result)); + properties.push_back(pair("Result", to_string(result))); AppCenter::trackEvent("OnWriteToSystemFileRequested", properties); return 0; diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index 3ab817948..fe3656b7d 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -118,10 +118,10 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) throw new AdminstratorAccessException(); } - var pipeReader = new StreamReader(adminConnectionPipeStream); + var pipeReader = new StreamReader(adminConnectionPipeStream, System.Text.Encoding.Unicode); var pipeWriter = new StreamWriter(adminConnectionPipeStream); - var mapName = Guid.NewGuid().ToString(); + var mapName = filePath.Replace(Path.DirectorySeparatorChar, '-'); // Create the memory-mapped file and write original file data to be written. using (var mmf = MemoryMappedFile.CreateOrOpen(mapName, data.Length > 0 ? data.Length : 1, MemoryMappedFileAccess.ReadWrite)) From 74367bbe1d640501740619633ccd8ae435a2c2bc Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Wed, 23 Dec 2020 00:04:52 +0530 Subject: [PATCH 123/181] code refactor. --- src/Notepads.DesktopExtension/appcenter.cpp | 49 +++++++++++-------- src/Notepads.DesktopExtension/elevated.cpp | 25 +++------- src/Notepads.DesktopExtension/extension.cpp | 14 ++---- src/Notepads.DesktopExtension/pch.cpp | 5 +- .../Services/DesktopExtensionService.cs | 2 +- 5 files changed, 42 insertions(+), 53 deletions(-) diff --git a/src/Notepads.DesktopExtension/appcenter.cpp b/src/Notepads.DesktopExtension/appcenter.cpp index 1a3643f17..a0c624414 100644 --- a/src/Notepads.DesktopExtension/appcenter.cpp +++ b/src/Notepads.DesktopExtension/appcenter.cpp @@ -32,7 +32,7 @@ void AppCenter::start() void AppCenter::trackError(bool isFatal, DWORD errorCode, const string& message, const stacktrace& stackTrace) { - if (!AppCenterSecret) return; + if (!headerList) return; string crashReportId = to_string(to_hstring(GuidHelper::CreateNewGuid())); crashReportId.erase(0, crashReportId.find_first_not_of('{')).erase(crashReportId.find_last_not_of('}') + 1); @@ -51,23 +51,28 @@ void AppCenter::trackError(bool isFatal, DWORD errorCode, const string& message, string isElevated = isElevatedProcess() ? "True" : "False"; string eventType = isFatal ? "OnWin32UnhandledException" : "OnWin32UnexpectedException"; - vector> properties; - properties.push_back(pair("Exception", format("Win32Exception: Exception of code no. {} was thrown.", errorCode))); - properties.push_back(pair("Message", message)); - properties.push_back(pair("Culture", to_string(localeDisplayName))); - properties.push_back(pair("AvailableMemory", to_string((FLOAT)MemoryManager::AppMemoryUsageLimit() / 1024 / 1024))); - properties.push_back(pair("FirstUseTimeUTC", getTimeStamp("%m/%d/%Y %T"))); - properties.push_back(pair("OSArchitecture", to_string(Package::Current().Id().Architecture()))); - properties.push_back(pair("OSVersion", deviceInfo.getOsVersion())); - properties.push_back(pair("IsDesktopExtension", "True")); - properties.push_back(pair("IsElevated", isElevated)); - - vector errorReportSet; - errorReportSet.push_back(Log(LogType::managedError, crashReportId, crashReportSid, isFatal, new Exception(message, stackTrace), properties)); - errorReportSet.push_back(Log(LogType::errorAttachment, errorAttachmentId, crashReportId, - base64_encode(format("Exception: Win32Exception code no. {}, Message: {}, IsDesktopExtension: True, IsElevated: {}", - errorCode, message, isElevated)))); - errorReportSet.push_back(Log(LogType::event, eventReportId, crashReportSid, eventType, properties)); + vector> properties + { + pair("Exception", format("Win32Exception: Exception of code no. {} was thrown.", errorCode)), + pair("Message", message), + pair("Culture", to_string(localeDisplayName)), + pair("AvailableMemory", to_string((FLOAT)MemoryManager::AppMemoryUsageLimit() / 1024 / 1024)), + pair("FirstUseTimeUTC", getTimeStamp("%m/%d/%Y %T")), + pair("OSArchitecture", to_string(Package::Current().Id().Architecture())), + pair("OSVersion", deviceInfo.getOsVersion()), + pair("IsDesktopExtension", "True"), + pair("IsElevated", isElevated) + }; + + + vector errorReportSet + { + Log(LogType::managedError, crashReportId, crashReportSid, isFatal, new Exception(message, stackTrace), properties), + Log(LogType::errorAttachment, errorAttachmentId, crashReportId, base64_encode( + format("Exception: Win32Exception code no. {}, Message: {}, IsDesktopExtension: True, IsElevated: {}", + errorCode, message, isElevated))), + Log(LogType::event, eventReportId, crashReportSid, eventType, properties) + }; StringBuffer errorReport; #ifdef _DEBUG @@ -87,7 +92,8 @@ void AppCenter::trackError(bool isFatal, DWORD errorCode, const string& message, writer.EndObject(); CURL* curl = curl_easy_init(); - if (curl) { + if (curl) + { curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerList); curl_easy_setopt(curl, CURLOPT_URL, APPCENTER_ENDPOINT); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, errorReport.GetString()); @@ -107,7 +113,7 @@ void AppCenter::trackError(bool isFatal, DWORD errorCode, const string& message, void AppCenter::trackEvent(const string& name, const vector>& properties, const string& sid) { - if (!AppCenterSecret) return; + if (!headerList) return; string eventReportId = to_string(to_hstring(GuidHelper::CreateNewGuid())); eventReportId.erase(0, eventReportId.find_first_not_of('{')).erase(eventReportId.find_last_not_of('}') + 1); @@ -127,7 +133,8 @@ void AppCenter::trackEvent(const string& name, const vector= 0) { - pipeDataStr.append(readBuffer); + pipeData << readBuffer; } - } while (byteRead >= (PIPE_READ_BUFFER - 1) * sizeof(CHAR)); - - // Need to convert pipe data string to UTF-16 to properly read unicode characters - wstring pipeDataWstr; - INT convertResult = MultiByteToWideChar(CP_UTF8, 0, pipeDataStr.c_str(), (INT)strlen(pipeDataStr.c_str()), NULL, 0); - if (convertResult > 0) - { - pipeDataWstr.resize(convertResult); - MultiByteToWideChar(CP_UTF8, 0, pipeDataStr.c_str(), (INT)pipeDataStr.size(), &pipeDataWstr[0], (INT)pipeDataWstr.size()); - } - wstringstream pipeData(pipeDataWstr); + ++count; + } while (byteRead >= (PIPE_READ_BUFFER - 1) * sizeof(TCHAR) || count <= 0); wstring filePath; wstring memoryMapId; @@ -119,8 +111,7 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) } printDebugMessage(L"Waiting on uwp app to send data."); - vector> properties; - properties.push_back(pair("Result", to_string(result))); + vector> properties{ pair("Result", to_string(result)) }; AppCenter::trackEvent("OnWriteToSystemFileRequested", properties); return 0; diff --git a/src/Notepads.DesktopExtension/extension.cpp b/src/Notepads.DesktopExtension/extension.cpp index 64bf40dde..59ac6bd03 100644 --- a/src/Notepads.DesktopExtension/extension.cpp +++ b/src/Notepads.DesktopExtension/extension.cpp @@ -17,16 +17,7 @@ fire_and_forget launchElevatedProcess() TCHAR fileName[MAX_PATH]; GetModuleFileName(NULL, fileName, MAX_PATH); - SHELLEXECUTEINFO shExInfo = { 0 }; - shExInfo.cbSize = sizeof(shExInfo); - shExInfo.fMask = SEE_MASK_NOCLOSEPROCESS; - shExInfo.hwnd = 0; - shExInfo.lpVerb = L"runas"; - shExInfo.lpFile = fileName; - shExInfo.lpParameters = L""; - shExInfo.lpDirectory = 0; - shExInfo.nShow = SW_SHOW; - shExInfo.hInstApp = 0; + SHELLEXECUTEINFO shExInfo{ sizeof(shExInfo), SEE_MASK_NOCLOSEPROCESS, 0, L"runas", fileName, L"", 0, SW_SHOW, 0 }; auto message = ValueSet(); vector> properties; @@ -34,12 +25,13 @@ fire_and_forget launchElevatedProcess() if (ShellExecuteEx(&shExInfo)) { // Create Job to close child process when parent exits/crashes. + TerminateJobObject(appExitJob, 0); if (appExitJob) CloseHandle(appExitJob); appExitJob = CreateJobObject(NULL, NULL); JOBOBJECT_EXTENDED_LIMIT_INFORMATION info = { 0 }; info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; SetInformationJobObject(appExitJob, JobObjectExtendedLimitInformation, &info, sizeof(info)); - AssignProcessToJobObject(appExitJob, shExInfo.hProcess); + if (shExInfo.hProcess) AssignProcessToJobObject(appExitJob, shExInfo.hProcess); message.Insert(InteropCommandAdminCreatedLabel, box_value(true)); printDebugMessage(L"Adminstrator Extension has been launched."); diff --git a/src/Notepads.DesktopExtension/pch.cpp b/src/Notepads.DesktopExtension/pch.cpp index a89b2c8ba..948969c64 100644 --- a/src/Notepads.DesktopExtension/pch.cpp +++ b/src/Notepads.DesktopExtension/pch.cpp @@ -96,10 +96,9 @@ IAsyncAction logLastError(bool isFatal) (LPTSTR)&msgBuf, 0, NULL); - wcout << winrt::hresult_error(errorCode).message().c_str() << endl; - wstringstream msgStrm; + + wstringstream msgStrm((LPCTSTR)msgBuf); wstring msg; - msgStrm << (LPCTSTR)msgBuf; LocalFree(msgBuf); getline(msgStrm, msg, L'\r'); diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index fe3656b7d..0b2510c20 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -119,7 +119,7 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) } var pipeReader = new StreamReader(adminConnectionPipeStream, System.Text.Encoding.Unicode); - var pipeWriter = new StreamWriter(adminConnectionPipeStream); + var pipeWriter = new StreamWriter(adminConnectionPipeStream, System.Text.Encoding.Unicode); var mapName = filePath.Replace(Path.DirectorySeparatorChar, '-'); From 1edee0e072a713f3e656c01241bd4d2b77561cd3 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Wed, 23 Dec 2020 14:44:20 +0530 Subject: [PATCH 124/181] Added more crash analytics. --- src/Notepads.DesktopExtension/elevated.cpp | 10 +++++- src/Notepads.DesktopExtension/extension.cpp | 21 ++++++++++-- src/Notepads.DesktopExtension/pch.cpp | 19 +++++++---- src/Notepads.DesktopExtension/pch.h | 1 + src/Notepads/App.xaml.cs | 2 -- .../Services/DesktopExtensionService.cs | 34 +++++++++++-------- .../Views/MainPage/NotepadsMainPage.xaml.cs | 5 +-- 7 files changed, 61 insertions(+), 31 deletions(-) diff --git a/src/Notepads.DesktopExtension/elevated.cpp b/src/Notepads.DesktopExtension/elevated.cpp index 85832fad4..71ae8d272 100644 --- a/src/Notepads.DesktopExtension/elevated.cpp +++ b/src/Notepads.DesktopExtension/elevated.cpp @@ -24,6 +24,7 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) { setExceptionHandling(); + vector> properties; LPCTSTR result = L"Failed"; wstring pipeName = format(L"\\\\.\\pipe\\Sessions\\{}\\AppContainerNamedObjects\\{}\\{}\\{}", @@ -101,17 +102,24 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) CloseHandle(hPipe); + properties.push_back(pair("Result", to_string(result))); if (wcscmp(result, L"Success") == 0) { printDebugMessage(format(L"Successfully wrote to \"{}\"", filePath).c_str()); } else { + pair ex = getLastErrorDetails(); + properties.insert(properties.end(), + { + pair("Error Code", to_string(ex.first)), + pair("Error Message", winrt::to_string(ex.second)) + }); + printDebugMessage(format(L"Failed to write to \"{}\"", filePath).c_str()); } printDebugMessage(L"Waiting on uwp app to send data."); - vector> properties{ pair("Result", to_string(result)) }; AppCenter::trackEvent("OnWriteToSystemFileRequested", properties); return 0; diff --git a/src/Notepads.DesktopExtension/extension.cpp b/src/Notepads.DesktopExtension/extension.cpp index 59ac6bd03..4c5bb0c7f 100644 --- a/src/Notepads.DesktopExtension/extension.cpp +++ b/src/Notepads.DesktopExtension/extension.cpp @@ -40,11 +40,18 @@ fire_and_forget launchElevatedProcess() else { message.Insert(InteropCommandAdminCreatedLabel, box_value(false)); - printDebugMessage(L"User canceled launching of Adminstrator Extension."); - properties.push_back(pair("Denied", "True")); + printDebugMessage(L"Launching of Adminstrator Extension was cancelled."); + + pair ex = getLastErrorDetails(); + properties.insert(properties.end(), + { + pair("Denied", "True"), + pair("Error Code", to_string(ex.first)), + pair("Error Message", to_string(ex.second)) + }); } co_await interopServiceConnection.SendMessageAsync(message); - AppCenter::trackEvent("OnAdminstratorPrivilageGranted", properties); + AppCenter::trackEvent("OnAdminstratorPrivilageRequested", properties); } void onConnectionServiceRequestRecieved(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) @@ -89,6 +96,14 @@ fire_and_forget initializeInteropService() auto status = co_await interopServiceConnection.OpenAsync(); if (status != AppServiceConnectionStatus::Success) { + pair ex = getLastErrorDetails(); + vector> properties + { + pair("Error Code", to_string(ex.first)), + pair("Error Message", to_string(ex.second)) + }; + + AppCenter::trackEvent("OnWin32ConnectionToAppServiceFailed", properties); exitApp(); } diff --git a/src/Notepads.DesktopExtension/pch.cpp b/src/Notepads.DesktopExtension/pch.cpp index 948969c64..2ba19488a 100644 --- a/src/Notepads.DesktopExtension/pch.cpp +++ b/src/Notepads.DesktopExtension/pch.cpp @@ -81,11 +81,8 @@ string base64_encode(const string& in) return out; } -IAsyncAction logLastError(bool isFatal) +pair getLastErrorDetails() { - stacktrace st = stacktrace(); - hstring stackTrace = to_hstring(to_string(&st.as_vector()[0], st.size())); - LPVOID msgBuf; DWORD errorCode = GetLastError(); FormatMessage( @@ -102,8 +99,18 @@ IAsyncAction logLastError(bool isFatal) LocalFree(msgBuf); getline(msgStrm, msg, L'\r'); + return pair { errorCode, msg }; +} + +IAsyncAction logLastError(bool isFatal) +{ + stacktrace st = stacktrace(); + hstring stackTrace = to_hstring(to_string(&st.as_vector()[0], st.size())); + + pair ex = getLastErrorDetails(); + printDebugMessage(stackTrace.c_str(), 5000); - AppCenter::trackError(isFatal, errorCode, to_string(msg), st); + AppCenter::trackError(isFatal, ex.first, to_string(ex.second), st); if (logFile) { @@ -114,7 +121,7 @@ IAsyncAction logLastError(bool isFatal) TCHAR dateStr[MAX_DATE_STR]; GetDateFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, NULL, dateStr, MAX_DATE_STR, NULL); wstring debugMsg = format(L"{} {} [Error] [Error Code: {}] {}{}\n{}\n", - dateStr, timeStr, errorCode, isFatal ? L"OnUnhandledException: " : L"OnUnexpectedException: ", msg, stackTrace); + dateStr, timeStr, ex.first, isFatal ? L"OnUnhandledException: " : L"OnUnexpectedException: ", ex.second, stackTrace); co_await PathIO::AppendTextAsync(logFile.Path(), debugMsg); } diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h index b7ca0bc40..f0b66e41a 100644 --- a/src/Notepads.DesktopExtension/pch.h +++ b/src/Notepads.DesktopExtension/pch.h @@ -46,5 +46,6 @@ winrt::fire_and_forget launchElevatedProcess(); void initializeAdminService(); winrt::Windows::Foundation::IInspectable readSettingsKey(winrt::hstring key); +std::pair getLastErrorDetails(); winrt::Windows::Foundation::IAsyncAction logLastError(bool isFatal); winrt::fire_and_forget initializeLogging(LPCTSTR trailStr); \ No newline at end of file diff --git a/src/Notepads/App.xaml.cs b/src/Notepads/App.xaml.cs index 41bc7623e..9a9082b85 100644 --- a/src/Notepads/App.xaml.cs +++ b/src/Notepads/App.xaml.cs @@ -49,8 +49,6 @@ public App() InitializeComponent(); Suspending += OnSuspending; - - DesktopExtensionService.InitializeDesktopExtension(); } /// diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index 0b2510c20..01a22d1e8 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -1,9 +1,12 @@ namespace Notepads.Services { using Microsoft.AppCenter; + using Microsoft.AppCenter.Analytics; + using Microsoft.Toolkit.Uwp.Helpers; using Notepads.Extensions; using Notepads.Settings; using System; + using System.Collections.Generic; using System.IO; using System.IO.MemoryMappedFiles; using System.IO.Pipes; @@ -16,8 +19,6 @@ using Windows.Foundation.Collections; using Windows.Foundation.Metadata; using Windows.Security.Authentication.Web; - using Windows.UI.ViewManagement; - using Windows.UI.Xaml; public class AdminstratorAccessException : Exception { @@ -34,17 +35,6 @@ public static class DesktopExtensionService !new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); private static readonly ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView(); - public static async void InitializeDesktopExtension() - { - if (!ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0) || - new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) return; - - ApplicationSettingsStore.Write(SettingsKey.PackageSidStr, WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host.ToUpper()); - var appcenterInstallidstr = (await AppCenter.GetInstallIdAsync())?.ToString(); - ApplicationSettingsStore.Write(SettingsKey.AppCenterInstallIdStr, appcenterInstallidstr); - await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); - } - public static async Task Initialize() { if (!ShouldUseDesktopExtension) return false; @@ -59,11 +49,25 @@ public static async Task Initialize() InteropServiceConnection.ServiceClosed += InteropServiceConnection_ServiceClosed; AppServiceConnectionStatus status = await InteropServiceConnection.OpenAsync(); - if (status != AppServiceConnectionStatus.Success && !await ApplicationView.GetForCurrentView().TryConsolidateAsync()) + if (status != AppServiceConnectionStatus.Success) { - Application.Current.Exit(); + Analytics.TrackEvent("OnConnectionToAppServiceFailed", new Dictionary + { + { "ConnectionStatus", status.ToString() }, + { "Culture", SystemInformation.Culture.EnglishName }, + { "AvailableMemory", SystemInformation.AvailableMemory.ToString("F0") }, + { "FirstUseTimeUTC", SystemInformation.FirstUseTime.ToUniversalTime().ToString("MM/dd/yyyy HH:mm:ss") }, + { "OSArchitecture", SystemInformation.OperatingSystemArchitecture.ToString() }, + { "OSVersion", SystemInformation.OperatingSystemVersion.ToString() } + }); + + return false; } + ApplicationSettingsStore.Write(SettingsKey.PackageSidStr, WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host.ToUpper()); + ApplicationSettingsStore.Write(SettingsKey.AppCenterInstallIdStr, (await AppCenter.GetInstallIdAsync())?.ToString()); + await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); + return true; } diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs index 339aa01ce..af8a159c7 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs @@ -297,10 +297,7 @@ private async void App_EnteredBackground(object sender, Windows.ApplicationModel private async void App_LeavingBackground(object sender, LeavingBackgroundEventArgs e) { - if (await DesktopExtensionService.Initialize()) - { - await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); - } + await DesktopExtensionService.Initialize(); } public void ExecuteProtocol(Uri uri) From e4ed6032746a8de31f639bc60d67452c0118c14b Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Wed, 23 Dec 2020 16:16:08 +0530 Subject: [PATCH 125/181] Updated vcpkg. --- src/Notepads.DesktopExtension/PropertySheet.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Notepads.DesktopExtension/PropertySheet.props b/src/Notepads.DesktopExtension/PropertySheet.props index 359870bb2..b0c60bb33 100644 --- a/src/Notepads.DesktopExtension/PropertySheet.props +++ b/src/Notepads.DesktopExtension/PropertySheet.props @@ -14,7 +14,7 @@ https://github.com/microsoft/vcpkg - e1417916bc1ed24bacd9cbc54bd42a99f996f618 + c54abfafbe0051075952c507da1f1ec234875e05 From 91f046103c3b5c95198ba89da3a32b841cbc3d1c Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Wed, 23 Dec 2020 18:10:17 +0530 Subject: [PATCH 126/181] Neglect BOM during pipe write in uwp app. --- src/Notepads.DesktopExtension/elevated.cpp | 6 ++---- src/Notepads/Services/DesktopExtensionService.cs | 8 +++++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Notepads.DesktopExtension/elevated.cpp b/src/Notepads.DesktopExtension/elevated.cpp index 71ae8d272..ce37c8c9b 100644 --- a/src/Notepads.DesktopExtension/elevated.cpp +++ b/src/Notepads.DesktopExtension/elevated.cpp @@ -45,16 +45,14 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) TCHAR readBuffer[PIPE_READ_BUFFER]; wstringstream pipeData; DWORD byteRead; - INT count = -1; do { fill(begin(readBuffer), end(readBuffer), '\0'); - if (ReadFile(hPipe, readBuffer, (PIPE_READ_BUFFER - 1) * sizeof(TCHAR), &byteRead, NULL) && count >= 0) + if (ReadFile(hPipe, readBuffer, (PIPE_READ_BUFFER - 1) * sizeof(TCHAR), &byteRead, NULL)) { pipeData << readBuffer; } - ++count; - } while (byteRead >= (PIPE_READ_BUFFER - 1) * sizeof(TCHAR) || count <= 0); + } while (byteRead >= (PIPE_READ_BUFFER - 1) * sizeof(TCHAR)); wstring filePath; wstring memoryMapId; diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index 01a22d1e8..20f20c52a 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -122,8 +122,8 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) throw new AdminstratorAccessException(); } - var pipeReader = new StreamReader(adminConnectionPipeStream, System.Text.Encoding.Unicode); - var pipeWriter = new StreamWriter(adminConnectionPipeStream, System.Text.Encoding.Unicode); + var pipeReader = new StreamReader(adminConnectionPipeStream, new System.Text.UnicodeEncoding(!BitConverter.IsLittleEndian, false)); + var pipeWriter = new StreamWriter(adminConnectionPipeStream, new System.Text.UnicodeEncoding(!BitConverter.IsLittleEndian, false)); var mapName = filePath.Replace(Path.DirectorySeparatorChar, '-'); @@ -167,7 +167,9 @@ public static async Task CreateElevetedExtension() var response = await InteropServiceConnection.SendMessageAsync(message); message = response.Message; - if (message?.ContainsKey(SettingsKey.InteropCommandFailedLabel) ?? false && (bool)message[SettingsKey.InteropCommandFailedLabel]) + if (response.Status != AppServiceResponseStatus.Success || + (message?.ContainsKey(SettingsKey.InteropCommandFailedLabel) ?? false && + (bool)message[SettingsKey.InteropCommandFailedLabel])) { // Pass the group id that describes the correct parameter for prompting admin process launch await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync("LaunchAdmin"); From d72532176641e1b50194a4d7049661cc45a2caa1 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 24 Dec 2020 10:19:13 +0530 Subject: [PATCH 127/181] Updated C++ language version. --- .../Notepads.DesktopExtension.vcxproj | 4 ++-- src/Notepads.DesktopExtension/elevated.cpp | 3 +-- src/Notepads.DesktopExtension/extension.cpp | 21 +++++++++++++--- src/Notepads.DesktopExtension/main.cpp | 5 ++-- src/Notepads.DesktopExtension/pch.cpp | 7 +++--- src/Notepads.DesktopExtension/vcpkg.json | 24 +++++++++++++++---- 6 files changed, 45 insertions(+), 19 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index d65751b21..db592fd4a 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -9,7 +9,7 @@ 15.0 {0a3b698e-6add-4c9e-9741-08f8ae576b2e} Win32Proj - Notepads_DesktopExtension + Notepads.DesktopExtension $(ProjectDir)bin\$(Platform)\$(Configuration)\ obj\$(Platform)\$(Configuration)\ Notepads32 @@ -91,7 +91,7 @@ _CONSOLE;WIN32_LEAN_AND_MEAN;WINRT_LEAN_AND_MEAN;%(PreprocessorDefinitions) Level4 %(AdditionalOptions) /permissive- /bigobj - stdcpp17 + stdcpplatest powershell -ExecutionPolicy Bypass $(ProjectDir)build.ps1 -project_dir $(ProjectDir) diff --git a/src/Notepads.DesktopExtension/elevated.cpp b/src/Notepads.DesktopExtension/elevated.cpp index ce37c8c9b..ff782d1e7 100644 --- a/src/Notepads.DesktopExtension/elevated.cpp +++ b/src/Notepads.DesktopExtension/elevated.cpp @@ -81,8 +81,7 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) if (hFile) { - DWORD byteWrote; - if (WriteFile(hFile, mapView, dataArrayLength, &byteWrote, NULL) && FlushFileBuffers(hFile)) + if (WriteFile(hFile, mapView, dataArrayLength, NULL, NULL) && FlushFileBuffers(hFile)) { result = L"Success"; } diff --git a/src/Notepads.DesktopExtension/extension.cpp b/src/Notepads.DesktopExtension/extension.cpp index 4c5bb0c7f..99c37a7f2 100644 --- a/src/Notepads.DesktopExtension/extension.cpp +++ b/src/Notepads.DesktopExtension/extension.cpp @@ -17,7 +17,18 @@ fire_and_forget launchElevatedProcess() TCHAR fileName[MAX_PATH]; GetModuleFileName(NULL, fileName, MAX_PATH); - SHELLEXECUTEINFO shExInfo{ sizeof(shExInfo), SEE_MASK_NOCLOSEPROCESS, 0, L"runas", fileName, L"", 0, SW_SHOW, 0 }; + SHELLEXECUTEINFO shExInfo + { + .cbSize = sizeof(shExInfo), + .fMask = SEE_MASK_NOCLOSEPROCESS, + .hwnd = 0, + .lpVerb = L"runas", + .lpFile = fileName, + .lpParameters = L"", + .lpDirectory = 0, + .nShow = SW_SHOW, + .hInstApp = 0 + }; auto message = ValueSet(); vector> properties; @@ -28,8 +39,12 @@ fire_and_forget launchElevatedProcess() TerminateJobObject(appExitJob, 0); if (appExitJob) CloseHandle(appExitJob); appExitJob = CreateJobObject(NULL, NULL); - JOBOBJECT_EXTENDED_LIMIT_INFORMATION info = { 0 }; - info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + + JOBOBJECT_EXTENDED_LIMIT_INFORMATION info { + .BasicLimitInformation { + .LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE + } + }; SetInformationJobObject(appExitJob, JobObjectExtendedLimitInformation, &info, sizeof(info)); if (shExInfo.hProcess) AssignProcessToJobObject(appExitJob, shExInfo.hProcess); diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index 303521939..43cc71bdf 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -43,9 +43,8 @@ bool isElevetedProcessLaunchRequested() { auto result = false; - LPTSTR* argList; INT argCount; - argList = CommandLineToArgvW(GetCommandLine(), &argCount); + LPTSTR* argList = CommandLineToArgvW(GetCommandLine(), &argCount); if (argCount > 3 && wcscmp(argList[3], L"/admin") == 0) { result = true; @@ -73,7 +72,7 @@ bool isFirstInstance(LPCTSTR mutexName) printDebugMessage(L"Closing this instance as another instance is already running.", 3000); exitApp(); } - ReleaseMutex(hMutex); + if (hMutex) ReleaseMutex(hMutex); return result; } diff --git a/src/Notepads.DesktopExtension/pch.cpp b/src/Notepads.DesktopExtension/pch.cpp index 2ba19488a..5f2f19818 100644 --- a/src/Notepads.DesktopExtension/pch.cpp +++ b/src/Notepads.DesktopExtension/pch.cpp @@ -14,7 +14,7 @@ constexpr INT MAX_TIME_STR = 20; constexpr INT MAX_DATE_STR = 20; constexpr INT MAX_DATETIME_STR = 100; -StorageFile logFile = nullptr; +StorageFile logFile = NULL; void printDebugMessage([[maybe_unused]] LPCTSTR message, [[maybe_unused]] DWORD sleepTime) { #ifdef _DEBUG @@ -94,12 +94,11 @@ pair getLastErrorDetails() 0, NULL); - wstringstream msgStrm((LPCTSTR)msgBuf); wstring msg; + getline(wstringstream((LPCTSTR)msgBuf), msg, L'\r'); LocalFree(msgBuf); - getline(msgStrm, msg, L'\r'); - return pair { errorCode, msg }; + return pair { errorCode, msg }; } IAsyncAction logLastError(bool isFatal) diff --git a/src/Notepads.DesktopExtension/vcpkg.json b/src/Notepads.DesktopExtension/vcpkg.json index f9cbc2e38..d3e4c084f 100644 --- a/src/Notepads.DesktopExtension/vcpkg.json +++ b/src/Notepads.DesktopExtension/vcpkg.json @@ -2,9 +2,23 @@ "name": "notepads-desktopextension", "version-string": "1.0.0.0", "dependencies": [ - "boost-stacktrace", - "curl", - "fmt", - "rapidjson" - ] + { + "name": "boost-stacktrace", + "$version": "1.74.0" + }, + { + "name": "curl", + "$version": "7.74.0", + "$port-version": 1 + }, + { + "name": "fmt", + "$version": "7.1.3" + }, + { + "name": "rapidjson", + "$version-date": "2020-09-14" + } + ], + "$x-default-baseline": "c54abfafbe0051075952c507da1f1ec234875e05" } \ No newline at end of file From 612c98befbe977b999b09136314bdba49d30bcb0 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 2 Jan 2021 17:39:17 +0530 Subject: [PATCH 128/181] code-refactor. --- .../Notepads.DesktopExtension.vcxproj | 13 +- .../Notepads.DesktopExtension.vcxproj.filters | 2 +- .../PropertySheet.props | 2 +- src/Notepads.DesktopExtension/log.h | 1 - src/Notepads.DesktopExtension/packages.config | 2 +- src/Notepads.DesktopExtension/vcpkg.json | 2 +- src/Notepads.Package/Notepads.Package.wapproj | 10 +- src/Notepads.Package/Package.appxmanifest | 1218 ----------------- src/Notepads/Package.appxmanifest | 1147 +++++++++++++++- src/Notepads/Program.cs | 3 - src/Notepads/Utilities/FileSystemUtility.cs | 1 - .../Settings/AdvancedSettingsPage.xaml.cs | 1 - .../PersonalizationSettingsPage.xaml.cs | 2 - .../TextAndEditorSettingsPage.xaml.cs | 1 - 14 files changed, 1164 insertions(+), 1241 deletions(-) delete mode 100644 src/Notepads.Package/Package.appxmanifest diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index db592fd4a..1505400ec 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -1,6 +1,6 @@ - + true true @@ -16,6 +16,10 @@ 10.0.19041.0 10.0.17763.0 true + false + false + Windows Store + 10.0 @@ -155,11 +159,12 @@ - + + @@ -174,7 +179,7 @@ This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - + + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters index 2204cd81c..d6d91d8b7 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters @@ -57,10 +57,10 @@ - Resource Files + diff --git a/src/Notepads.DesktopExtension/PropertySheet.props b/src/Notepads.DesktopExtension/PropertySheet.props index b0c60bb33..afef4a14a 100644 --- a/src/Notepads.DesktopExtension/PropertySheet.props +++ b/src/Notepads.DesktopExtension/PropertySheet.props @@ -14,7 +14,7 @@ https://github.com/microsoft/vcpkg - c54abfafbe0051075952c507da1f1ec234875e05 + 50ea8c0ab7aca3bb9245bba7fc877ad2f2a4464c diff --git a/src/Notepads.DesktopExtension/log.h b/src/Notepads.DesktopExtension/log.h index b43d9906c..e1497cd25 100644 --- a/src/Notepads.DesktopExtension/log.h +++ b/src/Notepads.DesktopExtension/log.h @@ -25,7 +25,6 @@ namespace AppCenter class Log { public: - #pragma region Constructors for error report Log(LogType type, const string& id, const string& sid, bool isFatal, Exception* exception) : diff --git a/src/Notepads.DesktopExtension/packages.config b/src/Notepads.DesktopExtension/packages.config index 92ff0cc3a..1c90c5bae 100644 --- a/src/Notepads.DesktopExtension/packages.config +++ b/src/Notepads.DesktopExtension/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/vcpkg.json b/src/Notepads.DesktopExtension/vcpkg.json index d3e4c084f..79a7ec7b9 100644 --- a/src/Notepads.DesktopExtension/vcpkg.json +++ b/src/Notepads.DesktopExtension/vcpkg.json @@ -20,5 +20,5 @@ "$version-date": "2020-09-14" } ], - "$x-default-baseline": "c54abfafbe0051075952c507da1f1ec234875e05" + "$x-default-baseline": "50ea8c0ab7aca3bb9245bba7fc877ad2f2a4464c" } \ No newline at end of file diff --git a/src/Notepads.Package/Notepads.Package.wapproj b/src/Notepads.Package/Notepads.Package.wapproj index 5a7e6beb1..b0151999e 100644 --- a/src/Notepads.Package/Notepads.Package.wapproj +++ b/src/Notepads.Package/Notepads.Package.wapproj @@ -46,11 +46,17 @@ 10.0.19041.0 10.0.17763.0 en-US - false ..\Notepads\Notepads.csproj + False + Always + 1 + OnApplicationRun + False + True + x86|x64|arm64|arm - + Designer diff --git a/src/Notepads.Package/Package.appxmanifest b/src/Notepads.Package/Package.appxmanifest deleted file mode 100644 index 6f86ab73c..000000000 --- a/src/Notepads.Package/Package.appxmanifest +++ /dev/null @@ -1,1218 +0,0 @@ - - - - - - - - - - Notepads App - Jackie Liu - Assets\StoreLogo.png - - - - - - - - - - - - - - - - - - - - - - - - - - - Assets\appicon_w.png - Notepads URI Scheme - - - - - - - - - - - - - - - - - - - - .txt - - ms-resource:Manifest/TextFileDisplayName - - Assets\FileIcons\txt.png - - - - - - .cfg - .config - .cnf - .conf - .properties - .directory - - ms-resource:Manifest/ConfigFileDisplayName - Assets\FileIcons\cfg.png - - - - - - - .ini - - ms-resource:Manifest/InitializationFileDisplayName - Assets\FileIcons\ini.png - - - - - - - .md - .markdown - .mkd - .mdwn - .mdown - .markdn - .mdtxt - .workbook - - ms-resource:Manifest/MarkdownFileDisplayName - Assets\FileIcons\md.png - - - - - - - .log - - ms-resource:Manifest/LogFileDisplayName - Assets\FileIcons\log.png - - - - - - - .bib - - ms-resource:Manifest/BibTeXFileDisplayName - Assets\FileIcons\bib.png - - - - - - - .json - .jsonc - .jsonld - .hintrc - .babelrc - .eslintrc - .jslintrc - .bowerrc - .jscsrc - .webmanifest - .har - - ms-resource:Manifest/JsonFileDisplayName - Assets\FileIcons\json.png - - - - - - - .yml - .yaml - - ms-resource:Manifest/YamlFileDisplayName - Assets\FileIcons\yml.png - - - - - - - .xml - .xsd - .ascx - .atom - .axml - .bpmn - .cpt - .csl - - ms-resource:Manifest/XmlFileDisplayName - Assets\FileIcons\xml.png - - - - - - - .html - .htm - .shtml - .xhtml - .mdoc - .jshtm - .volt - - ms-resource:Manifest/HtmlFileDisplayName - Assets\FileIcons\html.png - - - - - - - .asp - .aspx - - ms-resource:Manifest/AspFileDisplayName - Assets\FileIcons\asp.png - - - - - - - .jsp - .jspx - - ms-resource:Manifest/JspFileDisplayName - Assets\FileIcons\jsp.png - - - - - - - .css - .scss - - ms-resource:Manifest/CssFileDisplayName - Assets\FileIcons\css.png - - - - - - - .sh - - ms-resource:Manifest/ShellScriptFileDisplayName - Assets\FileIcons\sh.png - - - - - - - .bashrc - .vimrc - .rc - - ms-resource:Manifest/RunCommandsFileDisplayName - Assets\FileIcons\rc.png - - - - - - - .bash - - ms-resource:Manifest/BashScriptFileDisplayName - Assets\FileIcons\bash.png - - - - - - - .js - .jsx - .es6 - .mjs - .cjs - .pac - - ms-resource:Manifest/JavascriptFileDisplayName - Assets\FileIcons\js.png - - - - - - - .ts - .tsx - - ms-resource:Manifest/TypeScriptFileDisplayName - Assets\FileIcons\file.png - - - - - - - .lua - - ms-resource:Manifest/LuaFileDisplayName - Assets\FileIcons\file.png - - - - - - - .c - .m - .i - - ms-resource:Manifest/CFileDisplayName - Assets\FileIcons\c.png - - - - - - - .cc - .mm - .cpp - .cxx - .ii - .ino - - ms-resource:Manifest/CppFileDisplayName - Assets\FileIcons\cpp.png - - - - - - - .h - .hh - .hpp - .hxx - - ms-resource:Manifest/HeaderFileDisplayName - Assets\FileIcons\h.png - - - - - - - .cmake - - ms-resource:Manifest/CmakeFileDisplayName - Assets\FileIcons\file.png - - - - - - - .cs - .csx - .cake - - ms-resource:Manifest/CSharpFileDisplayName - Assets\FileIcons\cs.png - - - - - - - .php - .php4 - .php5 - .phtml - .ctp - - ms-resource:Manifest/PhpFileDisplayName - Assets\FileIcons\php.png - - - - - - - .py - - ms-resource:Manifest/PythonFileDisplayName - Assets\FileIcons\py.png - - - - - - - .rb - .rbx - .rjs - .gemspec - .rake - .ru - .erb - .rbi - .arb - - ms-resource:Manifest/RubyFileDisplayName - - Assets\FileIcons\rb.png - - - - - - .java - .jav - - ms-resource:Manifest/JavaFileDisplayName - Assets\FileIcons\java.png - - - - - - - .vb - .vbs - .brs - .bas - - ms-resource:Manifest/VisualBasicFileDisplayName - Assets\FileIcons\vb.png - - - - - - - .go - - ms-resource:Manifest/GoFileDisplayName - Assets\FileIcons\file.png - - - - - - - .srt - - ms-resource:Manifest/SubtitleFileDisplayName - Assets\FileIcons\srt.png - - - - - - - .ass - - ms-resource:Manifest/AegisubAdvancedSubtitleFileDisplayName - Assets\FileIcons\ass.png - - - - - - - .ssa - - ms-resource:Manifest/SubStationAlphaSubtitleFileDisplayName - Assets\FileIcons\ssa.png - - - - - - - .vue - - ms-resource:Manifest/VueFileDisplayName - Assets\FileIcons\vue.png - - - - - - - .vuerc - - ms-resource:Manifest/VueConfigFileDisplayName - Assets\FileIcons\vue.png - - - - - - - .gitconfig - - ms-resource:Manifest/GitConfigFileDisplayName - Assets\FileIcons\file.png - - - - - - - .gitignore - - ms-resource:Manifest/GitIgnoreFileDisplayName - Assets\FileIcons\file.png - - - - - - - .gitattributes - - ms-resource:Manifest/GitAttributesFileDisplayName - Assets\FileIcons\file.png - - - - - - - .project - .prj - - ms-resource:Manifest/ProjectFileDisplayName - Assets\FileIcons\file.png - - - - - - - .npmrc - - ms-resource:Manifest/NpmConfigFileDisplayName - Assets\FileIcons\file.png - - - - - - - .bash_history - - ms-resource:Manifest/BashHistoryFileDisplayName - Assets\FileIcons\file.png - - - - - - - .bash_aliases - - ms-resource:Manifest/BashAliasesFileDisplayName - Assets\FileIcons\file.png - - - - - - - .bash_profile - - ms-resource:Manifest/BashProfileFileDisplayName - Assets\FileIcons\file.png - - - - - - - .bash_login - - ms-resource:Manifest/BashLoginFileDisplayName - Assets\FileIcons\file.png - - - - - - - .bash_logout - - ms-resource:Manifest/BashLogoutFileDisplayName - Assets\FileIcons\file.png - - - - - - - .cgi - - ms-resource:Manifest/CgiFileDisplayName - Assets\FileIcons\file.png - - - - - - - .pl - .pm - .psgi - - ms-resource:Manifest/PerlFileDisplayName - Assets\FileIcons\perl.png - - - - - - - .buildpath - - ms-resource:Manifest/BuildPathFileDisplayName - Assets\FileIcons\file.png - - - - - - - .sql - .dsql - - ms-resource:Manifest/SqlFileDisplayName - Assets\FileIcons\sql.png - - - - - - - .nfo - - ms-resource:Manifest/NfoFileDisplayName - Assets\FileIcons\file.png - - - - - - - .ahk - - ms-resource:Manifest/AutoHotkeyScriptFileDisplayName - Assets\FileIcons\file.png - - - - - - - .zshrc - - ms-resource:Manifest/ZshellConfigFileDisplayName - Assets\FileIcons\file.png - - - - - - - .zsh_history - - ms-resource:Manifest/ZshellHistoryFileDisplayName - Assets\FileIcons\file.png - - - - - - - .lrc - - ms-resource:Manifest/LrcFileDisplayName - Assets\FileIcons\file.png - - - - - - - .v - - ms-resource:Manifest/VerilogFileDisplayName - Assets\FileIcons\file.png - - - - - - - .dat - - ms-resource:Manifest/DatFileDisplayName - Assets\FileIcons\file.png - - - - - - - .glsp - - ms-resource:Manifest/GlspFileDisplayName - Assets\FileIcons\file.png - - - - - - - .asm - - ms-resource:Manifest/AsmFileDisplayName - Assets\FileIcons\file.png - - - - - - - .clj - .cljs - .cljc - .cljx - .clojure - .edn - - ms-resource:Manifest/ClojureFileDisplayName - Assets\FileIcons\file.png - - - - - - - .coffee - .cson - .iced - - ms-resource:Manifest/CoffeeScriptFileDisplayName - Assets\FileIcons\file.png - - - - - - - .dockerfile - - ms-resource:Manifest/DockerFileDisplayName - Assets\FileIcons\file.png - - - - - - - .fs - .fsi - .fsx - .fsscript - - ms-resource:Manifest/FSharpFileDisplayName - Assets\FileIcons\file.png - - - - - - - .patch - .diff - .rej - - ms-resource:Manifest/DiffFileDisplayName - Assets\FileIcons\file.png - - - - - - - .groovy - .gvy - .gradle - - ms-resource:Manifest/GroovyFileDisplayName - Assets\FileIcons\file.png - - - - - - - .handlebars - .hbs - .hjs - - ms-resource:Manifest/HandlebarsFileDisplayName - Assets\FileIcons\file.png - - - - - - - .hlsl - .hlsli - .fx - .fxh - .vsh - .psh - .cginc - .compute - - ms-resource:Manifest/HlslFileDisplayName - Assets\FileIcons\file.png - - - - - - - .map - - ms-resource:Manifest/MapFileDisplayName - Assets\FileIcons\file.png - - - - - - - .less - - ms-resource:Manifest/LessFileDisplayName - Assets\FileIcons\file.png - - - - - - - .t - - ms-resource:Manifest/TFileDisplayName - Assets\FileIcons\file.png - - - - - - - .pod - .podspec - - ms-resource:Manifest/PodFileDisplayName - Assets\FileIcons\file.png - - - - - - - .p6 - .pl6 - .pm6 - .nqp - - ms-resource:Manifest/Perl6FileDisplayName - Assets\FileIcons\perl.png - - - - - - - .cshtml - - ms-resource:Manifest/RazorFileDisplayName - Assets\FileIcons\file.png - - - - - - - .rs - - ms-resource:Manifest/RustFileDisplayName - Assets\FileIcons\file.png - - - - - - - .shader - - ms-resource:Manifest/ShaderFileDisplayName - Assets\FileIcons\file.png - - - - - - - .jade - .pug - - ms-resource:Manifest/PugFileDisplayName - Assets\FileIcons\file.png - - - - - - - .r - .rhistory - .rprofile - .rt - - ms-resource:Manifest/RFileDisplayName - Assets\FileIcons\file.png - - - - - - - .install - - ms-resource:Manifest/InstallFileDisplayName - Assets\FileIcons\file.png - - - - - - - .profile - - ms-resource:Manifest/ProfileFileDisplayName - Assets\FileIcons\file.png - - - - - - - .ebuild - - ms-resource:Manifest/EBuildFileDisplayName - Assets\FileIcons\file.png - - - - - - - .swift - - ms-resource:Manifest/SwiftFileDisplayName - Assets\FileIcons\file.png - - - - - - - .ps1 - .psm1 - .psd1 - .pssc - .psrc - - ms-resource:Manifest/PowerShellFileDisplayName - Assets\FileIcons\file.png - - - - - - - .xaml - - ms-resource:Manifest/XamlFileDisplayName - Assets\FileIcons\file.png - - - - - - - .user - - ms-resource:Manifest/UserFileDisplayName - Assets\FileIcons\file.png - - - - - - - .bond - - ms-resource:Manifest/BondFileDisplayName - Assets\FileIcons\file.png - - - - - - - .htaccess - - ms-resource:Manifest/HypertextAccessFileDisplayName - Assets\FileIcons\file.png - - - - - - - .csv - - ms-resource:Manifest/CommaSeparatedValuesFileDisplayName - Assets\FileIcons\file.png - - - - - - - .m3u - .m3u8 - - ms-resource:Manifest/M3uFileDisplayName - Assets\FileIcons\file.png - - - - - - - .glslp - - ms-resource:Manifest/GlslFileDisplayName - Assets\FileIcons\file.png - - - - - - - .cht - - ms-resource:Manifest/CheatFileDisplayName - Assets\FileIcons\file.png - - - - - - - .opt - - ms-resource:Manifest/OptFileDisplayName - Assets\FileIcons\file.png - - - - - - - .env - - ms-resource:Manifest/EnvironmentFileDisplayName - Assets\FileIcons\file.png - - - - - - - .toml - - ms-resource:Manifest/TomlFileDisplayName - Assets\FileIcons\file.png - - - - - - - .pvd - - ms-resource:Manifest/PvdFileDisplayName - Assets\FileIcons\file.png - - - - - - - .xsl - - ms-resource:Manifest/XslFileDisplayName - Assets\FileIcons\file.png - - - - - - - .lic - - ms-resource:Manifest/LicenseFileDisplayName - Assets\FileIcons\file.png - - - - - - - .csproj - - ms-resource:Manifest/CSharpeProjectFileDisplayName - Assets\FileIcons\file.png - - - - - - - .resx - - ms-resource:Manifest/ResourceFileDisplayName - Assets\FileIcons\file.png - - - - - - - .plist - - ms-resource:Manifest/PropertyListFileDisplayName - Assets\FileIcons\file.png - - - - - - - - .randomextension - * - - Assets\FileIcons\file.png - - - - - - - - - - - - - - - - diff --git a/src/Notepads/Package.appxmanifest b/src/Notepads/Package.appxmanifest index 94c74143f..9fcc29066 100644 --- a/src/Notepads/Package.appxmanifest +++ b/src/Notepads/Package.appxmanifest @@ -4,12 +4,14 @@ xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10" xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest" xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10" + xmlns:uap3="http://schemas.microsoft.com/appx/manifest/uap/windows10/3" xmlns:uap5="http://schemas.microsoft.com/appx/manifest/uap/windows10/5" xmlns:uap10="http://schemas.microsoft.com/appx/manifest/uap/windows10/10" + xmlns:desktop="http://schemas.microsoft.com/appx/manifest/desktop/windows10" xmlns:desktop4="http://schemas.microsoft.com/appx/manifest/desktop/windows10/4" - xmlns:iot2="http://schemas.microsoft.com/appx/manifest/iot/windows10/2" + xmlns:iot2="http://schemas.microsoft.com/appx/manifest/iot/windows10/2" xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" - IgnorableNamespaces="mp uap uap5 uap10 desktop4 iot2 rescap"> + IgnorableNamespaces="mp uap uap3 uap5 uap10 desktop desktop4 iot2 rescap"> + @@ -35,7 +38,7 @@ + + + + + + + + + + + + + .txt + + ms-resource:Manifest/TextFileDisplayName + + Assets\FileIcons\txt.png + + + + + + .cfg + .config + .cnf + .conf + .properties + .directory + + ms-resource:Manifest/ConfigFileDisplayName + Assets\FileIcons\cfg.png + + + + + + + .ini + + ms-resource:Manifest/InitializationFileDisplayName + Assets\FileIcons\ini.png + + + + + + + .md + .markdown + .mkd + .mdwn + .mdown + .markdn + .mdtxt + .workbook + + ms-resource:Manifest/MarkdownFileDisplayName + Assets\FileIcons\md.png + + + + + + + .log + + ms-resource:Manifest/LogFileDisplayName + Assets\FileIcons\log.png + + + + + + + .bib + + ms-resource:Manifest/BibTeXFileDisplayName + Assets\FileIcons\bib.png + + + + + + + .json + .jsonc + .jsonld + .hintrc + .babelrc + .eslintrc + .jslintrc + .bowerrc + .jscsrc + .webmanifest + .har + + ms-resource:Manifest/JsonFileDisplayName + Assets\FileIcons\json.png + + + + + + + .yml + .yaml + + ms-resource:Manifest/YamlFileDisplayName + Assets\FileIcons\yml.png + + + + + + + .xml + .xsd + .ascx + .atom + .axml + .bpmn + .cpt + .csl + + ms-resource:Manifest/XmlFileDisplayName + Assets\FileIcons\xml.png + + + + + + + .html + .htm + .shtml + .xhtml + .mdoc + .jshtm + .volt + + ms-resource:Manifest/HtmlFileDisplayName + Assets\FileIcons\html.png + + + + + + + .asp + .aspx + + ms-resource:Manifest/AspFileDisplayName + Assets\FileIcons\asp.png + + + + + + + .jsp + .jspx + + ms-resource:Manifest/JspFileDisplayName + Assets\FileIcons\jsp.png + + + + + + + .css + .scss + + ms-resource:Manifest/CssFileDisplayName + Assets\FileIcons\css.png + + + + + + + .sh + + ms-resource:Manifest/ShellScriptFileDisplayName + Assets\FileIcons\sh.png + + + + + + + .bashrc + .vimrc + .rc + + ms-resource:Manifest/RunCommandsFileDisplayName + Assets\FileIcons\rc.png + + + + + + + .bash + + ms-resource:Manifest/BashScriptFileDisplayName + Assets\FileIcons\bash.png + + + + + + + .js + .jsx + .es6 + .mjs + .cjs + .pac + + ms-resource:Manifest/JavascriptFileDisplayName + Assets\FileIcons\js.png + + + + + + + .ts + .tsx + + ms-resource:Manifest/TypeScriptFileDisplayName + Assets\FileIcons\file.png + + + + + + + .lua + + ms-resource:Manifest/LuaFileDisplayName + Assets\FileIcons\file.png + + + + + + + .c + .m + .i + + ms-resource:Manifest/CFileDisplayName + Assets\FileIcons\c.png + + + + + + + .cc + .mm + .cpp + .cxx + .ii + .ino + + ms-resource:Manifest/CppFileDisplayName + Assets\FileIcons\cpp.png + + + + + + + .h + .hh + .hpp + .hxx + + ms-resource:Manifest/HeaderFileDisplayName + Assets\FileIcons\h.png + + + + + + + .cmake + + ms-resource:Manifest/CmakeFileDisplayName + Assets\FileIcons\file.png + + + + + + + .cs + .csx + .cake + + ms-resource:Manifest/CSharpFileDisplayName + Assets\FileIcons\cs.png + + + + + + + .php + .php4 + .php5 + .phtml + .ctp + + ms-resource:Manifest/PhpFileDisplayName + Assets\FileIcons\php.png + + + + + + + .py + + ms-resource:Manifest/PythonFileDisplayName + Assets\FileIcons\py.png + + + + + + + .rb + .rbx + .rjs + .gemspec + .rake + .ru + .erb + .rbi + .arb + + ms-resource:Manifest/RubyFileDisplayName + + Assets\FileIcons\rb.png + + + + + + .java + .jav + + ms-resource:Manifest/JavaFileDisplayName + Assets\FileIcons\java.png + + + + + + + .vb + .vbs + .brs + .bas + + ms-resource:Manifest/VisualBasicFileDisplayName + Assets\FileIcons\vb.png + + + + + + + .go + + ms-resource:Manifest/GoFileDisplayName + Assets\FileIcons\file.png + + + + + + + .srt + + ms-resource:Manifest/SubtitleFileDisplayName + Assets\FileIcons\srt.png + + + + + + + .ass + + ms-resource:Manifest/AegisubAdvancedSubtitleFileDisplayName + Assets\FileIcons\ass.png + + + + + + + .ssa + + ms-resource:Manifest/SubStationAlphaSubtitleFileDisplayName + Assets\FileIcons\ssa.png + + + + + + + .vue + + ms-resource:Manifest/VueFileDisplayName + Assets\FileIcons\vue.png + + + + + + + .vuerc + + ms-resource:Manifest/VueConfigFileDisplayName + Assets\FileIcons\vue.png + + + + + + + .gitconfig + + ms-resource:Manifest/GitConfigFileDisplayName + Assets\FileIcons\file.png + + + + + + + .gitignore + + ms-resource:Manifest/GitIgnoreFileDisplayName + Assets\FileIcons\file.png + + + + + + + .gitattributes + + ms-resource:Manifest/GitAttributesFileDisplayName + Assets\FileIcons\file.png + + + + + + + .project + .prj + + ms-resource:Manifest/ProjectFileDisplayName + Assets\FileIcons\file.png + + + + + + + .npmrc + + ms-resource:Manifest/NpmConfigFileDisplayName + Assets\FileIcons\file.png + + + + + + + .bash_history + + ms-resource:Manifest/BashHistoryFileDisplayName + Assets\FileIcons\file.png + + + + + + + .bash_aliases + + ms-resource:Manifest/BashAliasesFileDisplayName + Assets\FileIcons\file.png + + + + + + + .bash_profile + + ms-resource:Manifest/BashProfileFileDisplayName + Assets\FileIcons\file.png + + + + + + + .bash_login + + ms-resource:Manifest/BashLoginFileDisplayName + Assets\FileIcons\file.png + + + + + + + .bash_logout + + ms-resource:Manifest/BashLogoutFileDisplayName + Assets\FileIcons\file.png + + + + + + + .cgi + + ms-resource:Manifest/CgiFileDisplayName + Assets\FileIcons\file.png + + + + + + + .pl + .pm + .psgi + + ms-resource:Manifest/PerlFileDisplayName + Assets\FileIcons\perl.png + + + + + + + .buildpath + + ms-resource:Manifest/BuildPathFileDisplayName + Assets\FileIcons\file.png + + + + + + + .sql + .dsql + + ms-resource:Manifest/SqlFileDisplayName + Assets\FileIcons\sql.png + + + + + + + .nfo + + ms-resource:Manifest/NfoFileDisplayName + Assets\FileIcons\file.png + + + + + + + .ahk + + ms-resource:Manifest/AutoHotkeyScriptFileDisplayName + Assets\FileIcons\file.png + + + + + + + .zshrc + + ms-resource:Manifest/ZshellConfigFileDisplayName + Assets\FileIcons\file.png + + + + + + + .zsh_history + + ms-resource:Manifest/ZshellHistoryFileDisplayName + Assets\FileIcons\file.png + + + + + + + .lrc + + ms-resource:Manifest/LrcFileDisplayName + Assets\FileIcons\file.png + + + + + + + .v + + ms-resource:Manifest/VerilogFileDisplayName + Assets\FileIcons\file.png + + + + + + + .dat + + ms-resource:Manifest/DatFileDisplayName + Assets\FileIcons\file.png + + + + + + + .glsp + + ms-resource:Manifest/GlspFileDisplayName + Assets\FileIcons\file.png + + + + + + + .asm + + ms-resource:Manifest/AsmFileDisplayName + Assets\FileIcons\file.png + + + + + + + .clj + .cljs + .cljc + .cljx + .clojure + .edn + + ms-resource:Manifest/ClojureFileDisplayName + Assets\FileIcons\file.png + + + + + + + .coffee + .cson + .iced + + ms-resource:Manifest/CoffeeScriptFileDisplayName + Assets\FileIcons\file.png + + + + + + + .dockerfile + + ms-resource:Manifest/DockerFileDisplayName + Assets\FileIcons\file.png + + + + + + + .fs + .fsi + .fsx + .fsscript + + ms-resource:Manifest/FSharpFileDisplayName + Assets\FileIcons\file.png + + + + + + + .patch + .diff + .rej + + ms-resource:Manifest/DiffFileDisplayName + Assets\FileIcons\file.png + + + + + + + .groovy + .gvy + .gradle + + ms-resource:Manifest/GroovyFileDisplayName + Assets\FileIcons\file.png + + + + + + + .handlebars + .hbs + .hjs + + ms-resource:Manifest/HandlebarsFileDisplayName + Assets\FileIcons\file.png + + + + + + + .hlsl + .hlsli + .fx + .fxh + .vsh + .psh + .cginc + .compute + + ms-resource:Manifest/HlslFileDisplayName + Assets\FileIcons\file.png + + + + + + + .map + + ms-resource:Manifest/MapFileDisplayName + Assets\FileIcons\file.png + + + + + + + .less + + ms-resource:Manifest/LessFileDisplayName + Assets\FileIcons\file.png + + + + + + + .t + + ms-resource:Manifest/TFileDisplayName + Assets\FileIcons\file.png + + + + + + + .pod + .podspec + + ms-resource:Manifest/PodFileDisplayName + Assets\FileIcons\file.png + + + + + + + .p6 + .pl6 + .pm6 + .nqp + + ms-resource:Manifest/Perl6FileDisplayName + Assets\FileIcons\perl.png + + + + + + + .cshtml + + ms-resource:Manifest/RazorFileDisplayName + Assets\FileIcons\file.png + + + + + + + .rs + + ms-resource:Manifest/RustFileDisplayName + Assets\FileIcons\file.png + + + + + + + .shader + + ms-resource:Manifest/ShaderFileDisplayName + Assets\FileIcons\file.png + + + + + + + .jade + .pug + + ms-resource:Manifest/PugFileDisplayName + Assets\FileIcons\file.png + + + + + + + .r + .rhistory + .rprofile + .rt + + ms-resource:Manifest/RFileDisplayName + Assets\FileIcons\file.png + + + + + + + .install + + ms-resource:Manifest/InstallFileDisplayName + Assets\FileIcons\file.png + + + + + + + .profile + + ms-resource:Manifest/ProfileFileDisplayName + Assets\FileIcons\file.png + + + + + + + .ebuild + + ms-resource:Manifest/EBuildFileDisplayName + Assets\FileIcons\file.png + + + + + + + .swift + + ms-resource:Manifest/SwiftFileDisplayName + Assets\FileIcons\file.png + + + + + + + .ps1 + .psm1 + .psd1 + .pssc + .psrc + + ms-resource:Manifest/PowerShellFileDisplayName + Assets\FileIcons\file.png + + + + + + + .xaml + + ms-resource:Manifest/XamlFileDisplayName + Assets\FileIcons\file.png + + + + + + + .user + + ms-resource:Manifest/UserFileDisplayName + Assets\FileIcons\file.png + + + + + + + .bond + + ms-resource:Manifest/BondFileDisplayName + Assets\FileIcons\file.png + + + + + + + .htaccess + + ms-resource:Manifest/HypertextAccessFileDisplayName + Assets\FileIcons\file.png + + + + + + + .csv + + ms-resource:Manifest/CommaSeparatedValuesFileDisplayName + Assets\FileIcons\file.png + + + + + + + .m3u + .m3u8 + + ms-resource:Manifest/M3uFileDisplayName + Assets\FileIcons\file.png + + + + + + + .glslp + + ms-resource:Manifest/GlslFileDisplayName + Assets\FileIcons\file.png + + + + + + + .cht + + ms-resource:Manifest/CheatFileDisplayName + Assets\FileIcons\file.png + + + + + + + .opt + + ms-resource:Manifest/OptFileDisplayName + Assets\FileIcons\file.png + + + + + + + .env + + ms-resource:Manifest/EnvironmentFileDisplayName + Assets\FileIcons\file.png + + + + + + + .toml + + ms-resource:Manifest/TomlFileDisplayName + Assets\FileIcons\file.png + + + + + + + .pvd + + ms-resource:Manifest/PvdFileDisplayName + Assets\FileIcons\file.png + + + + + + + .xsl + + ms-resource:Manifest/XslFileDisplayName + Assets\FileIcons\file.png + + + + + + + .lic + + ms-resource:Manifest/LicenseFileDisplayName + Assets\FileIcons\file.png + + + + + + + .csproj + + ms-resource:Manifest/CSharpeProjectFileDisplayName + Assets\FileIcons\file.png + + + + + + + .resx + + ms-resource:Manifest/ResourceFileDisplayName + Assets\FileIcons\file.png + + + + + + + .plist + + ms-resource:Manifest/PropertyListFileDisplayName + Assets\FileIcons\file.png + + + + + + + + .randomextension + * + + Assets\FileIcons\file.png + + + + + + + - + \ No newline at end of file diff --git a/src/Notepads/Program.cs b/src/Notepads/Program.cs index 545ec65ae..5ac52a0f7 100644 --- a/src/Notepads/Program.cs +++ b/src/Notepads/Program.cs @@ -2,15 +2,12 @@ { using System; using System.Linq; - using System.Security.Principal; using System.Threading; using System.Threading.Tasks; using Notepads.Services; using Notepads.Settings; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; - using Windows.Foundation.Metadata; - using Windows.Security.Authentication.Web; public static class Program { diff --git a/src/Notepads/Utilities/FileSystemUtility.cs b/src/Notepads/Utilities/FileSystemUtility.cs index 1df85ae62..1debcfbd7 100644 --- a/src/Notepads/Utilities/FileSystemUtility.cs +++ b/src/Notepads/Utilities/FileSystemUtility.cs @@ -15,7 +15,6 @@ using Windows.Storage.FileProperties; using Windows.Storage.Provider; using UtfUnknown; - using Windows.Foundation.Metadata; public enum InvalidFilenameError { diff --git a/src/Notepads/Views/Settings/AdvancedSettingsPage.xaml.cs b/src/Notepads/Views/Settings/AdvancedSettingsPage.xaml.cs index 18aa73cc6..f2528f560 100644 --- a/src/Notepads/Views/Settings/AdvancedSettingsPage.xaml.cs +++ b/src/Notepads/Views/Settings/AdvancedSettingsPage.xaml.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Linq; using Windows.Globalization; - using Notepads.Settings; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; diff --git a/src/Notepads/Views/Settings/PersonalizationSettingsPage.xaml.cs b/src/Notepads/Views/Settings/PersonalizationSettingsPage.xaml.cs index a0048ba13..c48a7b64b 100644 --- a/src/Notepads/Views/Settings/PersonalizationSettingsPage.xaml.cs +++ b/src/Notepads/Views/Settings/PersonalizationSettingsPage.xaml.cs @@ -2,8 +2,6 @@ { using Notepads.Extensions; using Notepads.Services; - using Notepads.Settings; - using Notepads.Utilities; using Windows.System.Power; using Windows.UI; using Windows.UI.ViewManagement; diff --git a/src/Notepads/Views/Settings/TextAndEditorSettingsPage.xaml.cs b/src/Notepads/Views/Settings/TextAndEditorSettingsPage.xaml.cs index b7ab37a53..75c3ebe65 100644 --- a/src/Notepads/Views/Settings/TextAndEditorSettingsPage.xaml.cs +++ b/src/Notepads/Views/Settings/TextAndEditorSettingsPage.xaml.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Linq; using System.Text; - using Notepads.Settings; using Services; using Utilities; using Windows.ApplicationModel.Resources; From 14cc0fa57c7032e77eb9b5c8f13f0aa0dee25755 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 2 Jan 2021 22:06:03 +0530 Subject: [PATCH 129/181] Implemented process syncronization to indicate client of connecting to named pipe. --- src/Notepads.DesktopExtension/elevated.cpp | 16 +++++++++++++++- src/Notepads.DesktopExtension/pch.h | 1 + src/Notepads/Services/DesktopExtensionService.cs | 10 +++++++++- src/Notepads/Settings/SettingsKey.cs | 1 + 4 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/Notepads.DesktopExtension/elevated.cpp b/src/Notepads.DesktopExtension/elevated.cpp index ff782d1e7..2df1edcd6 100644 --- a/src/Notepads.DesktopExtension/elevated.cpp +++ b/src/Notepads.DesktopExtension/elevated.cpp @@ -13,6 +13,8 @@ constexpr INT PIPE_READ_BUFFER = 2 * MAX_PATH + 10; DWORD sessionId; +HANDLE adminWriteEvent = NULL; + IInspectable readSettingsKey(hstring key) { return ApplicationData::Current().LocalSettings().Values().TryLookup(key); @@ -33,13 +35,22 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) HANDLE hPipe = INVALID_HANDLE_VALUE; while (hPipe == INVALID_HANDLE_VALUE) { - Sleep(50); + if (adminWriteEvent) + { + WaitForSingleObject(adminWriteEvent, INFINITE); + } + else + { + Sleep(50); + } + if (WaitNamedPipe(pipeName.c_str(), NMPWAIT_WAIT_FOREVER)) { hPipe = CreateFile(pipeName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); } } + ResetEvent(adminWriteEvent); CreateThread(NULL, 0, saveFileFromPipeData, NULL, 0, NULL); TCHAR readBuffer[PIPE_READ_BUFFER]; @@ -126,6 +137,9 @@ void initializeAdminService() { ProcessIdToSessionId(GetCurrentProcessId(), &sessionId); + adminWriteEvent = OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, + format(L"AppContainerNamedObjects\\{}\\{}", packageSid, AdminWriteEventNameStr).c_str()); + printDebugMessage(L"Successfully started Adminstrator Extension."); printDebugMessage(L"Waiting on uwp app to send data."); diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h index f0b66e41a..ff89f4777 100644 --- a/src/Notepads.DesktopExtension/pch.h +++ b/src/Notepads.DesktopExtension/pch.h @@ -22,6 +22,7 @@ constexpr LPCTSTR AppCenterSecret = NULL; constexpr LPCTSTR AppCenterInstallIdStr = L"AppCenterInstallIdStr"; constexpr LPCTSTR InteropServiceName = L"DesktopExtensionServiceConnection"; constexpr LPCTSTR PackageSidStr = L"PackageSidStr"; +constexpr LPCTSTR AdminWriteEventNameStr = L"NotepadsAdminWriteEvent"; constexpr LPCTSTR AdminPipeConnectionNameStr = L"NotepadsAdminWritePipe"; constexpr LPCTSTR InteropCommandLabel = L"Command"; constexpr LPCTSTR InteropCommandAdminCreatedLabel = L"AdminCreated"; diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index 20f20c52a..e44447e99 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -11,6 +11,7 @@ using System.IO.MemoryMappedFiles; using System.IO.Pipes; using System.Security.Principal; + using System.Threading; using System.Threading.Tasks; using Windows.ApplicationModel; using Windows.ApplicationModel.AppService; @@ -30,15 +31,20 @@ public AdminstratorAccessException(string message, Exception innerException) : b public static class DesktopExtensionService { - public static AppServiceConnection InteropServiceConnection = null; public static readonly bool ShouldUseDesktopExtension = ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0) && !new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); + + public static AppServiceConnection InteropServiceConnection = null; private static readonly ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView(); + private static EventWaitHandle _adminWriteEvent = null; + public static async Task Initialize() { if (!ShouldUseDesktopExtension) return false; + _adminWriteEvent = new EventWaitHandle(false, EventResetMode.ManualReset, SettingsKey.AdminWriteEventNameStr); + InteropServiceConnection = new AppServiceConnection() { AppServiceName = SettingsKey.InteropServiceName, @@ -114,11 +120,13 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) PipeTransmissionMode.Message, PipeOptions.Asynchronous)) { + _adminWriteEvent.Set(); // Wait for 250 ms for desktop extension to accept request. if (!adminConnectionPipeStream.WaitForConnectionAsync().Wait(250)) { // If the connection fails, desktop extension is not launched with elevated privilages. // In that case, prompt user to launch desktop extension with elevated privilages. + _adminWriteEvent.Reset(); throw new AdminstratorAccessException(); } diff --git a/src/Notepads/Settings/SettingsKey.cs b/src/Notepads/Settings/SettingsKey.cs index 771640bf9..4a70c4c65 100644 --- a/src/Notepads/Settings/SettingsKey.cs +++ b/src/Notepads/Settings/SettingsKey.cs @@ -42,6 +42,7 @@ internal static class SettingsKey internal const string AppCenterInstallIdStr = "AppCenterInstallIdStr"; internal const string InteropServiceName = "DesktopExtensionServiceConnection"; // Keep this same as AppSeviceName value in manifest internal const string PackageSidStr = "PackageSidStr"; + internal const string AdminWriteEventNameStr = "NotepadsAdminWriteEvent"; internal const string AdminPipeConnectionNameStr = "NotepadsAdminWritePipe"; internal const string InteropCommandAdminCreatedLabel = "AdminCreated"; #endif From 6a6af4899ad989025aaba8ed3c0e0000621b1884 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sun, 3 Jan 2021 16:03:10 +0530 Subject: [PATCH 130/181] Better lifetime management for desktop extension. --- src/Notepads.DesktopExtension/elevated.cpp | 141 +++++++++--------- src/Notepads.DesktopExtension/extension.cpp | 7 +- src/Notepads.DesktopExtension/main.cpp | 20 ++- src/Notepads.DesktopExtension/pch.h | 2 +- .../DesktopExtensionConnectionService.cs | 12 +- .../Services/DesktopExtensionService.cs | 14 +- src/Notepads/Settings/SettingsKey.cs | 2 +- .../Views/MainPage/NotepadsMainPage.xaml.cs | 6 + 8 files changed, 112 insertions(+), 92 deletions(-) diff --git a/src/Notepads.DesktopExtension/elevated.cpp b/src/Notepads.DesktopExtension/elevated.cpp index 2df1edcd6..a32297edc 100644 --- a/src/Notepads.DesktopExtension/elevated.cpp +++ b/src/Notepads.DesktopExtension/elevated.cpp @@ -11,7 +11,8 @@ using namespace Windows::Storage; constexpr INT PIPE_READ_BUFFER = 2 * MAX_PATH + 10; -DWORD sessionId; +extern DWORD sessionId; +extern hstring packageSid; HANDLE adminWriteEvent = NULL; @@ -20,8 +21,6 @@ IInspectable readSettingsKey(hstring key) return ApplicationData::Current().LocalSettings().Values().TryLookup(key); } -hstring packageSid = unbox_value_or(readSettingsKey(PackageSidStr), L""); - DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) { setExceptionHandling(); @@ -33,110 +32,108 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) sessionId, packageSid, Package::Current().Id().FamilyName(), AdminPipeConnectionNameStr); HANDLE hPipe = INVALID_HANDLE_VALUE; - while (hPipe == INVALID_HANDLE_VALUE) + if (!WaitForSingleObject(adminWriteEvent, INFINITE) && ResetEvent(adminWriteEvent) && WaitNamedPipe(pipeName.c_str(), NMPWAIT_WAIT_FOREVER)) { - if (adminWriteEvent) - { - WaitForSingleObject(adminWriteEvent, INFINITE); - } - else - { - Sleep(50); - } - - if (WaitNamedPipe(pipeName.c_str(), NMPWAIT_WAIT_FOREVER)) - { - hPipe = CreateFile(pipeName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); - } + hPipe = CreateFile(pipeName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); } - ResetEvent(adminWriteEvent); - CreateThread(NULL, 0, saveFileFromPipeData, NULL, 0, NULL); - - TCHAR readBuffer[PIPE_READ_BUFFER]; - wstringstream pipeData; - DWORD byteRead; - do + if (hPipe) { - fill(begin(readBuffer), end(readBuffer), '\0'); - if (ReadFile(hPipe, readBuffer, (PIPE_READ_BUFFER - 1) * sizeof(TCHAR), &byteRead, NULL)) + CreateThread(NULL, 0, saveFileFromPipeData, NULL, 0, NULL); + + TCHAR readBuffer[PIPE_READ_BUFFER]; + wstringstream pipeData; + DWORD byteRead; + do { - pipeData << readBuffer; - } - } while (byteRead >= (PIPE_READ_BUFFER - 1) * sizeof(TCHAR)); + fill(begin(readBuffer), end(readBuffer), '\0'); + if (ReadFile(hPipe, readBuffer, (PIPE_READ_BUFFER - 1) * sizeof(TCHAR), &byteRead, NULL)) + { + pipeData << readBuffer; + } + } while (byteRead >= (PIPE_READ_BUFFER - 1) * sizeof(TCHAR)); - wstring filePath; - wstring memoryMapId; - wstring dataArrayLengthStr; - getline(pipeData, filePath, L'|'); - getline(pipeData, memoryMapId, L'|'); - getline(pipeData, dataArrayLengthStr); + wstring filePath; + wstring memoryMapId; + wstring dataArrayLengthStr; + getline(pipeData, filePath, L'|'); + getline(pipeData, memoryMapId, L'|'); + getline(pipeData, dataArrayLengthStr); - INT dataArrayLength = stoi(dataArrayLengthStr); - wstring memoryMapName = format(L"AppContainerNamedObjects\\{}\\{}", packageSid, memoryMapId); + INT dataArrayLength = stoi(dataArrayLengthStr); + wstring memoryMapName = format(L"AppContainerNamedObjects\\{}\\{}", packageSid, memoryMapId); - HANDLE hMemory = OpenFileMapping(FILE_MAP_READ, FALSE, memoryMapName.c_str()); - if (hMemory) - { - LPVOID mapView = MapViewOfFile(hMemory, FILE_MAP_READ, 0, 0, dataArrayLength); - if (mapView) + HANDLE hMemory = OpenFileMapping(FILE_MAP_READ, FALSE, memoryMapName.c_str()); + if (hMemory) { - HANDLE hFile = CreateFile( - filePath.c_str(), - GENERIC_READ | GENERIC_WRITE, - 0, - NULL, - TRUNCATE_EXISTING, - 0, - NULL); - - if (hFile) + LPVOID mapView = MapViewOfFile(hMemory, FILE_MAP_READ, 0, 0, dataArrayLength); + if (mapView) { - if (WriteFile(hFile, mapView, dataArrayLength, NULL, NULL) && FlushFileBuffers(hFile)) + HANDLE hFile = CreateFile( + filePath.c_str(), + GENERIC_READ | GENERIC_WRITE, + 0, + NULL, + TRUNCATE_EXISTING, + 0, + NULL); + + if (hFile) { - result = L"Success"; + if (WriteFile(hFile, mapView, dataArrayLength, NULL, NULL) && FlushFileBuffers(hFile)) + { + result = L"Success"; + } + + CloseHandle(hFile); } - CloseHandle(hFile); + CloseHandle(mapView); } - CloseHandle(mapView); + CloseHandle(hMemory); } - CloseHandle(hMemory); - } - - if (WriteFile(hPipe, result, wcslen(result) * sizeof(TCHAR), NULL, NULL)) FlushFileBuffers(hPipe); + if (WriteFile(hPipe, result, wcslen(result) * sizeof(TCHAR), NULL, NULL)) FlushFileBuffers(hPipe); + CloseHandle(hPipe); - CloseHandle(hPipe); + properties.push_back(pair("Result", to_string(result))); + if (wcscmp(result, L"Success") == 0) + { + printDebugMessage(format(L"Successfully wrote to \"{}\"", filePath).c_str()); + } + else + { + pair ex = getLastErrorDetails(); + properties.insert(properties.end(), + { + pair("Error Code", to_string(ex.first)), + pair("Error Message", winrt::to_string(ex.second)) + }); + printDebugMessage(format(L"Failed to write to \"{}\"", filePath).c_str()); + } + printDebugMessage(L"Waiting on uwp app to send data."); - properties.push_back(pair("Result", to_string(result))); - if (wcscmp(result, L"Success") == 0) - { - printDebugMessage(format(L"Successfully wrote to \"{}\"", filePath).c_str()); + AppCenter::trackEvent("OnWriteToSystemFileRequested", properties); } else { + properties.push_back(pair("Result", to_string(result))); pair ex = getLastErrorDetails(); properties.insert(properties.end(), { pair("Error Code", to_string(ex.first)), pair("Error Message", winrt::to_string(ex.second)) }); - - printDebugMessage(format(L"Failed to write to \"{}\"", filePath).c_str()); + AppCenter::trackEvent("OnWriteToSystemFileRequested", properties); + exitApp(); } - printDebugMessage(L"Waiting on uwp app to send data."); - - AppCenter::trackEvent("OnWriteToSystemFileRequested", properties); return 0; } void initializeAdminService() { - ProcessIdToSessionId(GetCurrentProcessId(), &sessionId); - adminWriteEvent = OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, format(L"AppContainerNamedObjects\\{}\\{}", packageSid, AdminWriteEventNameStr).c_str()); diff --git a/src/Notepads.DesktopExtension/extension.cpp b/src/Notepads.DesktopExtension/extension.cpp index 99c37a7f2..c6f75e91e 100644 --- a/src/Notepads.DesktopExtension/extension.cpp +++ b/src/Notepads.DesktopExtension/extension.cpp @@ -8,9 +8,8 @@ using namespace Windows::ApplicationModel::AppService; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; -HANDLE appExitJob = NULL; - AppServiceConnection interopServiceConnection = NULL; +HANDLE appExitJob = NULL; fire_and_forget launchElevatedProcess() { @@ -84,10 +83,6 @@ void onConnectionServiceRequestRecieved(AppServiceConnection sender, AppServiceR { launchElevatedProcess(); } - else if (command == ExitAppCommandStr) - { - exitApp(); - } messageDeferral.Complete(); } diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index 43cc71bdf..e3861dacd 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -1,24 +1,29 @@ #include "pch.h" #include "appcenter.h" +using namespace fmt; +using namespace std; using namespace winrt; constexpr LPCTSTR DesktopExtensionMutexName = L"DesktopExtensionMutexName"; constexpr LPCTSTR AdminExtensionMutexName = L"AdminExtensionMutexName"; -HANDLE appExitEvent = CreateEvent(NULL, TRUE, FALSE, NULL); +DWORD sessionId; +hstring packageSid = unbox_value_or(readSettingsKey(PackageSidStr), L""); + +extern HANDLE adminWriteEvent; extern HANDLE appExitJob; INT releaseResources() { - CloseHandle(appExitEvent); + CloseHandle(adminWriteEvent); CloseHandle(appExitJob); return 0; } void exitApp() { - SetEvent(appExitEvent); + exit(0); } void onUnhandledException() @@ -110,6 +115,8 @@ INT main() SetErrorMode(SEM_NOGPFAULTERRORBOX); _onexit(releaseResources); + ProcessIdToSessionId(GetCurrentProcessId(), &sessionId); + init_apartment(); AppCenter::start(); @@ -127,6 +134,11 @@ INT main() if (isElevetedProcessLaunchRequested()) launchElevatedProcess(); } - WaitForSingleObject(appExitEvent, INFINITE); + wstring pipeName = format(L"\\\\.\\pipe\\Sessions\\{}\\AppContainerNamedObjects\\{}\\{}", + sessionId, packageSid, DesktopExtensionLifetimeObjNameStr); + while (WaitNamedPipe(pipeName.c_str(), 2000) || GetLastError() == ERROR_SEM_TIMEOUT) + { + WaitNamedPipe(pipeName.c_str(), NMPWAIT_WAIT_FOREVER); + } exit(0); } \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h index ff89f4777..489b88de3 100644 --- a/src/Notepads.DesktopExtension/pch.h +++ b/src/Notepads.DesktopExtension/pch.h @@ -22,13 +22,13 @@ constexpr LPCTSTR AppCenterSecret = NULL; constexpr LPCTSTR AppCenterInstallIdStr = L"AppCenterInstallIdStr"; constexpr LPCTSTR InteropServiceName = L"DesktopExtensionServiceConnection"; constexpr LPCTSTR PackageSidStr = L"PackageSidStr"; +constexpr LPCTSTR DesktopExtensionLifetimeObjNameStr = L"DesktopExtensionLifetimeObj"; constexpr LPCTSTR AdminWriteEventNameStr = L"NotepadsAdminWriteEvent"; constexpr LPCTSTR AdminPipeConnectionNameStr = L"NotepadsAdminWritePipe"; constexpr LPCTSTR InteropCommandLabel = L"Command"; constexpr LPCTSTR InteropCommandAdminCreatedLabel = L"AdminCreated"; constexpr LPCTSTR RegisterExtensionCommandStr = L"RegisterExtension"; constexpr LPCTSTR CreateElevetedExtensionCommandStr = L"CreateElevetedExtension"; -constexpr LPCTSTR ExitAppCommandStr = L"ExitApp"; ///////////////////////////////////////////////////////////////////////////////////////////// bool isElevatedProcess(); diff --git a/src/Notepads.Services/DesktopExtensionConnectionService.cs b/src/Notepads.Services/DesktopExtensionConnectionService.cs index 176c531e6..98e9e03a3 100644 --- a/src/Notepads.Services/DesktopExtensionConnectionService.cs +++ b/src/Notepads.Services/DesktopExtensionConnectionService.cs @@ -10,7 +10,6 @@ using Windows.ApplicationModel; using Windows.ApplicationModel.AppService; using Windows.ApplicationModel.Background; - using Windows.Foundation.Collections; public sealed class DesktopExtensionConnectionService : IBackgroundTask { @@ -116,8 +115,10 @@ private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequ messageDeferral.Complete(); } - private async void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) + private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) { + var deferral = sender.GetDeferral(); + if (this.backgroundTaskDeferral != null) { // Complete the service deferral. @@ -131,13 +132,10 @@ private async void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTask else { appServiceConnections.Remove(serviceConnection); - if (appServiceConnections.Count == 0 && extensionAppServiceConnection != null) - { - var message = new ValueSet { { SettingsKey.InteropCommandLabel, SettingsKey.ExitAppCommandStr } }; - await extensionAppServiceConnection.SendMessageAsync(message); - } } } + + deferral.Complete(); } // Occurs when an exception is not handled on a background thread. diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index e44447e99..d7b8ee83a 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -35,6 +35,7 @@ public static class DesktopExtensionService !new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); public static AppServiceConnection InteropServiceConnection = null; + public static NamedPipeServerStream ExtensionLifetimeObject = null; private static readonly ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView(); private static EventWaitHandle _adminWriteEvent = null; @@ -43,7 +44,18 @@ public static async Task Initialize() { if (!ShouldUseDesktopExtension) return false; - _adminWriteEvent = new EventWaitHandle(false, EventResetMode.ManualReset, SettingsKey.AdminWriteEventNameStr); + if (ExtensionLifetimeObject == null) + { + ExtensionLifetimeObject = new NamedPipeServerStream( + $"Local\\{SettingsKey.DesktopExtensionLifetimeObjNameStr}", + PipeDirection.In, + NamedPipeServerStream.MaxAllowedServerInstances); + } + + if (_adminWriteEvent == null) + { + _adminWriteEvent = new EventWaitHandle(false, EventResetMode.ManualReset, SettingsKey.AdminWriteEventNameStr); + } InteropServiceConnection = new AppServiceConnection() { diff --git a/src/Notepads/Settings/SettingsKey.cs b/src/Notepads/Settings/SettingsKey.cs index 4a70c4c65..b1abc996b 100644 --- a/src/Notepads/Settings/SettingsKey.cs +++ b/src/Notepads/Settings/SettingsKey.cs @@ -42,6 +42,7 @@ internal static class SettingsKey internal const string AppCenterInstallIdStr = "AppCenterInstallIdStr"; internal const string InteropServiceName = "DesktopExtensionServiceConnection"; // Keep this same as AppSeviceName value in manifest internal const string PackageSidStr = "PackageSidStr"; + internal const string DesktopExtensionLifetimeObjNameStr = "DesktopExtensionLifetimeObj"; internal const string AdminWriteEventNameStr = "NotepadsAdminWriteEvent"; internal const string AdminPipeConnectionNameStr = "NotepadsAdminWritePipe"; internal const string InteropCommandAdminCreatedLabel = "AdminCreated"; @@ -51,6 +52,5 @@ internal static class SettingsKey internal const string InteropCommandFailedLabel = "Failed"; internal const string RegisterExtensionCommandStr = "RegisterExtension"; internal const string CreateElevetedExtensionCommandStr = "CreateElevetedExtension"; - internal const string ExitAppCommandStr = "ExitApp"; } } \ No newline at end of file diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs index af8a159c7..e0177ee2e 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs @@ -361,12 +361,14 @@ private async void MainPage_CloseRequested(object sender, Windows.UI.Core.Previe { // Save session before app exit await SessionManager.SaveSessionAsync(() => { SessionManager.IsBackupEnabled = false; }); + DesktopExtensionService.ExtensionLifetimeObject?.Dispose(); deferral.Complete(); return; } if (!NotepadsCore.HaveUnsavedTextEditor()) { + DesktopExtensionService.ExtensionLifetimeObject?.Dispose(); deferral.Complete(); return; } @@ -398,15 +400,18 @@ private async void MainPage_CloseRequested(object sender, Windows.UI.Core.Previe await BuildOpenRecentButtonSubItems(); } + DesktopExtensionService.ExtensionLifetimeObject?.Dispose(); deferral.Complete(); }, discardAndExitAction: () => { + DesktopExtensionService.ExtensionLifetimeObject?.Dispose(); deferral.Complete(); }, cancelAction: () => { e.Handled = true; + DesktopExtensionService.ExtensionLifetimeObject?.Dispose(); deferral.Complete(); }); @@ -415,6 +420,7 @@ private async void MainPage_CloseRequested(object sender, Windows.UI.Core.Previe if (result == null) { e.Handled = true; + DesktopExtensionService.ExtensionLifetimeObject?.Dispose(); deferral.Complete(); } From 3df5a01d061b034357e8cafb7973be36e91e2207 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sun, 3 Jan 2021 19:57:49 +0530 Subject: [PATCH 131/181] Clean up unnecessary references. --- src/Notepads.Services/Properties/AssemblyInfo.cs | 5 ++--- src/Notepads/Notepads.csproj | 7 +------ 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/src/Notepads.Services/Properties/AssemblyInfo.cs b/src/Notepads.Services/Properties/AssemblyInfo.cs index 7b0f0f6c3..97de743a3 100644 --- a/src/Notepads.Services/Properties/AssemblyInfo.cs +++ b/src/Notepads.Services/Properties/AssemblyInfo.cs @@ -1,16 +1,15 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Notepads.Services")] -[assembly: AssemblyDescription("")] +[assembly: AssemblyDescription("A background task to connect Notepads with its Desktop Extension.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Notepads.Services")] -[assembly: AssemblyCopyright("Copyright © 2020")] +[assembly: AssemblyCopyright("Copyright © Jackie Liu 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] diff --git a/src/Notepads/Notepads.csproj b/src/Notepads/Notepads.csproj index ac9afe710..c042da2bf 100644 --- a/src/Notepads/Notepads.csproj +++ b/src/Notepads/Notepads.csproj @@ -678,9 +678,7 @@ - - Designer - + @@ -886,9 +884,6 @@ - - - Windows Desktop Extensions for the UWP From 4392113888572b3cabde8d69f4ef04e584e19bde Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Mon, 4 Jan 2021 02:19:05 +0530 Subject: [PATCH 132/181] Fix desktop extension lifetime. --- src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs index e0177ee2e..5b3d7d513 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs @@ -399,8 +399,11 @@ private async void MainPage_CloseRequested(object sender, Windows.UI.Core.Previe e.Handled = true; await BuildOpenRecentButtonSubItems(); } + else + { + DesktopExtensionService.ExtensionLifetimeObject?.Dispose(); + } - DesktopExtensionService.ExtensionLifetimeObject?.Dispose(); deferral.Complete(); }, discardAndExitAction: () => @@ -411,7 +414,6 @@ private async void MainPage_CloseRequested(object sender, Windows.UI.Core.Previe cancelAction: () => { e.Handled = true; - DesktopExtensionService.ExtensionLifetimeObject?.Dispose(); deferral.Complete(); }); @@ -420,7 +422,6 @@ private async void MainPage_CloseRequested(object sender, Windows.UI.Core.Previe if (result == null) { e.Handled = true; - DesktopExtensionService.ExtensionLifetimeObject?.Dispose(); deferral.Complete(); } From e1c950d4a94d4eeec33a5f23191c2b77fb61f50c Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Tue, 5 Jan 2021 11:45:09 +0530 Subject: [PATCH 133/181] Added functionality to rename system files. --- .../PropertySheet.props | 1 + src/Notepads.DesktopExtension/elevated.cpp | 90 ++++++++++++++++++- src/Notepads.DesktopExtension/pch.h | 5 +- .../Dialog/CreateElevatedExtensionDialog.cs | 19 ---- .../Dialog/LaunchElevatedExtensionDialog.cs | 30 +++++++ .../Controls/TextEditor/TextEditor.xaml.cs | 26 +++++- src/Notepads/Core/TabContextFlyout.cs | 1 - src/Notepads/Notepads.csproj | 2 +- .../Services/DesktopExtensionService.cs | 70 ++++++++++++++- src/Notepads/Settings/SettingsKey.cs | 4 +- src/Notepads/Strings/en-US/Resources.resw | 32 +++++-- .../Views/MainPage/NotepadsMainPage.IO.cs | 8 +- 12 files changed, 248 insertions(+), 40 deletions(-) delete mode 100644 src/Notepads/Controls/Dialog/CreateElevatedExtensionDialog.cs create mode 100644 src/Notepads/Controls/Dialog/LaunchElevatedExtensionDialog.cs diff --git a/src/Notepads.DesktopExtension/PropertySheet.props b/src/Notepads.DesktopExtension/PropertySheet.props index afef4a14a..e5b027614 100644 --- a/src/Notepads.DesktopExtension/PropertySheet.props +++ b/src/Notepads.DesktopExtension/PropertySheet.props @@ -16,6 +16,7 @@ 50ea8c0ab7aca3bb9245bba7fc877ad2f2a4464c + windows \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/elevated.cpp b/src/Notepads.DesktopExtension/elevated.cpp index a32297edc..bf341a136 100644 --- a/src/Notepads.DesktopExtension/elevated.cpp +++ b/src/Notepads.DesktopExtension/elevated.cpp @@ -6,6 +6,7 @@ using namespace fmt; using namespace std; using namespace winrt; using namespace Windows::ApplicationModel; +using namespace Windows::ApplicationModel::DataTransfer; using namespace Windows::Foundation; using namespace Windows::Storage; @@ -15,6 +16,7 @@ extern DWORD sessionId; extern hstring packageSid; HANDLE adminWriteEvent = NULL; +HANDLE adminRenameEvent = NULL; IInspectable readSettingsKey(hstring key) { @@ -29,7 +31,7 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) LPCTSTR result = L"Failed"; wstring pipeName = format(L"\\\\.\\pipe\\Sessions\\{}\\AppContainerNamedObjects\\{}\\{}\\{}", - sessionId, packageSid, Package::Current().Id().FamilyName(), AdminPipeConnectionNameStr); + sessionId, packageSid, Package::Current().Id().FamilyName(), AdminWritePipeConnectionNameStr); HANDLE hPipe = INVALID_HANDLE_VALUE; if (!WaitForSingleObject(adminWriteEvent, INFINITE) && ResetEvent(adminWriteEvent) && WaitNamedPipe(pipeName.c_str(), NMPWAIT_WAIT_FOREVER)) @@ -132,13 +134,99 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) return 0; } +DWORD WINAPI renameFileFromPipeData(LPVOID /* param */) +{ + setExceptionHandling(); + + vector> properties; + LPCTSTR result = L"Failed"; + + wstring pipeName = format(L"\\\\.\\pipe\\Sessions\\{}\\AppContainerNamedObjects\\{}\\{}\\{}", + sessionId, packageSid, Package::Current().Id().FamilyName(), AdminRenamePipeConnectionNameStr); + + HANDLE hPipe = INVALID_HANDLE_VALUE; + if (!WaitForSingleObject(adminRenameEvent, INFINITE) && ResetEvent(adminRenameEvent) && WaitNamedPipe(pipeName.c_str(), NMPWAIT_WAIT_FOREVER)) + { + hPipe = CreateFile(pipeName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + } + + if (hPipe) + { + CreateThread(NULL, 0, renameFileFromPipeData, NULL, 0, NULL); + + TCHAR readBuffer[PIPE_READ_BUFFER]; + wstringstream pipeData; + DWORD byteRead; + do + { + fill(begin(readBuffer), end(readBuffer), '\0'); + if (ReadFile(hPipe, readBuffer, (PIPE_READ_BUFFER - 1) * sizeof(TCHAR), &byteRead, NULL)) + { + pipeData << readBuffer; + } + } while (byteRead >= (PIPE_READ_BUFFER - 1) * sizeof(TCHAR)); + + wstring fileToken; + wstring newName; + getline(pipeData, fileToken, L'|'); + getline(pipeData, newName, L'|'); + + auto file = SharedStorageAccessManager::RedeemTokenForFileAsync(fileToken).get(); + SharedStorageAccessManager::RemoveFile(fileToken); + file.RenameAsync(newName).get(); + result = SharedStorageAccessManager::AddFile(file).c_str(); + + if (WriteFile(hPipe, result, wcslen(result) * sizeof(TCHAR), NULL, NULL)) FlushFileBuffers(hPipe); + CloseHandle(hPipe); + + if (wcscmp(result, L"Failed") == 0) + { + pair ex = getLastErrorDetails(); + properties.insert(properties.end(), + { + pair("Result", to_string(result)), + pair("Error Code", to_string(ex.first)), + pair("Error Message", winrt::to_string(ex.second)) + }); + printDebugMessage(format(L"Failed to write to \"{}\"", file.Path()).c_str()); + } + else + { + properties.push_back(pair("Result", "Success")); + printDebugMessage(format(L"Successfully wrote to \"{}\"", file.Path()).c_str()); + } + printDebugMessage(L"Waiting on uwp app to send data."); + + AppCenter::trackEvent("OnRenameToSystemFileRequested", properties); + } + else + { + properties.push_back(pair("Result", to_string(result))); + pair ex = getLastErrorDetails(); + properties.insert(properties.end(), + { + pair("Result", to_string(result)), + pair("Error Code", to_string(ex.first)), + pair("Error Message", winrt::to_string(ex.second)) + }); + AppCenter::trackEvent("OnRenameToSystemFileRequested", properties); + exitApp(); + } + + return 0; +} + void initializeAdminService() { adminWriteEvent = OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, format(L"AppContainerNamedObjects\\{}\\{}", packageSid, AdminWriteEventNameStr).c_str()); + adminRenameEvent = OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, + format(L"AppContainerNamedObjects\\{}\\{}", packageSid, AdminRenameEventNameStr).c_str()); + printDebugMessage(L"Successfully started Adminstrator Extension."); printDebugMessage(L"Waiting on uwp app to send data."); CreateThread(NULL, 0, saveFileFromPipeData, NULL, 0, NULL); + CreateThread(NULL, 0, renameFileFromPipeData, NULL, 0, NULL); } \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h index 489b88de3..2d3ca93ed 100644 --- a/src/Notepads.DesktopExtension/pch.h +++ b/src/Notepads.DesktopExtension/pch.h @@ -6,6 +6,7 @@ #include "shellapi.h" #include "winrt/Windows.ApplicationModel.h" #include "winrt/Windows.ApplicationModel.AppService.h" +#include "winrt/Windows.ApplicationModel.DataTransfer.h" #include "winrt/Windows.Foundation.h" #include "winrt/Windows.Foundation.Collections.h" #include "winrt/Windows.Security.ExchangeActiveSyncProvisioning.h" @@ -24,7 +25,9 @@ constexpr LPCTSTR InteropServiceName = L"DesktopExtensionServiceConnection"; constexpr LPCTSTR PackageSidStr = L"PackageSidStr"; constexpr LPCTSTR DesktopExtensionLifetimeObjNameStr = L"DesktopExtensionLifetimeObj"; constexpr LPCTSTR AdminWriteEventNameStr = L"NotepadsAdminWriteEvent"; -constexpr LPCTSTR AdminPipeConnectionNameStr = L"NotepadsAdminWritePipe"; +constexpr LPCTSTR AdminWritePipeConnectionNameStr = L"NotepadsAdminWritePipe"; +constexpr LPCTSTR AdminRenameEventNameStr = L"NotepadsAdminRenameEvent"; +constexpr LPCTSTR AdminRenamePipeConnectionNameStr = L"NotepadsAdminRenamePipe"; constexpr LPCTSTR InteropCommandLabel = L"Command"; constexpr LPCTSTR InteropCommandAdminCreatedLabel = L"AdminCreated"; constexpr LPCTSTR RegisterExtensionCommandStr = L"RegisterExtension"; diff --git a/src/Notepads/Controls/Dialog/CreateElevatedExtensionDialog.cs b/src/Notepads/Controls/Dialog/CreateElevatedExtensionDialog.cs deleted file mode 100644 index 4c618b5d7..000000000 --- a/src/Notepads/Controls/Dialog/CreateElevatedExtensionDialog.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace Notepads.Controls.Dialog -{ - using System; - using Windows.ApplicationModel.Resources; - - public class CreateElevatedExtensionDialog : NotepadsDialog - { - public CreateElevatedExtensionDialog(Action confirmedAction, Action closeAction) - { - Title = ResourceLoader.GetString("CreateElevatedExtensionDialog_Title"); - Content = ResourceLoader.GetString("CreateElevatedExtensionDialog_Content"); - PrimaryButtonText = ResourceLoader.GetString("RevertAllChangesConfirmationDialog_PrimaryButtonText"); - CloseButtonText = ResourceLoader.GetString("CreateElevatedExtensionDialog_CloseButtonText"); - - PrimaryButtonClick += (dialog, args) => { confirmedAction(); }; - CloseButtonClick += (dialog, args) => { closeAction(); }; - } - } -} diff --git a/src/Notepads/Controls/Dialog/LaunchElevatedExtensionDialog.cs b/src/Notepads/Controls/Dialog/LaunchElevatedExtensionDialog.cs new file mode 100644 index 000000000..a4a2ffe7b --- /dev/null +++ b/src/Notepads/Controls/Dialog/LaunchElevatedExtensionDialog.cs @@ -0,0 +1,30 @@ +namespace Notepads.Controls.Dialog +{ + using System; + using Notepads.Services; + using Windows.ApplicationModel.Resources; + + public class LaunchElevatedExtensionDialog : NotepadsDialog + { + public LaunchElevatedExtensionDialog(AdminOperationType type, string fileName, Action confirmedAction, Action closeAction) + { + if (type == AdminOperationType.Save) + { + Title = ResourceLoader.GetString("LaunchElevatedExtensionDialog_SaveFailed_Title"); + Content = string.Format(ResourceLoader.GetString("LaunchElevatedExtensionDialog_SaveFailed_Content"), fileName); + CloseButtonText = ResourceLoader.GetString("LaunchElevatedExtensionDialog_SaveFailed_CloseButtonText"); + } + else + { + Title = ResourceLoader.GetString("LaunchElevatedExtensionDialog_RenameFailed_Title"); + Content = string.Format(ResourceLoader.GetString("LaunchElevatedExtensionDialog_RenameFailed_Content"), fileName); + CloseButtonText = ResourceLoader.GetString("LaunchElevatedExtensionDialog_RenameFailed_CloseButtonText"); + } + + PrimaryButtonText = ResourceLoader.GetString("LaunchElevatedExtensionDialog_PrimaryButtonText"); + + if (confirmedAction != null) PrimaryButtonClick += (dialog, args) => { confirmedAction(); }; + if (closeAction != null) CloseButtonClick += (dialog, args) => { closeAction(); }; + } + } +} diff --git a/src/Notepads/Controls/TextEditor/TextEditor.xaml.cs b/src/Notepads/Controls/TextEditor/TextEditor.xaml.cs index b85923151..d88f84075 100644 --- a/src/Notepads/Controls/TextEditor/TextEditor.xaml.cs +++ b/src/Notepads/Controls/TextEditor/TextEditor.xaml.cs @@ -294,18 +294,38 @@ await Dispatcher.CallOnUIThreadAsync(() => public async Task RenameAsync(string newFileName) { + var result = false; + if (EditingFile == null) { FileNamePlaceholder = newFileName; + result = true; } else { - await EditingFile.RenameAsync(newFileName); + try + { + await EditingFile.RenameAsync(newFileName); + result = true; + } + catch (UnauthorizedAccessException) + { + var file = await DesktopExtensionService.RenameFileAsAdmin(EditingFile, newFileName); + if (file != null) + { + EditingFile = file; + result = true; + } + } } - UpdateDocumentInfo(); + if (result) + { + UpdateDocumentInfo(); - FileRenamed?.Invoke(this, EventArgs.Empty); + FileRenamed?.Invoke(this, EventArgs.Empty); + NotificationCenter.Instance.PostNotification(_resourceLoader.GetString("TextEditor_NotificationMsg_FileRenamed"), 1500); + } } public string GetText() diff --git a/src/Notepads/Core/TabContextFlyout.cs b/src/Notepads/Core/TabContextFlyout.cs index 1c3a61917..0eabf669a 100644 --- a/src/Notepads/Core/TabContextFlyout.cs +++ b/src/Notepads/Core/TabContextFlyout.cs @@ -257,7 +257,6 @@ private MenuFlyoutItem Rename { await _textEditor.RenameAsync(newFilename); _notepadsCore.FocusOnSelectedTextEditor(); - NotificationCenter.Instance.PostNotification(_resourceLoader.GetString("TextEditor_NotificationMsg_FileRenamed"), 1500); } catch (Exception ex) { diff --git a/src/Notepads/Notepads.csproj b/src/Notepads/Notepads.csproj index c042da2bf..9facee008 100644 --- a/src/Notepads/Notepads.csproj +++ b/src/Notepads/Notepads.csproj @@ -132,7 +132,7 @@ - + diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index d7b8ee83a..f90fed12a 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -3,8 +3,10 @@ using Microsoft.AppCenter; using Microsoft.AppCenter.Analytics; using Microsoft.Toolkit.Uwp.Helpers; + using Notepads.Controls.Dialog; using Notepads.Extensions; using Notepads.Settings; + using Notepads.Utilities; using System; using System.Collections.Generic; using System.IO; @@ -16,10 +18,18 @@ using Windows.ApplicationModel; using Windows.ApplicationModel.AppService; using Windows.ApplicationModel.Core; + using Windows.ApplicationModel.DataTransfer; using Windows.ApplicationModel.Resources; using Windows.Foundation.Collections; using Windows.Foundation.Metadata; using Windows.Security.Authentication.Web; + using Windows.Storage; + + public enum AdminOperationType + { + Save, + Rename + } public class AdminstratorAccessException : Exception { @@ -39,6 +49,7 @@ public static class DesktopExtensionService private static readonly ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView(); private static EventWaitHandle _adminWriteEvent = null; + private static EventWaitHandle _adminRenameEvent = null; public static async Task Initialize() { @@ -57,6 +68,11 @@ public static async Task Initialize() _adminWriteEvent = new EventWaitHandle(false, EventResetMode.ManualReset, SettingsKey.AdminWriteEventNameStr); } + if (_adminRenameEvent == null) + { + _adminRenameEvent = new EventWaitHandle(false, EventResetMode.ManualReset, SettingsKey.AdminRenameEventNameStr); + } + InteropServiceConnection = new AppServiceConnection() { AppServiceName = SettingsKey.InteropServiceName, @@ -126,7 +142,7 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) if (InteropServiceConnection == null && !(await Initialize())) return; using (var adminConnectionPipeStream = new NamedPipeServerStream( - $"Local\\{Package.Current.Id.FamilyName}\\{SettingsKey.AdminPipeConnectionNameStr}", + $"Local\\{Package.Current.Id.FamilyName}\\{SettingsKey.AdminWritePipeConnectionNameStr}", PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, @@ -173,6 +189,58 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) } } + public static async Task RenameFileAsAdmin(StorageFile file, string newName) + { + if (InteropServiceConnection == null && !(await Initialize())) return null; + + var token = SharedStorageAccessManager.AddFile(file); + + using (var adminConnectionPipeStream = new NamedPipeServerStream( + $"Local\\{Package.Current.Id.FamilyName}\\{SettingsKey.AdminRenamePipeConnectionNameStr}", + PipeDirection.InOut, + NamedPipeServerStream.MaxAllowedServerInstances, + PipeTransmissionMode.Message, + PipeOptions.Asynchronous)) + { + _adminRenameEvent.Set(); + // Wait for 250 ms for desktop extension to accept request. + if (!adminConnectionPipeStream.WaitForConnectionAsync().Wait(250)) + { + // If the connection fails, desktop extension is not launched with elevated privilages. + // In that case, prompt user to launch desktop extension with elevated privilages. + _adminRenameEvent.Reset(); + var launchElevatedExtensionDialog = new LaunchElevatedExtensionDialog( + AdminOperationType.Rename, + file.Path, + async () => { await DesktopExtensionService.CreateElevetedExtension(); }, + null); + + var dialogResult = await DialogManager.OpenDialogAsync(launchElevatedExtensionDialog, awaitPreviousDialog: false); + + return null; + } + + var pipeReader = new StreamReader(adminConnectionPipeStream, new System.Text.UnicodeEncoding(!BitConverter.IsLittleEndian, false)); + var pipeWriter = new StreamWriter(adminConnectionPipeStream, new System.Text.UnicodeEncoding(!BitConverter.IsLittleEndian, false)); + + await pipeWriter.WriteAsync($"{token}|{newName}"); + await pipeWriter.FlushAsync(); + + // Wait for desktop extension to send response. + token = await pipeReader.ReadLineAsync(); + try + { + file = await SharedStorageAccessManager.RedeemTokenForFileAsync(token); + SharedStorageAccessManager.RemoveFile(token); + return file; + } + catch + { + throw new UnauthorizedAccessException(); + } + } + } + /// /// Launch desktop extension with elevated privilages. /// diff --git a/src/Notepads/Settings/SettingsKey.cs b/src/Notepads/Settings/SettingsKey.cs index b1abc996b..efaa12651 100644 --- a/src/Notepads/Settings/SettingsKey.cs +++ b/src/Notepads/Settings/SettingsKey.cs @@ -44,7 +44,9 @@ internal static class SettingsKey internal const string PackageSidStr = "PackageSidStr"; internal const string DesktopExtensionLifetimeObjNameStr = "DesktopExtensionLifetimeObj"; internal const string AdminWriteEventNameStr = "NotepadsAdminWriteEvent"; - internal const string AdminPipeConnectionNameStr = "NotepadsAdminWritePipe"; + internal const string AdminWritePipeConnectionNameStr = "NotepadsAdminWritePipe"; + internal const string AdminRenameEventNameStr = "NotepadsAdminRenameEvent"; + internal const string AdminRenamePipeConnectionNameStr = "NotepadsAdminRenamePipe"; internal const string InteropCommandAdminCreatedLabel = "AdminCreated"; #endif internal const string AppCenterSecret = null; diff --git a/src/Notepads/Strings/en-US/Resources.resw b/src/Notepads/Strings/en-US/Resources.resw index 6e4b6493b..7ba5acad3 100644 --- a/src/Notepads/Strings/en-US/Resources.resw +++ b/src/Notepads/Strings/en-US/Resources.resw @@ -693,17 +693,17 @@ File extension "{0}" is not supported at this moment FileRenameError: Extension is not currently supported. {0} stands for the file extension string. - - No - CreateElevatedExtensionDialog: CloseButtonText. + + Save As + LaunchElevatedExtensionDialog: Save Failed CloseButtonText. - - The file cannot be saved, it may be protected. Do you want to give Notepads Adminstrator permission? - CreateElevatedExtensionDialog: "Content" display text. + + Notepads needs Adminstrative Privilage to modify file "{0}" + LaunchElevatedExtensionDialog: Save Failed "Content" display text. - + Save Failed - CreateElevatedExtensionDialog: "Title" display text. + LaunchElevatedExtensionDialog: Save Failed "Title" display text. Now system files can be directly modified @@ -713,4 +713,20 @@ Failed to start admin process TextEditor: Notification message when launching of admin process is failed. + + Give Access + LaunchElevatedExtensionDialog: PrimaryButtonText. + + + Cancel + LaunchElevatedExtensionDialog: Rename Failed CloseButtonText. + + + Notepads needs Adminstrative Privilage to rename file "{0}" + LaunchElevatedExtensionDialog: Rename Failed "Content" display text. + + + Rename Failed + LaunchElevatedExtensionDialog: Rename Failed "Title" display text. + \ No newline at end of file diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs index 0774b90e4..7eccec55e 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs @@ -170,7 +170,8 @@ private async Task TrySaveFile(ITextEditor textEditor, StorageFile file, b } catch (AdminstratorAccessException) // Happens when the file we are saving is read-only, ask user for permission to write { - var createElevatedExtensionDialog = new CreateElevatedExtensionDialog( + var launchElevatedExtensionDialog = new LaunchElevatedExtensionDialog( + AdminOperationType.Save, file.Path, async () => { await DesktopExtensionService.CreateElevetedExtension(); @@ -180,9 +181,9 @@ private async Task TrySaveFile(ITextEditor textEditor, StorageFile file, b isSaveSuccess = false; }); - var dialogResult = await DialogManager.OpenDialogAsync(createElevatedExtensionDialog, awaitPreviousDialog: false); + var dialogResult = await DialogManager.OpenDialogAsync(launchElevatedExtensionDialog, awaitPreviousDialog: false); - if (dialogResult == null || createElevatedExtensionDialog.IsAborted) + if (dialogResult == null || launchElevatedExtensionDialog.IsAborted) { isSaveSuccess = false; } @@ -270,7 +271,6 @@ private async Task RenameFileAsync(ITextEditor textEditor) { await textEditor.RenameAsync(newFilename); NotepadsCore.FocusOnSelectedTextEditor(); - NotificationCenter.Instance.PostNotification(_resourceLoader.GetString("TextEditor_NotificationMsg_FileRenamed"), 1500); } catch (Exception ex) { From b0d5e214d1b40f93fda8fd2d5426b3967a8013ac Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Tue, 5 Jan 2021 23:32:47 +0530 Subject: [PATCH 134/181] Code refactor. --- src/Notepads.DesktopExtension/elevated.cpp | 42 ++++++++----------- src/Notepads.DesktopExtension/main.cpp | 9 ++++ .../Services/DesktopExtensionService.cs | 21 +++++----- 3 files changed, 37 insertions(+), 35 deletions(-) diff --git a/src/Notepads.DesktopExtension/elevated.cpp b/src/Notepads.DesktopExtension/elevated.cpp index bf341a136..50e40c819 100644 --- a/src/Notepads.DesktopExtension/elevated.cpp +++ b/src/Notepads.DesktopExtension/elevated.cpp @@ -7,10 +7,10 @@ using namespace std; using namespace winrt; using namespace Windows::ApplicationModel; using namespace Windows::ApplicationModel::DataTransfer; -using namespace Windows::Foundation; -using namespace Windows::Storage; constexpr INT PIPE_READ_BUFFER = 2 * MAX_PATH + 10; +constexpr LPCTSTR pipeNameFormat = L"\\\\.\\pipe\\Sessions\\{}\\AppContainerNamedObjects\\{}\\{}\\{}"; +constexpr LPCTSTR namedObjectFormat = L"AppContainerNamedObjects\\{}\\{}"; extern DWORD sessionId; extern hstring packageSid; @@ -18,10 +18,8 @@ extern hstring packageSid; HANDLE adminWriteEvent = NULL; HANDLE adminRenameEvent = NULL; -IInspectable readSettingsKey(hstring key) -{ - return ApplicationData::Current().LocalSettings().Values().TryLookup(key); -} +wstring writePipeName; +wstring renamePipeName; DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) { @@ -30,13 +28,10 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) vector> properties; LPCTSTR result = L"Failed"; - wstring pipeName = format(L"\\\\.\\pipe\\Sessions\\{}\\AppContainerNamedObjects\\{}\\{}\\{}", - sessionId, packageSid, Package::Current().Id().FamilyName(), AdminWritePipeConnectionNameStr); - HANDLE hPipe = INVALID_HANDLE_VALUE; - if (!WaitForSingleObject(adminWriteEvent, INFINITE) && ResetEvent(adminWriteEvent) && WaitNamedPipe(pipeName.c_str(), NMPWAIT_WAIT_FOREVER)) + if (!WaitForSingleObject(adminWriteEvent, INFINITE) && ResetEvent(adminWriteEvent) && WaitNamedPipe(writePipeName.c_str(), NMPWAIT_WAIT_FOREVER)) { - hPipe = CreateFile(pipeName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + hPipe = CreateFile(writePipeName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); } if (hPipe) @@ -63,7 +58,7 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) getline(pipeData, dataArrayLengthStr); INT dataArrayLength = stoi(dataArrayLengthStr); - wstring memoryMapName = format(L"AppContainerNamedObjects\\{}\\{}", packageSid, memoryMapId); + wstring memoryMapName = format(namedObjectFormat, packageSid, memoryMapId); HANDLE hMemory = OpenFileMapping(FILE_MAP_READ, FALSE, memoryMapName.c_str()); if (hMemory) @@ -120,10 +115,10 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) } else { - properties.push_back(pair("Result", to_string(result))); pair ex = getLastErrorDetails(); properties.insert(properties.end(), { + pair("Result", to_string(result)), pair("Error Code", to_string(ex.first)), pair("Error Message", winrt::to_string(ex.second)) }); @@ -141,13 +136,10 @@ DWORD WINAPI renameFileFromPipeData(LPVOID /* param */) vector> properties; LPCTSTR result = L"Failed"; - wstring pipeName = format(L"\\\\.\\pipe\\Sessions\\{}\\AppContainerNamedObjects\\{}\\{}\\{}", - sessionId, packageSid, Package::Current().Id().FamilyName(), AdminRenamePipeConnectionNameStr); - HANDLE hPipe = INVALID_HANDLE_VALUE; - if (!WaitForSingleObject(adminRenameEvent, INFINITE) && ResetEvent(adminRenameEvent) && WaitNamedPipe(pipeName.c_str(), NMPWAIT_WAIT_FOREVER)) + if (!WaitForSingleObject(adminRenameEvent, INFINITE) && ResetEvent(adminRenameEvent) && WaitNamedPipe(renamePipeName.c_str(), NMPWAIT_WAIT_FOREVER)) { - hPipe = CreateFile(pipeName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); + hPipe = CreateFile(renamePipeName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); } if (hPipe) @@ -173,6 +165,7 @@ DWORD WINAPI renameFileFromPipeData(LPVOID /* param */) auto file = SharedStorageAccessManager::RedeemTokenForFileAsync(fileToken).get(); SharedStorageAccessManager::RemoveFile(fileToken); + auto oldName = file.Path(); file.RenameAsync(newName).get(); result = SharedStorageAccessManager::AddFile(file).c_str(); @@ -188,12 +181,12 @@ DWORD WINAPI renameFileFromPipeData(LPVOID /* param */) pair("Error Code", to_string(ex.first)), pair("Error Message", winrt::to_string(ex.second)) }); - printDebugMessage(format(L"Failed to write to \"{}\"", file.Path()).c_str()); + printDebugMessage(format(L"Failed to rename \"{}\" to \"{}\"", oldName, newName).c_str()); } else { properties.push_back(pair("Result", "Success")); - printDebugMessage(format(L"Successfully wrote to \"{}\"", file.Path()).c_str()); + printDebugMessage(format(L"Successfully renamed \"{}\" to \"{}\"", oldName, newName).c_str()); } printDebugMessage(L"Waiting on uwp app to send data."); @@ -201,7 +194,6 @@ DWORD WINAPI renameFileFromPipeData(LPVOID /* param */) } else { - properties.push_back(pair("Result", to_string(result))); pair ex = getLastErrorDetails(); properties.insert(properties.end(), { @@ -218,11 +210,11 @@ DWORD WINAPI renameFileFromPipeData(LPVOID /* param */) void initializeAdminService() { - adminWriteEvent = OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, - format(L"AppContainerNamedObjects\\{}\\{}", packageSid, AdminWriteEventNameStr).c_str()); + adminWriteEvent = OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, format(namedObjectFormat, packageSid, AdminWriteEventNameStr).c_str()); + adminRenameEvent = OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, format(namedObjectFormat, packageSid, AdminRenameEventNameStr).c_str()); - adminRenameEvent = OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, - format(L"AppContainerNamedObjects\\{}\\{}", packageSid, AdminRenameEventNameStr).c_str()); + writePipeName = format(pipeNameFormat, sessionId, packageSid, Package::Current().Id().FamilyName(), AdminWritePipeConnectionNameStr); + renamePipeName = format(pipeNameFormat, sessionId, packageSid, Package::Current().Id().FamilyName(), AdminRenamePipeConnectionNameStr); printDebugMessage(L"Successfully started Adminstrator Extension."); printDebugMessage(L"Waiting on uwp app to send data."); diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index e3861dacd..b03a7fb14 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -4,6 +4,8 @@ using namespace fmt; using namespace std; using namespace winrt; +using namespace Windows::Foundation; +using namespace Windows::Storage; constexpr LPCTSTR DesktopExtensionMutexName = L"DesktopExtensionMutexName"; constexpr LPCTSTR AdminExtensionMutexName = L"AdminExtensionMutexName"; @@ -12,11 +14,18 @@ DWORD sessionId; hstring packageSid = unbox_value_or(readSettingsKey(PackageSidStr), L""); extern HANDLE adminWriteEvent; +extern HANDLE adminRenameEvent; extern HANDLE appExitJob; +IInspectable readSettingsKey(hstring key) +{ + return ApplicationData::Current().LocalSettings().Values().TryLookup(key); +} + INT releaseResources() { CloseHandle(adminWriteEvent); + CloseHandle(adminRenameEvent); CloseHandle(appExitJob); return 0; } diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index f90fed12a..266c4f6e1 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -189,6 +189,14 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) } } + /// + /// Rename system file. + /// + /// + /// Only available for legacy Windows 10 desktop. + /// + /// File to rename + /// New name public static async Task RenameFileAsAdmin(StorageFile file, string newName) { if (InteropServiceConnection == null && !(await Initialize())) return null; @@ -228,16 +236,9 @@ public static async Task RenameFileAsAdmin(StorageFile file, string // Wait for desktop extension to send response. token = await pipeReader.ReadLineAsync(); - try - { - file = await SharedStorageAccessManager.RedeemTokenForFileAsync(token); - SharedStorageAccessManager.RemoveFile(token); - return file; - } - catch - { - throw new UnauthorizedAccessException(); - } + file = await SharedStorageAccessManager.RedeemTokenForFileAsync(token); + SharedStorageAccessManager.RemoveFile(token); + return file; } } From 198e1af050afb4994b4f3a2618db30405e3cb1b2 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 7 Jan 2021 19:38:01 +0530 Subject: [PATCH 135/181] code refacor. --- .../PropertySheet.props | 2 +- src/Notepads.DesktopExtension/appcenter.cpp | 6 +++--- src/Notepads.DesktopExtension/appcenter.h | 6 +++--- src/Notepads.DesktopExtension/device.h | 2 +- src/Notepads.DesktopExtension/elevated.cpp | 12 ++++++------ src/Notepads.DesktopExtension/exception.h | 4 ++-- src/Notepads.DesktopExtension/extension.cpp | 4 ++-- src/Notepads.DesktopExtension/log.h | 4 ++-- src/Notepads.DesktopExtension/main.cpp | 15 +++++++++++---- src/Notepads.DesktopExtension/pch.cpp | 2 +- src/Notepads.DesktopExtension/pch.h | 8 ++++---- src/Notepads.DesktopExtension/vcpkg.json | 2 +- .../Services/DesktopExtensionService.cs | 18 ++++++++++++++++-- .../Views/MainPage/NotepadsMainPage.xaml.cs | 8 -------- 14 files changed, 53 insertions(+), 40 deletions(-) diff --git a/src/Notepads.DesktopExtension/PropertySheet.props b/src/Notepads.DesktopExtension/PropertySheet.props index e5b027614..6067a2369 100644 --- a/src/Notepads.DesktopExtension/PropertySheet.props +++ b/src/Notepads.DesktopExtension/PropertySheet.props @@ -14,7 +14,7 @@ https://github.com/microsoft/vcpkg - 50ea8c0ab7aca3bb9245bba7fc877ad2f2a4464c + 9ddc9173d7858ddb40b2fc0cdc73b529c390ba47 windows diff --git a/src/Notepads.DesktopExtension/appcenter.cpp b/src/Notepads.DesktopExtension/appcenter.cpp index a0c624414..0e6fdad12 100644 --- a/src/Notepads.DesktopExtension/appcenter.cpp +++ b/src/Notepads.DesktopExtension/appcenter.cpp @@ -18,7 +18,7 @@ using namespace Windows::Storage; using namespace Windows::System; using namespace Windows::System::Profile; -void AppCenter::start() +VOID AppCenter::start() { if (!AppCenterSecret) return; @@ -30,7 +30,7 @@ void AppCenter::start() headerList = curl_slist_append(headerList, format("install-id: {}", to_string(installId)).c_str()); } -void AppCenter::trackError(bool isFatal, DWORD errorCode, const string& message, const stacktrace& stackTrace) +VOID AppCenter::trackError(bool isFatal, DWORD errorCode, const string& message, const stacktrace& stackTrace) { if (!headerList) return; @@ -111,7 +111,7 @@ void AppCenter::trackError(bool isFatal, DWORD errorCode, const string& message, curl_easy_cleanup(curl); } -void AppCenter::trackEvent(const string& name, const vector>& properties, const string& sid) +VOID AppCenter::trackEvent(const string& name, const vector>& properties, const string& sid) { if (!headerList) return; diff --git a/src/Notepads.DesktopExtension/appcenter.h b/src/Notepads.DesktopExtension/appcenter.h index c5795d2f8..fc8a076f5 100644 --- a/src/Notepads.DesktopExtension/appcenter.h +++ b/src/Notepads.DesktopExtension/appcenter.h @@ -18,7 +18,7 @@ namespace AppCenter static struct curl_slist* headerList = NULL; } - void start(); - void trackError(bool isFatal, DWORD errorCode, const string& message, const stacktrace& stackTrace); - void trackEvent(const string& name, const vector>& properties, const string& sid = ""); + VOID start(); + VOID trackError(bool isFatal, DWORD errorCode, const string& message, const stacktrace& stackTrace); + VOID trackEvent(const string& name, const vector>& properties, const string& sid = ""); } \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/device.h b/src/Notepads.DesktopExtension/device.h index fcbb654cf..1573f65d4 100644 --- a/src/Notepads.DesktopExtension/device.h +++ b/src/Notepads.DesktopExtension/device.h @@ -83,7 +83,7 @@ namespace AppCenter } template - void Serialize(Writer& writer) const + VOID Serialize(Writer& writer) const { writer.StartObject(); diff --git a/src/Notepads.DesktopExtension/elevated.cpp b/src/Notepads.DesktopExtension/elevated.cpp index 50e40c819..eefe7c60b 100644 --- a/src/Notepads.DesktopExtension/elevated.cpp +++ b/src/Notepads.DesktopExtension/elevated.cpp @@ -9,7 +9,7 @@ using namespace Windows::ApplicationModel; using namespace Windows::ApplicationModel::DataTransfer; constexpr INT PIPE_READ_BUFFER = 2 * MAX_PATH + 10; -constexpr LPCTSTR pipeNameFormat = L"\\\\.\\pipe\\Sessions\\{}\\AppContainerNamedObjects\\{}\\{}\\{}"; +constexpr LPCTSTR pipeNameFormat = L"\\\\.\\pipe\\Sessions\\{}\\AppContainerNamedObjects\\{}\\{}"; constexpr LPCTSTR namedObjectFormat = L"AppContainerNamedObjects\\{}\\{}"; extern DWORD sessionId; @@ -59,7 +59,6 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) INT dataArrayLength = stoi(dataArrayLengthStr); wstring memoryMapName = format(namedObjectFormat, packageSid, memoryMapId); - HANDLE hMemory = OpenFileMapping(FILE_MAP_READ, FALSE, memoryMapName.c_str()); if (hMemory) { @@ -85,7 +84,7 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) CloseHandle(hFile); } - CloseHandle(mapView); + UnmapViewOfFile(mapView); } CloseHandle(hMemory); @@ -208,13 +207,14 @@ DWORD WINAPI renameFileFromPipeData(LPVOID /* param */) return 0; } -void initializeAdminService() +VOID initializeAdminService() { adminWriteEvent = OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, format(namedObjectFormat, packageSid, AdminWriteEventNameStr).c_str()); adminRenameEvent = OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, format(namedObjectFormat, packageSid, AdminRenameEventNameStr).c_str()); - writePipeName = format(pipeNameFormat, sessionId, packageSid, Package::Current().Id().FamilyName(), AdminWritePipeConnectionNameStr); - renamePipeName = format(pipeNameFormat, sessionId, packageSid, Package::Current().Id().FamilyName(), AdminRenamePipeConnectionNameStr); + auto packageFamilyName = Package::Current().Id().FamilyName(); + writePipeName = format(pipeNameFormat, sessionId, packageSid, AdminWritePipeConnectionNameStr); + renamePipeName = format(pipeNameFormat, sessionId, packageSid, AdminRenamePipeConnectionNameStr); printDebugMessage(L"Successfully started Adminstrator Extension."); printDebugMessage(L"Waiting on uwp app to send data."); diff --git a/src/Notepads.DesktopExtension/exception.h b/src/Notepads.DesktopExtension/exception.h index 6655df05a..aff0f4c0e 100644 --- a/src/Notepads.DesktopExtension/exception.h +++ b/src/Notepads.DesktopExtension/exception.h @@ -25,7 +25,7 @@ namespace AppCenter } template - void Serialize(Writer& writer) const + VOID Serialize(Writer& writer) const { if (_lineNumber <= 0 && _fileName.empty()) return; @@ -77,7 +77,7 @@ namespace AppCenter } template - void Serialize(Writer& writer) const + VOID Serialize(Writer& writer) const { writer.StartObject(); diff --git a/src/Notepads.DesktopExtension/extension.cpp b/src/Notepads.DesktopExtension/extension.cpp index c6f75e91e..9351262e4 100644 --- a/src/Notepads.DesktopExtension/extension.cpp +++ b/src/Notepads.DesktopExtension/extension.cpp @@ -68,7 +68,7 @@ fire_and_forget launchElevatedProcess() AppCenter::trackEvent("OnAdminstratorPrivilageRequested", properties); } -void onConnectionServiceRequestRecieved(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) +VOID onConnectionServiceRequestRecieved(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { // Get a deferral because we use an awaitable API below to respond to the message // and we don't want this call to get canceled while we are waiting. @@ -87,7 +87,7 @@ void onConnectionServiceRequestRecieved(AppServiceConnection sender, AppServiceR messageDeferral.Complete(); } -void onConnectionServiceClosed(AppServiceConnection sender, AppServiceClosedEventArgs args) +VOID onConnectionServiceClosed(AppServiceConnection sender, AppServiceClosedEventArgs args) { exitApp(); } diff --git a/src/Notepads.DesktopExtension/log.h b/src/Notepads.DesktopExtension/log.h index e1497cd25..aed13cd47 100644 --- a/src/Notepads.DesktopExtension/log.h +++ b/src/Notepads.DesktopExtension/log.h @@ -98,7 +98,7 @@ namespace AppCenter } template - void Serialize(Writer& writer) const + VOID Serialize(Writer& writer) const { writer.StartObject(); @@ -183,7 +183,7 @@ namespace AppCenter Exception* _exception = NULL; vector> _properties; - void InitializeLog() + VOID InitializeLog() { switch (_type) { diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index b03a7fb14..7bd1ab1ea 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -30,24 +30,26 @@ INT releaseResources() return 0; } -void exitApp() +VOID exitApp() { exit(0); } -void onUnhandledException() +VOID onUnhandledException() { logLastError(true).get(); + Sleep(5000); exitApp(); } -void onUnexpectedException() +VOID onUnexpectedException() { logLastError(false).get(); + Sleep(5000); exitApp(); } -void setExceptionHandling() +VOID setExceptionHandling() { set_terminate(onUnhandledException); set_unexpected(onUnexpectedException); @@ -143,6 +145,11 @@ INT main() if (isElevetedProcessLaunchRequested()) launchElevatedProcess(); } + /*INT desiredVal = 0; + HANDLE hMemory = OpenFileMapping(FILE_MAP_READ, FALSE, format(L"AppContainerNamedObjects\\{}\\{}", packageSid, DesktopExtensionLifetimeObjNameStr).c_str()); + LPVOID mapView = MapViewOfFile(hMemory, FILE_MAP_READ, 0, 0, 4); + volatile VOID* address = static_cast(mapView); + if (WaitOnAddress(mapView, &desiredVal, 4, INFINITE)) cout << "wait completed" << endl;*/ wstring pipeName = format(L"\\\\.\\pipe\\Sessions\\{}\\AppContainerNamedObjects\\{}\\{}", sessionId, packageSid, DesktopExtensionLifetimeObjNameStr); while (WaitNamedPipe(pipeName.c_str(), 2000) || GetLastError() == ERROR_SEM_TIMEOUT) diff --git a/src/Notepads.DesktopExtension/pch.cpp b/src/Notepads.DesktopExtension/pch.cpp index 5f2f19818..849a1cb4e 100644 --- a/src/Notepads.DesktopExtension/pch.cpp +++ b/src/Notepads.DesktopExtension/pch.cpp @@ -16,7 +16,7 @@ constexpr INT MAX_DATETIME_STR = 100; StorageFile logFile = NULL; -void printDebugMessage([[maybe_unused]] LPCTSTR message, [[maybe_unused]] DWORD sleepTime) { +VOID printDebugMessage([[maybe_unused]] LPCTSTR message, [[maybe_unused]] DWORD sleepTime) { #ifdef _DEBUG wcout << message << endl; Sleep(sleepTime); diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h index 2d3ca93ed..688c85820 100644 --- a/src/Notepads.DesktopExtension/pch.h +++ b/src/Notepads.DesktopExtension/pch.h @@ -35,10 +35,10 @@ constexpr LPCTSTR CreateElevetedExtensionCommandStr = L"CreateElevetedExtension" ///////////////////////////////////////////////////////////////////////////////////////////// bool isElevatedProcess(); -void setExceptionHandling(); -void exitApp(); +VOID setExceptionHandling(); +VOID exitApp(); -void printDebugMessage([[maybe_unused]] LPCTSTR message, [[maybe_unused]] DWORD sleepTime = 0); +VOID printDebugMessage([[maybe_unused]] LPCTSTR message, [[maybe_unused]] DWORD sleepTime = 0); std::string getTimeStamp(); std::string getTimeStamp(const CHAR* format); std::string to_string(winrt::Windows::System::ProcessorArchitecture arch); @@ -47,7 +47,7 @@ std::string base64_encode(const std::string& in); winrt::fire_and_forget initializeInteropService(); winrt::fire_and_forget launchElevatedProcess(); -void initializeAdminService(); +VOID initializeAdminService(); winrt::Windows::Foundation::IInspectable readSettingsKey(winrt::hstring key); std::pair getLastErrorDetails(); diff --git a/src/Notepads.DesktopExtension/vcpkg.json b/src/Notepads.DesktopExtension/vcpkg.json index 79a7ec7b9..e2933580f 100644 --- a/src/Notepads.DesktopExtension/vcpkg.json +++ b/src/Notepads.DesktopExtension/vcpkg.json @@ -20,5 +20,5 @@ "$version-date": "2020-09-14" } ], - "$x-default-baseline": "50ea8c0ab7aca3bb9245bba7fc877ad2f2a4464c" + "$x-default-baseline": "9ddc9173d7858ddb40b2fc0cdc73b529c390ba47" } \ No newline at end of file diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index 266c4f6e1..69a6b7fe3 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -46,6 +46,7 @@ public static class DesktopExtensionService public static AppServiceConnection InteropServiceConnection = null; public static NamedPipeServerStream ExtensionLifetimeObject = null; + //public static MemoryMappedFile ExtensionLifetimeObject = null; private static readonly ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView(); private static EventWaitHandle _adminWriteEvent = null; @@ -61,6 +62,19 @@ public static async Task Initialize() $"Local\\{SettingsKey.DesktopExtensionLifetimeObjNameStr}", PipeDirection.In, NamedPipeServerStream.MaxAllowedServerInstances); + /*try + { + ExtensionLifetimeObject = MemoryMappedFile.OpenExisting(SettingsKey.DesktopExtensionLifetimeObjNameStr, MemoryMappedFileRights.ReadWrite); + } + catch (FileNotFoundException) + { + ExtensionLifetimeObject = MemoryMappedFile.CreateOrOpen(SettingsKey.DesktopExtensionLifetimeObjNameStr, 4, MemoryMappedFileAccess.ReadWrite); + using (var writer = new BinaryWriter(ExtensionLifetimeObject.CreateViewStream())) + { + writer.Write(1); + writer.Flush(); + } + }*/ } if (_adminWriteEvent == null) @@ -142,7 +156,7 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) if (InteropServiceConnection == null && !(await Initialize())) return; using (var adminConnectionPipeStream = new NamedPipeServerStream( - $"Local\\{Package.Current.Id.FamilyName}\\{SettingsKey.AdminWritePipeConnectionNameStr}", + $"Local\\{SettingsKey.AdminWritePipeConnectionNameStr}", PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, @@ -204,7 +218,7 @@ public static async Task RenameFileAsAdmin(StorageFile file, string var token = SharedStorageAccessManager.AddFile(file); using (var adminConnectionPipeStream = new NamedPipeServerStream( - $"Local\\{Package.Current.Id.FamilyName}\\{SettingsKey.AdminRenamePipeConnectionNameStr}", + $"Local\\{SettingsKey.AdminRenamePipeConnectionNameStr}", PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs index 2e7e68c75..645af1b5b 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs @@ -472,14 +472,6 @@ private static void UpdateApplicationTitle(ITextEditor activeTextEditor) } } - private async void HideSettingsPane_OnSettingsChanged(object sender, bool hideArgs) - { - await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () => - { - RootSplitView.IsPaneOpen = !hideArgs; - }); - } - #endregion #region NotepadsCore Events From 30d9b0a6a3f697bd234e254228fe25f038ea5989 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 9 Jan 2021 16:44:01 +0530 Subject: [PATCH 136/181] Modified script execution policy. --- src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index e80421ff1..2f6fb9f8d 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -98,7 +98,7 @@ stdcpplatest - powershell -ExecutionPolicy Bypass $(ProjectDir)build.ps1 -project_dir $(ProjectDir) + powershell -ExecutionPolicy Unrestricted $(ProjectDir)build.ps1 -project_dir $(ProjectDir) From 567d99b5baa0e33a455244b052dee434984a9b7e Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 9 Jan 2021 23:19:11 +0530 Subject: [PATCH 137/181] Modified build tasks. --- .github/workflows/Build.yml | 5 +++++ azure-pipelines.yml | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index b51181a5e..54dd12abc 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -24,6 +24,11 @@ jobs: - name: Setup MSBuild uses: microsoft/setup-msbuild@v1 + - name: Restore the application + run: msbuild $env:Solution_Name /t:Restore /p:Configuration=$env:Configuration + env: + Configuration: ${{ matrix.configuration }} + - name: Setup NuGet uses: NuGet/setup-nuget@v1.0.5 diff --git a/azure-pipelines.yml b/azure-pipelines.yml index dc86a0b06..46771142f 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -19,9 +19,9 @@ steps: inputs: restoreSolution: '$(solution)' -- task: MSBuild@1 +- task: VSBuild@1 inputs: - platform: 'x86' + platform: 'x64' solution: '**/*.wapproj' configuration: '$(buildConfiguration)' msbuildArgs: '/t:build;_GenerateAppxPackage From 5d7573ba88f89ddfa28459a2d7154f5c2cd4127e Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 15 Jan 2021 18:51:29 +0530 Subject: [PATCH 138/181] Corrected some spelling mistakes. --- src/Notepads/Package.appxmanifest | 18 ------------------ src/Notepads/Strings/en-US/Resources.resw | 2 +- 2 files changed, 1 insertion(+), 19 deletions(-) diff --git a/src/Notepads/Package.appxmanifest b/src/Notepads/Package.appxmanifest index b9296a118..72d4b3055 100644 --- a/src/Notepads/Package.appxmanifest +++ b/src/Notepads/Package.appxmanifest @@ -1180,24 +1180,6 @@ - diff --git a/src/Notepads/Strings/en-US/Resources.resw b/src/Notepads/Strings/en-US/Resources.resw index 7ba5acad3..2da3201fb 100644 --- a/src/Notepads/Strings/en-US/Resources.resw +++ b/src/Notepads/Strings/en-US/Resources.resw @@ -725,7 +725,7 @@ Notepads needs Adminstrative Privilage to rename file "{0}" LaunchElevatedExtensionDialog: Rename Failed "Content" display text. - + Rename Failed LaunchElevatedExtensionDialog: Rename Failed "Title" display text. From babac171f27fca65f1aea0c23dcce7934b1deb9f Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 16 Jan 2021 13:55:00 +0530 Subject: [PATCH 139/181] Better app analytics. --- .../PropertySheet.props | 2 +- src/Notepads.DesktopExtension/appcenter.cpp | 35 ++++++---------- src/Notepads.DesktopExtension/exception.h | 7 ++-- src/Notepads.DesktopExtension/log.h | 42 +++++++++++++------ src/Notepads.DesktopExtension/vcpkg.json | 6 +-- .../Services/DesktopExtensionService.cs | 38 +++++++++-------- 6 files changed, 68 insertions(+), 62 deletions(-) diff --git a/src/Notepads.DesktopExtension/PropertySheet.props b/src/Notepads.DesktopExtension/PropertySheet.props index a8d8189aa..ca8277c7a 100644 --- a/src/Notepads.DesktopExtension/PropertySheet.props +++ b/src/Notepads.DesktopExtension/PropertySheet.props @@ -14,7 +14,7 @@ https://github.com/microsoft/vcpkg - a14a6bcb27287e3ec138dba1b948a0cdbc337a3a + b60f003ccf5fe8613d029f49f835c8929a66eb61 windows diff --git a/src/Notepads.DesktopExtension/appcenter.cpp b/src/Notepads.DesktopExtension/appcenter.cpp index 0e6fdad12..0603b2801 100644 --- a/src/Notepads.DesktopExtension/appcenter.cpp +++ b/src/Notepads.DesktopExtension/appcenter.cpp @@ -12,11 +12,7 @@ using namespace std; using namespace winrt; using namespace AppCenter; using namespace Windows::ApplicationModel; -using namespace Windows::Foundation; -using namespace Windows::Security::ExchangeActiveSyncProvisioning; -using namespace Windows::Storage; using namespace Windows::System; -using namespace Windows::System::Profile; VOID AppCenter::start() { @@ -34,15 +30,6 @@ VOID AppCenter::trackError(bool isFatal, DWORD errorCode, const string& message, { if (!headerList) return; - string crashReportId = to_string(to_hstring(GuidHelper::CreateNewGuid())); - crashReportId.erase(0, crashReportId.find_first_not_of('{')).erase(crashReportId.find_last_not_of('}') + 1); - string crashReportSid = to_string(to_hstring(GuidHelper::CreateNewGuid())); - crashReportSid.erase(0, crashReportSid.find_first_not_of('{')).erase(crashReportSid.find_last_not_of('}') + 1); - string errorAttachmentId = to_string(to_hstring(GuidHelper::CreateNewGuid())); - errorAttachmentId.erase(0, errorAttachmentId.find_first_not_of('{')).erase(errorAttachmentId.find_last_not_of('}') + 1); - string eventReportId = to_string(to_hstring(GuidHelper::CreateNewGuid())); - eventReportId.erase(0, eventReportId.find_first_not_of('{')).erase(eventReportId.find_last_not_of('}') + 1); - TCHAR locale[LOCALE_NAME_MAX_LENGTH + 1]; LCIDToLocaleName(GetThreadLocale(), locale, LOCALE_NAME_MAX_LENGTH, 0); TCHAR localeDisplayName[LOCALE_NAME_MAX_LENGTH + 1]; @@ -51,6 +38,9 @@ VOID AppCenter::trackError(bool isFatal, DWORD errorCode, const string& message, string isElevated = isElevatedProcess() ? "True" : "False"; string eventType = isFatal ? "OnWin32UnhandledException" : "OnWin32UnexpectedException"; + string attachmentData = base64_encode(format("Exception: Win32Exception code no. {}\nMessage: {}\nIsDesktopExtension: True, IsElevated: {}", + errorCode, message, isElevated)); + vector> properties { pair("Exception", format("Win32Exception: Exception of code no. {} was thrown.", errorCode)), @@ -63,16 +53,18 @@ VOID AppCenter::trackError(bool isFatal, DWORD errorCode, const string& message, pair("IsDesktopExtension", "True"), pair("IsElevated", isElevated) }; - vector errorReportSet { - Log(LogType::managedError, crashReportId, crashReportSid, isFatal, new Exception(message, stackTrace), properties), - Log(LogType::errorAttachment, errorAttachmentId, crashReportId, base64_encode( - format("Exception: Win32Exception code no. {}, Message: {}, IsDesktopExtension: True, IsElevated: {}", - errorCode, message, isElevated))), - Log(LogType::event, eventReportId, crashReportSid, eventType, properties) + Log(LogType::managedError, isFatal, new Exception(message, stackTrace)), + Log(LogType::handledError, isFatal, new Exception(message), properties) }; + errorReportSet.insert(errorReportSet.end(), + { + Log(LogType::errorAttachment, errorReportSet[0].Id(), attachmentData), + Log(LogType::errorAttachment, errorReportSet[1].Id(), attachmentData), + Log(LogType::event, errorReportSet[0].Sid(), eventType, properties) + }); StringBuffer errorReport; #ifdef _DEBUG @@ -115,9 +107,6 @@ VOID AppCenter::trackEvent(const string& name, const vector writer(eventReport); @@ -128,7 +117,7 @@ VOID AppCenter::trackEvent(const string& name, const vector>& properties) : - _type(type), _id(id), _sid(sid), _fatal(isFatal), _exception(exception), _properties(properties) + #pragma endregion + + #pragma region Constructors for handled error report + + Log(LogType type, bool isFatal, Exception* exception, const vector>& properties) : + _type(type), _fatal(isFatal), _exception(exception), _properties(properties) { InitializeLog(); } @@ -43,8 +49,8 @@ namespace AppCenter #pragma region Constructor for error attachment - Log(LogType type, const string& id, const string& errorId, const string& data) : - _type(type), _id(id), _errorId(errorId), _data(data) + Log(LogType type, const string& errorId, const string& data) : + _type(type), _errorId(errorId), _data(data) { InitializeLog(); } @@ -53,8 +59,8 @@ namespace AppCenter #pragma region Constructor for event report - Log(LogType type, const string& id, const string& sid, const string& name, const vector>& properties) : - _type(type), _id(id), _sid(sid), _name(name), _properties(properties) + Log(LogType type, const string& sid, const string& name, const vector>& properties) : + _type(type), _sid(sid), _name(name), _properties(properties) { InitializeLog(); } @@ -62,12 +68,12 @@ namespace AppCenter #pragma endregion Log(const Log& log) : - _type(log._type), _name(log._name), _timestamp(log._timestamp), _processId(log._processId), _id(log._id), _sid(log._sid), _fatal(log._fatal), - _processName(log._processName), _errorThreadId(log._errorThreadId), _data(log._data), _errorId(log._errorId), + _type(log._type), _contentType(log._contentType), _name(log._name), _timestamp(log._timestamp), + _processId(log._processId), _id(log._id), _sid(log._sid), _fatal(log._fatal), _processName(log._processName), + _errorThreadId(log._errorThreadId), _data(log._data), _errorId(log._errorId), _exception(NULL), _properties(log._properties) { _exception = (log._exception == 0) ? 0 : new Exception(*log._exception); - InitializeLog(); } ~Log() @@ -120,6 +126,7 @@ namespace AppCenter switch (_type) { case LogType::managedError: + case LogType::handledError: writer.String("processId"); writer.Uint(_processId); writer.String("fatal"); @@ -167,6 +174,9 @@ namespace AppCenter writer.EndObject(); } + inline const string& Id() { return _id; } + inline const string& Sid() { return _sid; } + private: LogType _type; string _contentType = "text/plain"; @@ -185,9 +195,15 @@ namespace AppCenter VOID InitializeLog() { + _id = to_string(to_hstring(GuidHelper::CreateNewGuid())); + _id.erase(0, _id.find_first_not_of('{')).erase(_id.find_last_not_of('}') + 1); + switch (_type) { case LogType::managedError: + case LogType::handledError: + _sid = to_string(to_hstring(GuidHelper::CreateNewGuid())); + _sid.erase(0, _sid.find_first_not_of('{')).erase(_sid.find_last_not_of('}') + 1); _processId = GetCurrentProcessId(); _errorThreadId = GetCurrentThreadId(); break; diff --git a/src/Notepads.DesktopExtension/vcpkg.json b/src/Notepads.DesktopExtension/vcpkg.json index d4336cecf..8db28aa6e 100644 --- a/src/Notepads.DesktopExtension/vcpkg.json +++ b/src/Notepads.DesktopExtension/vcpkg.json @@ -1,10 +1,11 @@ { "name": "notepads-desktopextension", "version-string": "1.0.0.0", + "$builtin-baseline": "b60f003ccf5fe8613d029f49f835c8929a66eb61", "dependencies": [ { "name": "boost-stacktrace", - "$version": "1.74.0" + "$version": "1.75.0" }, { "name": "curl", @@ -19,6 +20,5 @@ "name": "rapidjson", "$version-date": "2020-09-14" } - ], - "$x-default-baseline": "a14a6bcb27287e3ec138dba1b948a0cdbc337a3a" + ] } \ No newline at end of file diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index 6e3c2beee..5ac50e326 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -125,6 +125,7 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) // If the connection fails, desktop extension is not launched with elevated privilages. // In that case, prompt user to launch desktop extension with elevated privilages. _adminWriteEvent.Reset(); + adminConnectionPipeStream?.Dispose(); throw new AdminstratorAccessException(); } @@ -146,13 +147,11 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) await pipeWriter.FlushAsync(); // Wait for desktop extension to send response. - if ("Success".Equals(await pipeReader.ReadLineAsync())) - { - return; - } - else + if (!"Success".Equals(await pipeReader.ReadLineAsync())) { // Promt user to "Save As" if extension failed to save data. + mmf?.Dispose(); + adminConnectionPipeStream?.Dispose(); throw new UnauthorizedAccessException(); } } @@ -185,6 +184,8 @@ public static async Task RenameFileAsAdmin(StorageFile file, string // If the connection fails, desktop extension is not launched with elevated privilages. // In that case, prompt user to launch desktop extension with elevated privilages. _adminRenameEvent.Reset(); + file = null; + var launchElevatedExtensionDialog = new LaunchElevatedExtensionDialog( AdminOperationType.Rename, file.Path, @@ -192,23 +193,24 @@ public static async Task RenameFileAsAdmin(StorageFile file, string null); var dialogResult = await DialogManager.OpenDialogAsync(launchElevatedExtensionDialog, awaitPreviousDialog: false); - - return null; } + else + { + var pipeReader = new StreamReader(adminConnectionPipeStream, new System.Text.UnicodeEncoding(!BitConverter.IsLittleEndian, false)); + var pipeWriter = new StreamWriter(adminConnectionPipeStream, new System.Text.UnicodeEncoding(!BitConverter.IsLittleEndian, false)); - var pipeReader = new StreamReader(adminConnectionPipeStream, new System.Text.UnicodeEncoding(!BitConverter.IsLittleEndian, false)); - var pipeWriter = new StreamWriter(adminConnectionPipeStream, new System.Text.UnicodeEncoding(!BitConverter.IsLittleEndian, false)); - - var token = SharedStorageAccessManager.AddFile(file); - await pipeWriter.WriteAsync($"{token}|{newName}"); - await pipeWriter.FlushAsync(); + var token = SharedStorageAccessManager.AddFile(file); + await pipeWriter.WriteAsync($"{token}|{newName}"); + await pipeWriter.FlushAsync(); - // Wait for desktop extension to send response. - token = await pipeReader.ReadLineAsync(); - file = await SharedStorageAccessManager.RedeemTokenForFileAsync(token); - SharedStorageAccessManager.RemoveFile(token); - return file; + // Wait for desktop extension to send response. + token = await pipeReader.ReadLineAsync(); + file = await SharedStorageAccessManager.RedeemTokenForFileAsync(token); + SharedStorageAccessManager.RemoveFile(token); + } } + + return file; } } } From f26c7ddd65b9bbf998686f5dc4a8eacf8d86da8b Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 16 Jan 2021 14:36:12 +0530 Subject: [PATCH 140/181] code refactor. --- src/Notepads.DesktopExtension/appcenter.cpp | 22 +++++++++++++++++---- src/Notepads.DesktopExtension/appcenter.h | 1 + src/Notepads.DesktopExtension/log.h | 4 ++-- src/Notepads.DesktopExtension/main.cpp | 6 +++--- 4 files changed, 24 insertions(+), 9 deletions(-) diff --git a/src/Notepads.DesktopExtension/appcenter.cpp b/src/Notepads.DesktopExtension/appcenter.cpp index 0603b2801..afba0a534 100644 --- a/src/Notepads.DesktopExtension/appcenter.cpp +++ b/src/Notepads.DesktopExtension/appcenter.cpp @@ -21,9 +21,17 @@ VOID AppCenter::start() hstring installId = unbox_value_or(readSettingsKey(AppCenterInstallIdStr), L""); if (installId.empty()) return; - headerList = curl_slist_append(headerList, "Content-Type: application/json"); - headerList = curl_slist_append(headerList, format("app-secret: {}", to_string(AppCenterSecret)).c_str()); - headerList = curl_slist_append(headerList, format("install-id: {}", to_string(installId)).c_str()); + if (!headerList) + { + headerList = curl_slist_append(headerList, "Content-Type: application/json"); + headerList = curl_slist_append(headerList, format("app-secret: {}", to_string(AppCenterSecret)).c_str()); + headerList = curl_slist_append(headerList, format("install-id: {}", to_string(installId)).c_str()); + } + + if (!deviceInfo) + { + deviceInfo = new Device(); + } } VOID AppCenter::trackError(bool isFatal, DWORD errorCode, const string& message, const stacktrace& stackTrace) @@ -49,7 +57,7 @@ VOID AppCenter::trackError(bool isFatal, DWORD errorCode, const string& message, pair("AvailableMemory", to_string((FLOAT)MemoryManager::AppMemoryUsageLimit() / 1024 / 1024)), pair("FirstUseTimeUTC", getTimeStamp("%m/%d/%Y %T")), pair("OSArchitecture", to_string(Package::Current().Id().Architecture())), - pair("OSVersion", deviceInfo.getOsVersion()), + pair("OSVersion", deviceInfo->getOsVersion()), pair("IsDesktopExtension", "True"), pair("IsElevated", isElevated) }; @@ -139,4 +147,10 @@ VOID AppCenter::trackEvent(const string& name, const vector>& properties, const string& sid = ""); + VOID exit(); } \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/log.h b/src/Notepads.DesktopExtension/log.h index bd043962a..478b918cd 100644 --- a/src/Notepads.DesktopExtension/log.h +++ b/src/Notepads.DesktopExtension/log.h @@ -21,7 +21,7 @@ namespace AppCenter { static const string logTypes[] = { "managedError", "handledError", "errorAttachment", "event" }; static string launchTimeStamp = getTimeStamp(); - static Device deviceInfo = Device(); + static Device* deviceInfo = NULL; } class Log @@ -156,7 +156,7 @@ namespace AppCenter // Write device specific data writer.String("device"); - deviceInfo.Serialize(writer); + deviceInfo->Serialize(writer); // Write custom properties if available if (!_properties.empty()) diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index 463cfc51e..8605246aa 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -25,6 +25,8 @@ INT releaseResources() { CloseHandle(adminWriteEvent); CloseHandle(adminRenameEvent); + AppCenter::exit(); + uninit_apartment(); return 0; } @@ -36,14 +38,12 @@ VOID exitApp() VOID onUnhandledException() { logLastError(true).get(); - Sleep(5000); exitApp(); } VOID onUnexpectedException() { logLastError(false).get(); - Sleep(5000); exitApp(); } @@ -183,5 +183,5 @@ INT main() Sleep(1000); goto LifeTimeCheck; } - exit(0); + return 0; } \ No newline at end of file From b9deb31b66459e42df5cf264c00c643b1827c7a9 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Mon, 18 Jan 2021 11:40:57 +0530 Subject: [PATCH 141/181] Implemented unblocking file modified by UWP. --- .../Notepads.DesktopExtension.vcxproj | 1 + .../Notepads.DesktopExtension.vcxproj.filters | 3 + .../PropertySheet.props | 2 +- src/Notepads.DesktopExtension/appcenter.cpp | 8 +- src/Notepads.DesktopExtension/elevated.cpp | 45 +++-- src/Notepads.DesktopExtension/extension.cpp | 159 ++++++++++++++++++ src/Notepads.DesktopExtension/main.cpp | 94 +---------- src/Notepads.DesktopExtension/pch.cpp | 8 +- src/Notepads.DesktopExtension/pch.h | 42 +++-- src/Notepads.DesktopExtension/vcpkg.json | 2 +- .../Dialog/LaunchElevatedExtensionDialog.cs | 20 +-- src/Notepads/Package.appxmanifest | 7 +- .../Services/DesktopExtensionService.cs | 147 +++++++++++----- src/Notepads/Settings/SettingsKey.cs | 15 +- src/Notepads/Strings/en-US/Resources.resw | 38 ++--- src/Notepads/Utilities/FileSystemUtility.cs | 2 + .../Views/MainPage/NotepadsMainPage.IO.cs | 8 +- .../Views/MainPage/NotepadsMainPage.xaml.cs | 8 +- 18 files changed, 402 insertions(+), 207 deletions(-) create mode 100644 src/Notepads.DesktopExtension/extension.cpp diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index 2f6fb9f8d..a0e1669f6 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -141,6 +141,7 @@ + Create diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters index e840983df..6114fce40 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters @@ -30,6 +30,9 @@ AppCenter + + Source Files + diff --git a/src/Notepads.DesktopExtension/PropertySheet.props b/src/Notepads.DesktopExtension/PropertySheet.props index ca8277c7a..be03aabb5 100644 --- a/src/Notepads.DesktopExtension/PropertySheet.props +++ b/src/Notepads.DesktopExtension/PropertySheet.props @@ -14,7 +14,7 @@ https://github.com/microsoft/vcpkg - b60f003ccf5fe8613d029f49f835c8929a66eb61 + 0c94afc7883faee9f188c36232d628ffa94cf27f windows diff --git a/src/Notepads.DesktopExtension/appcenter.cpp b/src/Notepads.DesktopExtension/appcenter.cpp index afba0a534..f7bae8c7f 100644 --- a/src/Notepads.DesktopExtension/appcenter.cpp +++ b/src/Notepads.DesktopExtension/appcenter.cpp @@ -12,11 +12,17 @@ using namespace std; using namespace winrt; using namespace AppCenter; using namespace Windows::ApplicationModel; +using namespace Windows::Storage; using namespace Windows::System; +IInspectable readSettingsKey(hstring key) +{ + return ApplicationData::Current().LocalSettings().Values().TryLookup(key); +} + VOID AppCenter::start() { - if (!AppCenterSecret) return; + if (!AppCenterSecret || wcslen(AppCenterSecret) == 0) return; hstring installId = unbox_value_or(readSettingsKey(AppCenterInstallIdStr), L""); if (installId.empty()) return; diff --git a/src/Notepads.DesktopExtension/elevated.cpp b/src/Notepads.DesktopExtension/elevated.cpp index eefe7c60b..822cb75c9 100644 --- a/src/Notepads.DesktopExtension/elevated.cpp +++ b/src/Notepads.DesktopExtension/elevated.cpp @@ -8,15 +8,11 @@ using namespace winrt; using namespace Windows::ApplicationModel; using namespace Windows::ApplicationModel::DataTransfer; -constexpr INT PIPE_READ_BUFFER = 2 * MAX_PATH + 10; -constexpr LPCTSTR pipeNameFormat = L"\\\\.\\pipe\\Sessions\\{}\\AppContainerNamedObjects\\{}\\{}"; -constexpr LPCTSTR namedObjectFormat = L"AppContainerNamedObjects\\{}\\{}"; - extern DWORD sessionId; extern hstring packageSid; -HANDLE adminWriteEvent = NULL; -HANDLE adminRenameEvent = NULL; +HANDLE elevatedWriteEvent = NULL; +HANDLE elevatedRenameEvent = NULL; wstring writePipeName; wstring renamePipeName; @@ -29,7 +25,9 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) LPCTSTR result = L"Failed"; HANDLE hPipe = INVALID_HANDLE_VALUE; - if (!WaitForSingleObject(adminWriteEvent, INFINITE) && ResetEvent(adminWriteEvent) && WaitNamedPipe(writePipeName.c_str(), NMPWAIT_WAIT_FOREVER)) + if (!WaitForSingleObject(elevatedWriteEvent, INFINITE) && + ResetEvent(elevatedWriteEvent) && + WaitNamedPipe(writePipeName.c_str(), NMPWAIT_WAIT_FOREVER)) { hPipe = CreateFile(writePipeName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); } @@ -58,7 +56,7 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) getline(pipeData, dataArrayLengthStr); INT dataArrayLength = stoi(dataArrayLengthStr); - wstring memoryMapName = format(namedObjectFormat, packageSid, memoryMapId); + wstring memoryMapName = format(NAMED_OBJECT_FORMAT, packageSid, memoryMapId); HANDLE hMemory = OpenFileMapping(FILE_MAP_READ, FALSE, memoryMapName.c_str()); if (hMemory) { @@ -136,7 +134,9 @@ DWORD WINAPI renameFileFromPipeData(LPVOID /* param */) LPCTSTR result = L"Failed"; HANDLE hPipe = INVALID_HANDLE_VALUE; - if (!WaitForSingleObject(adminRenameEvent, INFINITE) && ResetEvent(adminRenameEvent) && WaitNamedPipe(renamePipeName.c_str(), NMPWAIT_WAIT_FOREVER)) + if (!WaitForSingleObject(elevatedRenameEvent, INFINITE) && + ResetEvent(elevatedRenameEvent) && + WaitNamedPipe(renamePipeName.c_str(), NMPWAIT_WAIT_FOREVER)) { hPipe = CreateFile(renamePipeName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); } @@ -207,18 +207,31 @@ DWORD WINAPI renameFileFromPipeData(LPVOID /* param */) return 0; } -VOID initializeAdminService() +VOID initializeElevatedService() { - adminWriteEvent = OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, format(namedObjectFormat, packageSid, AdminWriteEventNameStr).c_str()); - adminRenameEvent = OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, format(namedObjectFormat, packageSid, AdminRenameEventNameStr).c_str()); + if (!isFirstInstance(ElevatedMutexName)) return; + + ProcessIdToSessionId(GetCurrentProcessId(), &sessionId); + packageSid = unbox_value_or(readSettingsKey(PackageSidStr), L""); + + elevatedWriteEvent = OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, format(NAMED_OBJECT_FORMAT, packageSid, ElevatedWriteEventNameStr).c_str()); + elevatedRenameEvent = OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, format(NAMED_OBJECT_FORMAT, packageSid, ElevatedRenameEventNameStr).c_str()); - auto packageFamilyName = Package::Current().Id().FamilyName(); - writePipeName = format(pipeNameFormat, sessionId, packageSid, AdminWritePipeConnectionNameStr); - renamePipeName = format(pipeNameFormat, sessionId, packageSid, AdminRenamePipeConnectionNameStr); + writePipeName = format(PIPE_NAME_FORMAT, sessionId, packageSid, ElevatedWritePipeConnectionNameStr); + renamePipeName = format(PIPE_NAME_FORMAT, sessionId, packageSid, ElevatedRenamePipeConnectionNameStr); - printDebugMessage(L"Successfully started Adminstrator Extension."); + printDebugMessage(L"Successfully started Elevated Process."); printDebugMessage(L"Waiting on uwp app to send data."); CreateThread(NULL, 0, saveFileFromPipeData, NULL, 0, NULL); CreateThread(NULL, 0, renameFileFromPipeData, NULL, 0, NULL); + +LifeTimeCheck: + HANDLE lifeTimeObj = OpenMutex(SYNCHRONIZE, FALSE, format(L"AppContainerNamedObjects\\{}\\{}", packageSid, ElevatedProcessLifetimeObjNameStr).c_str()); + if (lifeTimeObj) + { + CloseHandle(lifeTimeObj); + Sleep(1000); + goto LifeTimeCheck; + } } \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/extension.cpp b/src/Notepads.DesktopExtension/extension.cpp new file mode 100644 index 000000000..dd5509e3e --- /dev/null +++ b/src/Notepads.DesktopExtension/extension.cpp @@ -0,0 +1,159 @@ +#include "pch.h" +#include "appcenter.h" + +using namespace fmt; +using namespace std; +using namespace winrt; +using namespace Windows::ApplicationModel; +using namespace Windows::Storage; + +DWORD sessionId; +hstring packageSid; + +wstring extensionUnblockPipeName; + +HANDLE extensionUnblockEvent = NULL; + +DWORD WINAPI unblockFileFromPipeData(LPVOID /* param */) +{ + setExceptionHandling(); + + HANDLE hPipe = INVALID_HANDLE_VALUE; + if (!WaitForSingleObject(extensionUnblockEvent, INFINITE) && + ResetEvent(extensionUnblockEvent) && + WaitNamedPipe(extensionUnblockPipeName.c_str(), NMPWAIT_WAIT_FOREVER)) + { + hPipe = CreateFile(extensionUnblockPipeName.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); + } + + if (hPipe) + { + CreateThread(NULL, 0, unblockFileFromPipeData, NULL, 0, NULL); + + TCHAR readBuffer[PIPE_READ_BUFFER]; + wstringstream pipeData; + DWORD byteRead; + do + { + fill(begin(readBuffer), end(readBuffer), '\0'); + if (ReadFile(hPipe, readBuffer, (PIPE_READ_BUFFER - 1) * sizeof(TCHAR), &byteRead, NULL)) + { + pipeData << readBuffer; + } + } while (byteRead >= (PIPE_READ_BUFFER - 1) * sizeof(TCHAR)); + + wstring filePath(pipeData.str()); + if (DeleteFile(format(L"{}:Zone.Identifier", filePath).c_str())) + { + printDebugMessage(format(L"Successfully unblocked file \"{}\"", filePath).c_str()); + } + else + { + printDebugMessage(format(L"Failed to unblock file \"{}\"", filePath).c_str()); + } + + CloseHandle(hPipe); + printDebugMessage(L"Waiting on uwp app to send data."); + } + else + { + exitApp(); + } + + return 0; +} + +VOID launchElevatedProcess() +{ + TCHAR fileName[MAX_PATH]; + GetModuleFileName(NULL, fileName, MAX_PATH); + + SHELLEXECUTEINFO shExInfo + { + .cbSize = sizeof(shExInfo), + .fMask = SEE_MASK_NOCLOSEPROCESS, + .hwnd = 0, + .lpVerb = L"runas", + .lpFile = fileName, + .lpParameters = L"", + .lpDirectory = 0, + .nShow = SW_SHOW, + .hInstApp = 0 + }; + + vector> properties; + if (ShellExecuteEx(&shExInfo)) + { + ApplicationData::Current().LocalSettings().Values().Insert(LastChangedSettingsAppInstanceIdStr, box_value(L"")); + ApplicationData::Current().LocalSettings().Values().Insert(LastChangedSettingsKeyStr, box_value(LaunchElevetedProcessSuccessStr)); + + printDebugMessage(L"Elevated Process has been launched."); + properties.push_back(pair("Accepted", "True")); + } + else + { + ApplicationData::Current().LocalSettings().Values().Insert(LastChangedSettingsAppInstanceIdStr, box_value(L"")); + ApplicationData::Current().LocalSettings().Values().Insert(LastChangedSettingsKeyStr, box_value(LaunchElevetedProcessFailedStr)); + + printDebugMessage(L"Launching of Elevated Process was cancelled."); + pair ex = getLastErrorDetails(); + properties.insert(properties.end(), + { + pair("Denied", "True"), + pair("Error Code", to_string(ex.first)), + pair("Error Message", to_string(ex.second)) + }); + } + + ApplicationData::Current().SignalDataChanged(); + AppCenter::trackEvent("OnAdminstratorPrivilageRequested", properties); +} + +VOID launchElevatedProcessIfRequested() +{ + LPWSTR* szArglist = NULL; + INT nArgs; + szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs); + if (szArglist) + { + // Assumed first entry is for uwp app + auto aumid = Package::Current().GetAppListEntries().GetAt(0).AppUserModelId(); + wstring praid(aumid); + praid.erase(0, praid.find(L"!") + 1); + if (nArgs > 3 && + wcscmp(szArglist[1], L"/InvokerPRAID:") == 0 && + wcscmp(szArglist[2], praid.c_str()) == 0 && + wcscmp(szArglist[3], L"/admin") == 0) + { + launchElevatedProcess(); + } + } + LocalFree(szArglist); +} + +VOID initializeExtensionService() +{ + launchElevatedProcessIfRequested(); + + if (!isFirstInstance(ExtensionMutexName)) return; + + ProcessIdToSessionId(GetCurrentProcessId(), &sessionId); + packageSid = unbox_value_or(readSettingsKey(PackageSidStr), L""); + + extensionUnblockEvent = OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, format(NAMED_OBJECT_FORMAT, packageSid, ExtensionUnblockEventNameStr).c_str()); + extensionUnblockPipeName = format(PIPE_NAME_FORMAT, sessionId, packageSid, ExtensionUnblockPipeConnectionNameStr); + + printDebugMessage(L"Successfully started Desktop Extension."); + printDebugMessage(L"Waiting on uwp app to send data."); + + CreateThread(NULL, 0, unblockFileFromPipeData, NULL, 0, NULL); + +LifeTimeCheck: + HANDLE lifeTimeObj = OpenMutex(SYNCHRONIZE, FALSE, format(L"AppContainerNamedObjects\\{}\\{}", packageSid, ExtensionProcessLifetimeObjNameStr).c_str()); + if (lifeTimeObj) + { + CloseHandle(lifeTimeObj); + Sleep(1000); + goto LifeTimeCheck; + } +} \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index 8605246aa..ce11e7599 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -1,30 +1,17 @@ #include "pch.h" #include "appcenter.h" -using namespace fmt; -using namespace std; using namespace winrt; -using namespace Windows::Foundation; -using namespace Windows::Storage; -constexpr LPCTSTR DesktopExtensionMutexName = L"DesktopExtensionMutexName"; -constexpr LPCTSTR AdminExtensionMutexName = L"AdminExtensionMutexName"; - -DWORD sessionId; -hstring packageSid = unbox_value_or(readSettingsKey(PackageSidStr), L""); - -extern HANDLE adminWriteEvent; -extern HANDLE adminRenameEvent; - -IInspectable readSettingsKey(hstring key) -{ - return ApplicationData::Current().LocalSettings().Values().TryLookup(key); -} +extern HANDLE extensionUnblockEvent; +extern HANDLE elevatedWriteEvent; +extern HANDLE elevatedRenameEvent; INT releaseResources() { - CloseHandle(adminWriteEvent); - CloseHandle(adminRenameEvent); + CloseHandle(extensionUnblockEvent); + CloseHandle(elevatedWriteEvent); + CloseHandle(elevatedRenameEvent); AppCenter::exit(); uninit_apartment(); return 0; @@ -53,52 +40,6 @@ VOID setExceptionHandling() set_unexpected(onUnexpectedException); } -VOID launchElevatedProcess() -{ - TCHAR fileName[MAX_PATH]; - GetModuleFileName(NULL, fileName, MAX_PATH); - - SHELLEXECUTEINFO shExInfo - { - .cbSize = sizeof(shExInfo), - .fMask = SEE_MASK_NOCLOSEPROCESS, - .hwnd = 0, - .lpVerb = L"runas", - .lpFile = fileName, - .lpParameters = L"", - .lpDirectory = 0, - .nShow = SW_SHOW, - .hInstApp = 0 - }; - - vector> properties; - if (ShellExecuteEx(&shExInfo)) - { - ApplicationData::Current().LocalSettings().Values().Insert(LastChangedSettingsAppInstanceIdStr, box_value(L"")); - ApplicationData::Current().LocalSettings().Values().Insert(LastChangedSettingsKeyStr, box_value(LaunchElevetedProcessSuccessStr)); - - printDebugMessage(L"Adminstrator Extension has been launched."); - properties.push_back(pair("Accepted", "True")); - } - else - { - ApplicationData::Current().LocalSettings().Values().Insert(LastChangedSettingsAppInstanceIdStr, box_value(L"")); - ApplicationData::Current().LocalSettings().Values().Insert(LastChangedSettingsKeyStr, box_value(LaunchElevetedProcessSuccessStr)); - - printDebugMessage(L"Launching of Adminstrator Extension was cancelled."); - pair ex = getLastErrorDetails(); - properties.insert(properties.end(), - { - pair("Denied", "True"), - pair("Error Code", to_string(ex.first)), - pair("Error Message", to_string(ex.second)) - }); - } - - ApplicationData::Current().SignalDataChanged(); - AppCenter::trackEvent("OnAdminstratorPrivilageRequested", properties); -} - bool isFirstInstance(LPCTSTR mutexName) { auto result = true; @@ -109,7 +50,7 @@ bool isFirstInstance(LPCTSTR mutexName) CreateMutex(NULL, FALSE, mutexName); #ifdef _DEBUG - initializeLogging(wcscmp(mutexName, DesktopExtensionMutexName) == 0 ? L"-extension.log" : L"-elevated-extension.log"); + initializeLogging(wcscmp(mutexName, ExtensionMutexName) == 0 ? L"-extension.log" : L"-elevated-extension.log"); #endif } else @@ -156,32 +97,15 @@ INT main() SetErrorMode(SEM_NOGPFAULTERRORBOX); _onexit(releaseResources); - ProcessIdToSessionId(GetCurrentProcessId(), &sessionId); - init_apartment(); AppCenter::start(); if (isElevatedProcess()) { - if (!isFirstInstance(AdminExtensionMutexName)) return 0; - - initializeAdminService(); + initializeElevatedService(); } else { - if (!isFirstInstance(DesktopExtensionMutexName)) return 0; - - launchElevatedProcess(); - return 0; - } - - LifeTimeCheck: - HANDLE lifeTimeObj = OpenMutex(SYNCHRONIZE, FALSE, format(L"AppContainerNamedObjects\\{}\\{}", packageSid, DesktopExtensionLifetimeObjNameStr).c_str()); - if (lifeTimeObj) - { - CloseHandle(lifeTimeObj); - Sleep(1000); - goto LifeTimeCheck; + initializeExtensionService(); } - return 0; } \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/pch.cpp b/src/Notepads.DesktopExtension/pch.cpp index 849a1cb4e..772a0d164 100644 --- a/src/Notepads.DesktopExtension/pch.cpp +++ b/src/Notepads.DesktopExtension/pch.cpp @@ -1,6 +1,10 @@ #include "pch.h" #include "appcenter.h" +#define MAX_TIME_STR 20 +#define MAX_DATE_STR 20 +#define MAX_DATETIME_STR 100 + using namespace boost::stacktrace; using namespace boost::stacktrace::detail; using namespace fmt; @@ -10,10 +14,6 @@ using namespace Windows::Foundation; using namespace Windows::Storage; using namespace Windows::System; -constexpr INT MAX_TIME_STR = 20; -constexpr INT MAX_DATE_STR = 20; -constexpr INT MAX_DATETIME_STR = 100; - StorageFile logFile = NULL; VOID printDebugMessage([[maybe_unused]] LPCTSTR message, [[maybe_unused]] DWORD sleepTime) { diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h index 8430e31f2..c099b3ef9 100644 --- a/src/Notepads.DesktopExtension/pch.h +++ b/src/Notepads.DesktopExtension/pch.h @@ -5,6 +5,7 @@ #include "windows.h" #include "shellapi.h" #include "winrt/Windows.ApplicationModel.h" +#include "winrt/Windows.ApplicationModel.Core.h" #include "winrt/Windows.ApplicationModel.DataTransfer.h" #include "winrt/Windows.Foundation.h" #include "winrt/Windows.Foundation.Collections.h" @@ -15,25 +16,38 @@ #include "boost/stacktrace.hpp" #include "fmt/core.h" +#define ExtensionMutexName L"ExtensionMutex" +#define ElevatedMutexName L"ElevatedMutex" + +#define PIPE_READ_BUFFER 2 * MAX_PATH + 10 +#define PIPE_NAME_FORMAT L"\\\\.\\pipe\\Sessions\\{}\\AppContainerNamedObjects\\{}\\{}" +#define NAMED_OBJECT_FORMAT L"AppContainerNamedObjects\\{}\\{}" + // These values depend upon constant fields described in ..\Notepads\Settings\SettingsKey.cs. // Changing value in one place require changing variable with similar name in another. ///////////////////////////////////////////////////////////////////////////////////////////// -constexpr LPCTSTR AppCenterSecret = NULL; -constexpr LPCTSTR AppCenterInstallIdStr = L"AppCenterInstallIdStr"; -constexpr LPCTSTR LastChangedSettingsKeyStr = L"LastChangedSettingsKeyStr"; -constexpr LPCTSTR LastChangedSettingsAppInstanceIdStr = L"LastChangedSettingsAppInstanceIdStr"; -constexpr LPCTSTR LaunchElevetedProcessSuccessStr = L"LaunchElevetedProcessSuccess"; -constexpr LPCTSTR LaunchElevetedProcessFailedStr = L"LaunchElevetedProcessFailed"; -constexpr LPCTSTR DesktopExtensionLifetimeObjNameStr = L"DesktopExtensionLifetimeObj"; -constexpr LPCTSTR PackageSidStr = L"PackageSidStr"; -constexpr LPCTSTR AdminWriteEventNameStr = L"NotepadsAdminWriteEvent"; -constexpr LPCTSTR AdminWritePipeConnectionNameStr = L"NotepadsAdminWritePipe"; -constexpr LPCTSTR AdminRenameEventNameStr = L"NotepadsAdminRenameEvent"; -constexpr LPCTSTR AdminRenamePipeConnectionNameStr = L"NotepadsAdminRenamePipe"; +#define AppCenterSecret NULL +#define PackageSidStr L"PackageSidStr" +#define AppCenterInstallIdStr L"AppCenterInstallIdStr" +#define LastChangedSettingsKeyStr L"LastChangedSettingsKeyStr" +#define LastChangedSettingsAppInstanceIdStr L"LastChangedSettingsAppInstanceIdStr" +#define LaunchElevetedProcessSuccessStr L"LaunchElevetedProcessSuccess" +#define LaunchElevetedProcessFailedStr L"LaunchElevetedProcessFailed" +#define ExtensionProcessLifetimeObjNameStr L"ExtensionProcessLifetimeObj" +#define ElevatedProcessLifetimeObjNameStr L"ElevatedProcessLifetimeObj" +#define ExtensionUnblockEventNameStr L"NotepadsExtensionUnblockEvent" +#define ElevatedWriteEventNameStr L"NotepadsElevatedWriteEvent" +#define ElevatedRenameEventNameStr L"NotepadsElevatedRenameEvent" +#define ExtensionUnblockPipeConnectionNameStr L"NotepadsExtensionUnblockPipe" +#define ElevatedWritePipeConnectionNameStr L"NotepadsElevatedWritePipe" +#define ElevatedRenamePipeConnectionNameStr L"NotepadsElevatedRenamePipe" ///////////////////////////////////////////////////////////////////////////////////////////// -bool isElevatedProcess(); VOID setExceptionHandling(); +bool isElevatedProcess(); +bool isFirstInstance(LPCTSTR mutexName); +VOID initializeExtensionService(); +VOID initializeElevatedService(); VOID exitApp(); VOID printDebugMessage([[maybe_unused]] LPCTSTR message, [[maybe_unused]] DWORD sleepTime = 0); @@ -42,9 +56,7 @@ std::string getTimeStamp(const CHAR* format); std::string to_string(winrt::Windows::System::ProcessorArchitecture arch); std::string base64_encode(const std::string& in); -VOID initializeAdminService(); winrt::Windows::Foundation::IInspectable readSettingsKey(winrt::hstring key); - std::pair getLastErrorDetails(); winrt::Windows::Foundation::IAsyncAction logLastError(bool isFatal); winrt::fire_and_forget initializeLogging(LPCTSTR trailStr); \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/vcpkg.json b/src/Notepads.DesktopExtension/vcpkg.json index 8db28aa6e..659282202 100644 --- a/src/Notepads.DesktopExtension/vcpkg.json +++ b/src/Notepads.DesktopExtension/vcpkg.json @@ -1,7 +1,7 @@ { "name": "notepads-desktopextension", "version-string": "1.0.0.0", - "$builtin-baseline": "b60f003ccf5fe8613d029f49f835c8929a66eb61", + "$builtin-baseline": "0c94afc7883faee9f188c36232d628ffa94cf27f", "dependencies": [ { "name": "boost-stacktrace", diff --git a/src/Notepads/Controls/Dialog/LaunchElevatedExtensionDialog.cs b/src/Notepads/Controls/Dialog/LaunchElevatedExtensionDialog.cs index a4a2ffe7b..64f6c7fe6 100644 --- a/src/Notepads/Controls/Dialog/LaunchElevatedExtensionDialog.cs +++ b/src/Notepads/Controls/Dialog/LaunchElevatedExtensionDialog.cs @@ -4,24 +4,24 @@ using Notepads.Services; using Windows.ApplicationModel.Resources; - public class LaunchElevatedExtensionDialog : NotepadsDialog + public class LaunchElevatedProcessDialog : NotepadsDialog { - public LaunchElevatedExtensionDialog(AdminOperationType type, string fileName, Action confirmedAction, Action closeAction) + public LaunchElevatedProcessDialog(ElevatedOperationType type, string fileName, Action confirmedAction, Action closeAction) { - if (type == AdminOperationType.Save) + if (type == ElevatedOperationType.Save) { - Title = ResourceLoader.GetString("LaunchElevatedExtensionDialog_SaveFailed_Title"); - Content = string.Format(ResourceLoader.GetString("LaunchElevatedExtensionDialog_SaveFailed_Content"), fileName); - CloseButtonText = ResourceLoader.GetString("LaunchElevatedExtensionDialog_SaveFailed_CloseButtonText"); + Title = ResourceLoader.GetString("LaunchElevatedProcessDialog_SaveFailed_Title"); + Content = string.Format(ResourceLoader.GetString("LaunchElevatedProcessDialog_SaveFailed_Content"), fileName); + CloseButtonText = ResourceLoader.GetString("LaunchElevatedProcessDialog_SaveFailed_CloseButtonText"); } else { - Title = ResourceLoader.GetString("LaunchElevatedExtensionDialog_RenameFailed_Title"); - Content = string.Format(ResourceLoader.GetString("LaunchElevatedExtensionDialog_RenameFailed_Content"), fileName); - CloseButtonText = ResourceLoader.GetString("LaunchElevatedExtensionDialog_RenameFailed_CloseButtonText"); + Title = ResourceLoader.GetString("LaunchElevatedProcessDialog_RenameFailed_Title"); + Content = string.Format(ResourceLoader.GetString("LaunchElevatedProcessDialog_RenameFailed_Content"), fileName); + CloseButtonText = ResourceLoader.GetString("LaunchElevatedProcessDialog_RenameFailed_CloseButtonText"); } - PrimaryButtonText = ResourceLoader.GetString("LaunchElevatedExtensionDialog_PrimaryButtonText"); + PrimaryButtonText = ResourceLoader.GetString("LaunchElevatedProcessDialog_PrimaryButtonText"); if (confirmedAction != null) PrimaryButtonClick += (dialog, args) => { confirmedAction(); }; if (closeAction != null) CloseButtonClick += (dialog, args) => { closeAction(); }; diff --git a/src/Notepads/Package.appxmanifest b/src/Notepads/Package.appxmanifest index 72d4b3055..dca200dd6 100644 --- a/src/Notepads/Package.appxmanifest +++ b/src/Notepads/Package.appxmanifest @@ -71,7 +71,12 @@ - + + + + + + diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index 5ac50e326..d9958f21a 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -18,7 +18,7 @@ using Windows.Security.Authentication.Web; using Windows.Storage; - public enum AdminOperationType + public enum ElevatedOperationType { Save, Rename @@ -38,30 +38,98 @@ public static class DesktopExtensionService ApiInformation.IsApiContractPresent("Windows.ApplicationModel.FullTrustAppContract", 1, 0) && !new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator); - public static Mutex ExtensionLifetimeObject = null; - private static readonly ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView(); - private static EventWaitHandle _adminWriteEvent = null; - private static EventWaitHandle _adminRenameEvent = null; + private static Mutex ExtensionProcessLifetimeObject = null; + private static Mutex ElevatedProcessLifetimeObject = null; + + private static EventWaitHandle _extensionUnblockEvent = null; + private static EventWaitHandle _elevatedWriteEvent = null; + private static EventWaitHandle _elevatedRenameEvent = null; - public static void Initialize() + /// + /// Initializes desktop processes. + /// + public static async void Initialize() { if (!ShouldUseDesktopExtension) return; - if (ExtensionLifetimeObject == null) + if (ExtensionProcessLifetimeObject == null) + { + ExtensionProcessLifetimeObject = new Mutex(false, SettingsKey.ExtensionProcessLifetimeObjNameStr); + } + + if (ElevatedProcessLifetimeObject == null) + { + ElevatedProcessLifetimeObject = new Mutex(false, SettingsKey.ElevatedProcessLifetimeObjNameStr); + } + + if (_extensionUnblockEvent == null) { - ExtensionLifetimeObject = new Mutex(false, SettingsKey.DesktopExtensionLifetimeObjNameStr); + _extensionUnblockEvent = new EventWaitHandle(false, EventResetMode.ManualReset, SettingsKey.ExtensionUnblockEventNameStr); } - if (_adminWriteEvent == null) + if (_elevatedWriteEvent == null) { - _adminWriteEvent = new EventWaitHandle(false, EventResetMode.ManualReset, SettingsKey.AdminWriteEventNameStr); + _elevatedWriteEvent = new EventWaitHandle(false, EventResetMode.ManualReset, SettingsKey.ElevatedWriteEventNameStr); } - if (_adminRenameEvent == null) + if (_elevatedRenameEvent == null) { - _adminRenameEvent = new EventWaitHandle(false, EventResetMode.ManualReset, SettingsKey.AdminRenameEventNameStr); + _elevatedRenameEvent = new EventWaitHandle(false, EventResetMode.ManualReset, SettingsKey.ElevatedRenameEventNameStr); + } + + ApplicationSettingsStore.Write(SettingsKey.PackageSidStr, WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host.ToUpper()); + ApplicationSettingsStore.Write(SettingsKey.AppCenterInstallIdStr, (await AppCenter.GetInstallIdAsync())?.ToString()); + + await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); + } + + /// + /// Releases resources and closes desktop processes. + /// + public static void Dispose() + { + _extensionUnblockEvent?.Dispose(); + _elevatedWriteEvent?.Dispose(); + _elevatedRenameEvent?.Dispose(); + ExtensionProcessLifetimeObject?.Dispose(); + ElevatedProcessLifetimeObject?.Dispose(); + } + + /// + /// Unblock UWP edited file with desktop component. + /// + /// + /// Only available for legacy Windows 10 desktop. + /// + public static async void UnblockFile(string filePath) + { + if (!ShouldUseDesktopExtension) return; + + using (var pipeStream = new NamedPipeServerStream( + $"Local\\{SettingsKey.ExtensionUnblockPipeConnectionNameStr}", + PipeDirection.Out, + NamedPipeServerStream.MaxAllowedServerInstances, + PipeTransmissionMode.Message, + PipeOptions.Asynchronous)) + { + _extensionUnblockEvent.Set(); + // Wait for 100 ms for desktop extension to accept request. + if (!pipeStream.WaitForConnectionAsync().Wait(100)) + { + // If the connection fails, desktop extension is not launched. + // In that case, launch desktop extension. + _extensionUnblockEvent.Reset(); + await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); + } + else + { + var pipeWriter = new StreamWriter(pipeStream, new System.Text.UnicodeEncoding(!BitConverter.IsLittleEndian, false)); + + await pipeWriter.WriteAsync(filePath); + await pipeWriter.FlushAsync(); + } } } @@ -75,9 +143,8 @@ public static async Task LaunchElevetedProcess() { if (!ShouldUseDesktopExtension) return; - ApplicationSettingsStore.Write(SettingsKey.PackageSidStr, WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host.ToUpper()); - ApplicationSettingsStore.Write(SettingsKey.AppCenterInstallIdStr, (await AppCenter.GetInstallIdAsync())?.ToString()); - await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); + // Pass the group id that describes the correct parameter for prompting elevated process launch + await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync("Elevate"); } /// @@ -91,11 +158,11 @@ public static void OnElevetedProcessLaunchRequested(bool isLaunched) { if (isLaunched) { - NotificationCenter.Instance.PostNotification(_resourceLoader.GetString("TextEditor_NotificationMsg_AdminExtensionCreated"), 1500); + NotificationCenter.Instance.PostNotification(_resourceLoader.GetString("TextEditor_NotificationMsg_ElevatedProcessLaunched"), 1500); } else { - NotificationCenter.Instance.PostNotification(_resourceLoader.GetString("TextEditor_NotificationMsg_AdminExtensionCreationFailed"), 1500); + NotificationCenter.Instance.PostNotification(_resourceLoader.GetString("TextEditor_NotificationMsg_ElevatedProcessLaunchFailed"), 1500); } } @@ -111,26 +178,26 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) { if (!ShouldUseDesktopExtension) return; - using (var adminConnectionPipeStream = new NamedPipeServerStream( - $"Local\\{SettingsKey.AdminWritePipeConnectionNameStr}", + using (var pipeStream = new NamedPipeServerStream( + $"Local\\{SettingsKey.ElevatedWritePipeConnectionNameStr}", PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.Asynchronous)) { - _adminWriteEvent.Set(); - // Wait for 250 ms for desktop extension to accept request. - if (!adminConnectionPipeStream.WaitForConnectionAsync().Wait(100)) + _elevatedWriteEvent.Set(); + // Wait for 100 ms for desktop extension to accept request. + if (!pipeStream.WaitForConnectionAsync().Wait(100)) { // If the connection fails, desktop extension is not launched with elevated privilages. // In that case, prompt user to launch desktop extension with elevated privilages. - _adminWriteEvent.Reset(); - adminConnectionPipeStream?.Dispose(); + _elevatedWriteEvent.Reset(); + pipeStream?.Dispose(); throw new AdminstratorAccessException(); } - var pipeReader = new StreamReader(adminConnectionPipeStream, new System.Text.UnicodeEncoding(!BitConverter.IsLittleEndian, false)); - var pipeWriter = new StreamWriter(adminConnectionPipeStream, new System.Text.UnicodeEncoding(!BitConverter.IsLittleEndian, false)); + var pipeReader = new StreamReader(pipeStream, new System.Text.UnicodeEncoding(!BitConverter.IsLittleEndian, false)); + var pipeWriter = new StreamWriter(pipeStream, new System.Text.UnicodeEncoding(!BitConverter.IsLittleEndian, false)); var mapName = filePath.Replace(Path.DirectorySeparatorChar, '-'); @@ -151,7 +218,7 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) { // Promt user to "Save As" if extension failed to save data. mmf?.Dispose(); - adminConnectionPipeStream?.Dispose(); + pipeStream?.Dispose(); throw new UnauthorizedAccessException(); } } @@ -170,34 +237,34 @@ public static async Task RenameFileAsAdmin(StorageFile file, string { if (!ShouldUseDesktopExtension) return null; - using (var adminConnectionPipeStream = new NamedPipeServerStream( - $"Local\\{SettingsKey.AdminRenamePipeConnectionNameStr}", + using (var pipeStream = new NamedPipeServerStream( + $"Local\\{SettingsKey.ElevatedRenamePipeConnectionNameStr}", PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, PipeOptions.Asynchronous)) { - _adminRenameEvent.Set(); - // Wait for 250 ms for desktop extension to accept request. - if (!adminConnectionPipeStream.WaitForConnectionAsync().Wait(100)) + _elevatedRenameEvent.Set(); + // Wait for 100 ms for desktop extension to accept request. + if (!pipeStream.WaitForConnectionAsync().Wait(100)) { // If the connection fails, desktop extension is not launched with elevated privilages. // In that case, prompt user to launch desktop extension with elevated privilages. - _adminRenameEvent.Reset(); - file = null; + _elevatedRenameEvent.Reset(); - var launchElevatedExtensionDialog = new LaunchElevatedExtensionDialog( - AdminOperationType.Rename, + var launchElevatedProcessDialog = new LaunchElevatedProcessDialog( + ElevatedOperationType.Rename, file.Path, - async () => { await DesktopExtensionService.LaunchElevetedProcess(); }, + async () => { await LaunchElevetedProcess(); }, null); - var dialogResult = await DialogManager.OpenDialogAsync(launchElevatedExtensionDialog, awaitPreviousDialog: false); + await DialogManager.OpenDialogAsync(launchElevatedProcessDialog, awaitPreviousDialog: false); + file = null; } else { - var pipeReader = new StreamReader(adminConnectionPipeStream, new System.Text.UnicodeEncoding(!BitConverter.IsLittleEndian, false)); - var pipeWriter = new StreamWriter(adminConnectionPipeStream, new System.Text.UnicodeEncoding(!BitConverter.IsLittleEndian, false)); + var pipeReader = new StreamReader(pipeStream, new System.Text.UnicodeEncoding(!BitConverter.IsLittleEndian, false)); + var pipeWriter = new StreamWriter(pipeStream, new System.Text.UnicodeEncoding(!BitConverter.IsLittleEndian, false)); var token = SharedStorageAccessManager.AddFile(file); await pipeWriter.WriteAsync($"{token}|{newName}"); diff --git a/src/Notepads/Settings/SettingsKey.cs b/src/Notepads/Settings/SettingsKey.cs index 9c9ceeab3..2d98ea225 100644 --- a/src/Notepads/Settings/SettingsKey.cs +++ b/src/Notepads/Settings/SettingsKey.cs @@ -39,16 +39,19 @@ internal static class SettingsKey // These values depend upon constant fields described in ..\Notepads.DesktopExtension\pch.h. // Changing value in one place require changing variable with similar name in another. internal const string AppCenterSecret = null; + internal const string PackageSidStr = "PackageSidStr"; internal const string AppCenterInstallIdStr = "AppCenterInstallIdStr"; internal const string LastChangedSettingsKeyStr = "LastChangedSettingsKeyStr"; internal const string LastChangedSettingsAppInstanceIdStr = "LastChangedSettingsAppInstanceIdStr"; internal const string LaunchElevetedProcessSuccessStr = "LaunchElevetedProcessSuccess"; internal const string LaunchElevetedProcessFailedStr = "LaunchElevetedProcessFailed"; - internal const string DesktopExtensionLifetimeObjNameStr = "DesktopExtensionLifetimeObj"; - internal const string PackageSidStr = "PackageSidStr"; - internal const string AdminWriteEventNameStr = "NotepadsAdminWriteEvent"; - internal const string AdminWritePipeConnectionNameStr = "NotepadsAdminWritePipe"; - internal const string AdminRenameEventNameStr = "NotepadsAdminRenameEvent"; - internal const string AdminRenamePipeConnectionNameStr = "NotepadsAdminRenamePipe"; + internal const string ExtensionProcessLifetimeObjNameStr = "ExtensionProcessLifetimeObj"; + internal const string ElevatedProcessLifetimeObjNameStr = "ElevatedProcessLifetimeObj"; + internal const string ExtensionUnblockEventNameStr = "NotepadsExtensionUnblockEvent"; + internal const string ElevatedWriteEventNameStr = "NotepadsElevatedWriteEvent"; + internal const string ElevatedRenameEventNameStr = "NotepadsElevatedRenameEvent"; + internal const string ExtensionUnblockPipeConnectionNameStr = "NotepadsExtensionUnblockPipe"; + internal const string ElevatedWritePipeConnectionNameStr = "NotepadsElevatedWritePipe"; + internal const string ElevatedRenamePipeConnectionNameStr = "NotepadsElevatedRenamePipe"; } } \ No newline at end of file diff --git a/src/Notepads/Strings/en-US/Resources.resw b/src/Notepads/Strings/en-US/Resources.resw index 2da3201fb..44ea44cef 100644 --- a/src/Notepads/Strings/en-US/Resources.resw +++ b/src/Notepads/Strings/en-US/Resources.resw @@ -693,40 +693,40 @@ File extension "{0}" is not supported at this moment FileRenameError: Extension is not currently supported. {0} stands for the file extension string. - + Save As - LaunchElevatedExtensionDialog: Save Failed CloseButtonText. + LaunchElevatedProcessDialog: Save Failed CloseButtonText. - + Notepads needs Adminstrative Privilage to modify file "{0}" - LaunchElevatedExtensionDialog: Save Failed "Content" display text. + LaunchElevatedProcessDialog: Save Failed "Content" display text. - + Save Failed - LaunchElevatedExtensionDialog: Save Failed "Title" display text. + LaunchElevatedProcessDialog: Save Failed "Title" display text. - + Now system files can be directly modified - TextEditor: Notification message when launching of admin process is successful. + TextEditor: Notification message when launching of elevated process is successful. - - Failed to start admin process - TextEditor: Notification message when launching of admin process is failed. + + Failed to start elevated process + TextEditor: Notification message when launching of elevated process is failed. - + Give Access - LaunchElevatedExtensionDialog: PrimaryButtonText. + LaunchElevatedProcessDialog: PrimaryButtonText. - + Cancel - LaunchElevatedExtensionDialog: Rename Failed CloseButtonText. + LaunchElevatedProcessDialog: Rename Failed CloseButtonText. - + Notepads needs Adminstrative Privilage to rename file "{0}" - LaunchElevatedExtensionDialog: Rename Failed "Content" display text. + LaunchElevatedProcessDialog: Rename Failed "Content" display text. - + Rename Failed - LaunchElevatedExtensionDialog: Rename Failed "Title" display text. + LaunchElevatedProcessDialog: Rename Failed "Title" display text. \ No newline at end of file diff --git a/src/Notepads/Utilities/FileSystemUtility.cs b/src/Notepads/Utilities/FileSystemUtility.cs index 073e8588c..3c4097c9f 100644 --- a/src/Notepads/Utilities/FileSystemUtility.cs +++ b/src/Notepads/Utilities/FileSystemUtility.cs @@ -576,6 +576,7 @@ public static async Task WriteToFile(string text, Encoding encoding, StorageFile try { await PathIO.WriteBytesAsync(file.Path, result); + DesktopExtensionService.UnblockFile(file.Path); } catch (UnauthorizedAccessException ex) // Try to save as admin if fullTrust api is supported { @@ -594,6 +595,7 @@ public static async Task WriteToFile(string text, Encoding encoding, StorageFile await writer.FlushAsync(); stream.SetLength(stream.Position); // Truncate } + DesktopExtensionService.UnblockFile(file.Path); } } finally diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs index 2ccc2ae49..79d247e89 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.IO.cs @@ -170,8 +170,8 @@ private async Task TrySaveFile(ITextEditor textEditor, StorageFile file, b } catch (AdminstratorAccessException) // Happens when the file we are saving is read-only, ask user for permission to write { - var launchElevatedExtensionDialog = new LaunchElevatedExtensionDialog( - AdminOperationType.Save, file.Path, + var launchElevatedProcessDialog = new LaunchElevatedProcessDialog( + ElevatedOperationType.Save, file.Path, async () => { await DesktopExtensionService.LaunchElevetedProcess(); @@ -181,9 +181,9 @@ private async Task TrySaveFile(ITextEditor textEditor, StorageFile file, b isSaveSuccess = false; }); - var dialogResult = await DialogManager.OpenDialogAsync(launchElevatedExtensionDialog, awaitPreviousDialog: false); + var dialogResult = await DialogManager.OpenDialogAsync(launchElevatedProcessDialog, awaitPreviousDialog: false); - if (dialogResult == null || launchElevatedExtensionDialog.IsAborted) + if (dialogResult == null || launchElevatedProcessDialog.IsAborted) { isSaveSuccess = false; } diff --git a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs index b4aaf6e87..2fd78e078 100644 --- a/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs +++ b/src/Notepads/Views/MainPage/NotepadsMainPage.xaml.cs @@ -353,7 +353,7 @@ private async void MainPage_CloseRequested(object sender, Windows.UI.Core.Previe // Save session before app exit await SessionManager.SaveSessionAsync(() => { SessionManager.IsBackupEnabled = false; }); App.InstanceHandlerMutex?.Dispose(); - DesktopExtensionService.ExtensionLifetimeObject?.Dispose(); + DesktopExtensionService.Dispose(); deferral.Complete(); return; } @@ -361,7 +361,7 @@ private async void MainPage_CloseRequested(object sender, Windows.UI.Core.Previe if (!NotepadsCore.HaveUnsavedTextEditor()) { App.InstanceHandlerMutex?.Dispose(); - DesktopExtensionService.ExtensionLifetimeObject?.Dispose(); + DesktopExtensionService.Dispose(); deferral.Complete(); return; } @@ -395,7 +395,7 @@ private async void MainPage_CloseRequested(object sender, Windows.UI.Core.Previe else { App.InstanceHandlerMutex?.Dispose(); - DesktopExtensionService.ExtensionLifetimeObject?.Dispose(); + DesktopExtensionService.Dispose(); } deferral.Complete(); @@ -403,7 +403,7 @@ private async void MainPage_CloseRequested(object sender, Windows.UI.Core.Previe discardAndExitAction: () => { App.InstanceHandlerMutex?.Dispose(); - DesktopExtensionService.ExtensionLifetimeObject?.Dispose(); + DesktopExtensionService.Dispose(); deferral.Complete(); }, cancelAction: () => From 14532e29432723ed1bfde954c4771993e387ce55 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Tue, 19 Jan 2021 00:48:24 +0530 Subject: [PATCH 142/181] code refactor. --- src/Notepads.DesktopExtension/extension.cpp | 20 +++++++++++++++++--- src/Notepads.DesktopExtension/pch.h | 1 + 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/Notepads.DesktopExtension/extension.cpp b/src/Notepads.DesktopExtension/extension.cpp index dd5509e3e..6fa49f393 100644 --- a/src/Notepads.DesktopExtension/extension.cpp +++ b/src/Notepads.DesktopExtension/extension.cpp @@ -42,15 +42,29 @@ DWORD WINAPI unblockFileFromPipeData(LPVOID /* param */) } } while (byteRead >= (PIPE_READ_BUFFER - 1) * sizeof(TCHAR)); - wstring filePath(pipeData.str()); - if (DeleteFile(format(L"{}:Zone.Identifier", filePath).c_str())) + hstring filePath(pipeData.str()); + com_ptr pFile; + if (SUCCEEDED(CoCreateInstance(CLSID_PersistentZoneIdentifier, 0, CLSCTX_ALL, __uuidof(pFile), pFile.put_void())) && + SUCCEEDED(pFile->Load(filePath.c_str(), STGM_READWRITE))) { - printDebugMessage(format(L"Successfully unblocked file \"{}\"", filePath).c_str()); + LPTSTR lastWriterPackageFamilyName; + if (SUCCEEDED(pFile.as()->GetLastWriterPackageFamilyName(&lastWriterPackageFamilyName)) && + Package::Current().Id().FamilyName() == lastWriterPackageFamilyName && + SUCCEEDED(pFile.as()->Remove()) && + SUCCEEDED(pFile->Save(filePath.c_str(), TRUE))) + { + printDebugMessage(format(L"Successfully unblocked file \"{}\"", filePath).c_str()); + } + else + { + printDebugMessage(format(L"Failed to unblock file \"{}\"", filePath).c_str()); + } } else { printDebugMessage(format(L"Failed to unblock file \"{}\"", filePath).c_str()); } + pFile.~com_ptr(); CloseHandle(hPipe); printDebugMessage(L"Waiting on uwp app to send data."); diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h index c099b3ef9..7a2c9e574 100644 --- a/src/Notepads.DesktopExtension/pch.h +++ b/src/Notepads.DesktopExtension/pch.h @@ -4,6 +4,7 @@ #include "sstream" #include "windows.h" #include "shellapi.h" +#include "shlobj_core.h" #include "winrt/Windows.ApplicationModel.h" #include "winrt/Windows.ApplicationModel.Core.h" #include "winrt/Windows.ApplicationModel.DataTransfer.h" From 5dd0f24b45b42713cb312ba3ae0d4b84693dc087 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Wed, 20 Jan 2021 10:34:17 +0530 Subject: [PATCH 143/181] Fixed rename not working. --- src/Notepads.DesktopExtension/PropertySheet.props | 2 +- src/Notepads.DesktopExtension/elevated.cpp | 8 ++++---- src/Notepads.DesktopExtension/pch.h | 2 +- src/Notepads.DesktopExtension/vcpkg.json | 2 +- src/Notepads/Services/DesktopExtensionService.cs | 8 ++++---- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/Notepads.DesktopExtension/PropertySheet.props b/src/Notepads.DesktopExtension/PropertySheet.props index be03aabb5..ed80ee32d 100644 --- a/src/Notepads.DesktopExtension/PropertySheet.props +++ b/src/Notepads.DesktopExtension/PropertySheet.props @@ -14,7 +14,7 @@ https://github.com/microsoft/vcpkg - 0c94afc7883faee9f188c36232d628ffa94cf27f + c977e3861d24f54b589e321c852a79b027df899b windows diff --git a/src/Notepads.DesktopExtension/elevated.cpp b/src/Notepads.DesktopExtension/elevated.cpp index 822cb75c9..055b548a3 100644 --- a/src/Notepads.DesktopExtension/elevated.cpp +++ b/src/Notepads.DesktopExtension/elevated.cpp @@ -6,7 +6,7 @@ using namespace fmt; using namespace std; using namespace winrt; using namespace Windows::ApplicationModel; -using namespace Windows::ApplicationModel::DataTransfer; +using namespace Windows::Storage::AccessCache; extern DWORD sessionId; extern hstring packageSid; @@ -162,11 +162,11 @@ DWORD WINAPI renameFileFromPipeData(LPVOID /* param */) getline(pipeData, fileToken, L'|'); getline(pipeData, newName, L'|'); - auto file = SharedStorageAccessManager::RedeemTokenForFileAsync(fileToken).get(); - SharedStorageAccessManager::RemoveFile(fileToken); + auto file = StorageApplicationPermissions::FutureAccessList().GetFileAsync(fileToken).get(); + StorageApplicationPermissions::FutureAccessList().Remove(fileToken); auto oldName = file.Path(); file.RenameAsync(newName).get(); - result = SharedStorageAccessManager::AddFile(file).c_str(); + result = StorageApplicationPermissions::FutureAccessList().Add(file).c_str(); if (WriteFile(hPipe, result, wcslen(result) * sizeof(TCHAR), NULL, NULL)) FlushFileBuffers(hPipe); CloseHandle(hPipe); diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h index 7a2c9e574..6f8ec1c64 100644 --- a/src/Notepads.DesktopExtension/pch.h +++ b/src/Notepads.DesktopExtension/pch.h @@ -7,11 +7,11 @@ #include "shlobj_core.h" #include "winrt/Windows.ApplicationModel.h" #include "winrt/Windows.ApplicationModel.Core.h" -#include "winrt/Windows.ApplicationModel.DataTransfer.h" #include "winrt/Windows.Foundation.h" #include "winrt/Windows.Foundation.Collections.h" #include "winrt/Windows.Security.ExchangeActiveSyncProvisioning.h" #include "winrt/Windows.Storage.h" +#include "winrt/Windows.Storage.AccessCache.h" #include "winrt/Windows.System.h" #include "winrt/Windows.System.Profile.h" #include "boost/stacktrace.hpp" diff --git a/src/Notepads.DesktopExtension/vcpkg.json b/src/Notepads.DesktopExtension/vcpkg.json index 659282202..46aa9e2a8 100644 --- a/src/Notepads.DesktopExtension/vcpkg.json +++ b/src/Notepads.DesktopExtension/vcpkg.json @@ -1,7 +1,7 @@ { "name": "notepads-desktopextension", "version-string": "1.0.0.0", - "$builtin-baseline": "0c94afc7883faee9f188c36232d628ffa94cf27f", + "$builtin-baseline": "c977e3861d24f54b589e321c852a79b027df899b", "dependencies": [ { "name": "boost-stacktrace", diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index d9958f21a..0ad2dfb3a 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -12,11 +12,11 @@ using System.Threading; using System.Threading.Tasks; using Windows.ApplicationModel; - using Windows.ApplicationModel.DataTransfer; using Windows.ApplicationModel.Resources; using Windows.Foundation.Metadata; using Windows.Security.Authentication.Web; using Windows.Storage; + using Windows.Storage.AccessCache; public enum ElevatedOperationType { @@ -266,14 +266,14 @@ public static async Task RenameFileAsAdmin(StorageFile file, string var pipeReader = new StreamReader(pipeStream, new System.Text.UnicodeEncoding(!BitConverter.IsLittleEndian, false)); var pipeWriter = new StreamWriter(pipeStream, new System.Text.UnicodeEncoding(!BitConverter.IsLittleEndian, false)); - var token = SharedStorageAccessManager.AddFile(file); + var token = StorageApplicationPermissions.FutureAccessList.Add(file); await pipeWriter.WriteAsync($"{token}|{newName}"); await pipeWriter.FlushAsync(); // Wait for desktop extension to send response. token = await pipeReader.ReadLineAsync(); - file = await SharedStorageAccessManager.RedeemTokenForFileAsync(token); - SharedStorageAccessManager.RemoveFile(token); + file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(token); + StorageApplicationPermissions.FutureAccessList.Remove(token); } } From e64448a35628b658f2901d26e3d0039728306575 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Tue, 9 Feb 2021 09:35:29 +0530 Subject: [PATCH 144/181] Fix build failing. --- src/Notepads.Package/Notepads.Package.wapproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Notepads.Package/Notepads.Package.wapproj b/src/Notepads.Package/Notepads.Package.wapproj index 425247d43..263f82e51 100644 --- a/src/Notepads.Package/Notepads.Package.wapproj +++ b/src/Notepads.Package/Notepads.Package.wapproj @@ -82,7 +82,7 @@ - + From 20f570c5015e954a3d59ad981e96d440d62cc7e4 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 11 Feb 2021 20:23:37 +0530 Subject: [PATCH 145/181] Implementer version constraint with vcpkg. --- src/Notepads.DesktopExtension/.gitignore | 4 --- .../Notepads.DesktopExtension.vcxproj | 32 +++++++++++-------- .../Notepads.DesktopExtension.vcxproj.filters | 1 - .../PropertySheet.props | 21 ------------ src/Notepads.DesktopExtension/vcpkg.json | 19 +++++++---- src/Notepads.sln | 24 +++++++------- 6 files changed, 42 insertions(+), 59 deletions(-) delete mode 100644 src/Notepads.DesktopExtension/PropertySheet.props diff --git a/src/Notepads.DesktopExtension/.gitignore b/src/Notepads.DesktopExtension/.gitignore index b44ff4fd5..d516abcb1 100644 --- a/src/Notepads.DesktopExtension/.gitignore +++ b/src/Notepads.DesktopExtension/.gitignore @@ -1,7 +1,3 @@ -# vcpkg generated files # -######################### -**/vcpkg_installed/ - # AppCenter version file # ########################## appcenter-sdk-version.txt \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index 317aa2470..7dc6b7870 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -1,18 +1,20 @@ - + - true - true - true - true 15.0 {0a3b698e-6add-4c9e-9741-08f8ae576b2e} Win32Proj Notepads.DesktopExtension + obj\ + $(BaseIntermediateOutputPath)$(Platform)\$(Configuration)\ $(ProjectDir)bin\$(Platform)\$(Configuration)\ - obj\$(Platform)\$(Configuration)\ Notepads32 + true + true + true + true + $(BaseIntermediateOutputPath)Generated Files\ 10.0.19041.0 10.0.17763.0 true @@ -101,12 +103,19 @@ - - - + https://github.com/microsoft/vcpkg + + --feature-flags=versions + true + Release true + true + $(ProjectDir)$(BaseIntermediateOutputPath)$(Platform)\ @@ -171,7 +180,6 @@ - @@ -184,11 +192,7 @@ - - - - This project uses vcpkg that is missing on this computer. Manually download from $(VcpkgRepo) and place the contents in {0}. Or install git and add it to your path, for more information see https://git-scm.com. The missing file is {1}. diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters index 6114fce40..b2459d4ef 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters @@ -55,7 +55,6 @@ - Resource Files diff --git a/src/Notepads.DesktopExtension/PropertySheet.props b/src/Notepads.DesktopExtension/PropertySheet.props deleted file mode 100644 index 0af627514..000000000 --- a/src/Notepads.DesktopExtension/PropertySheet.props +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - https://github.com/microsoft/vcpkg - - ea11604579181b0ff790be223ee3ded3068142f9 - - - - \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/vcpkg.json b/src/Notepads.DesktopExtension/vcpkg.json index 46aa9e2a8..9d3db4668 100644 --- a/src/Notepads.DesktopExtension/vcpkg.json +++ b/src/Notepads.DesktopExtension/vcpkg.json @@ -1,24 +1,29 @@ { "name": "notepads-desktopextension", - "version-string": "1.0.0.0", - "$builtin-baseline": "c977e3861d24f54b589e321c852a79b027df899b", + "version": "1.0.0.0", "dependencies": [ + "boost-stacktrace", + "curl", + "fmt", + "rapidjson" + ], + "overrides": [ { "name": "boost-stacktrace", - "$version": "1.75.0" + "version": "1.75.0" }, { "name": "curl", - "$version": "7.74.0", - "$port-version": 1 + "version": "7.74.0", + "port-version": 3 }, { "name": "fmt", - "$version": "7.1.3" + "version": "7.1.3" }, { "name": "rapidjson", - "$version-date": "2020-09-14" + "version-date": "2020-09-14" } ] } \ No newline at end of file diff --git a/src/Notepads.sln b/src/Notepads.sln index 6863723a9..1cbed9975 100644 --- a/src/Notepads.sln +++ b/src/Notepads.sln @@ -95,18 +95,18 @@ Global {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|x86.ActiveCfg = Debug|x86 {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|x86.Build.0 = Debug|x86 {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Debug|x86.Deploy.0 = Debug|x86 - {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|ARM.ActiveCfg = Release|ARM - {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|ARM.Build.0 = Release|ARM - {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|ARM.Deploy.0 = Release|ARM - {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|ARM64.ActiveCfg = Release|ARM64 - {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|ARM64.Build.0 = Release|ARM64 - {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|ARM64.Deploy.0 = Release|ARM64 - {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|x64.ActiveCfg = Release|x64 - {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|x64.Build.0 = Release|x64 - {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|x64.Deploy.0 = Release|x64 - {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|x86.ActiveCfg = Release|x86 - {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|x86.Build.0 = Release|x86 - {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|x86.Deploy.0 = Release|x86 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|ARM.ActiveCfg = Production|ARM + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|ARM.Build.0 = Production|ARM + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|ARM.Deploy.0 = Production|ARM + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|ARM64.ActiveCfg = Production|ARM64 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|ARM64.Build.0 = Production|ARM64 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|ARM64.Deploy.0 = Production|ARM64 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|x64.ActiveCfg = Production|x64 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|x64.Build.0 = Production|x64 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|x64.Deploy.0 = Production|x64 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|x86.ActiveCfg = Production|x86 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|x86.Build.0 = Production|x86 + {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Production|x86.Deploy.0 = Production|x86 {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|ARM.ActiveCfg = Release|ARM {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|ARM.Build.0 = Release|ARM {F451C0EB-4F7F-47D4-BCCE-B0E265909DD9}.Release|ARM.Deploy.0 = Release|ARM From e53ac4b8fd5075df10ba9b95c05f93c1185c566e Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 12 Feb 2021 11:01:35 +0530 Subject: [PATCH 146/181] Update cppwinrt. --- .../Notepads.DesktopExtension.vcxproj | 8 ++++---- src/Notepads.DesktopExtension/packages.config | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index 7dc6b7870..6f501aebf 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -1,6 +1,6 @@ - + 15.0 {0a3b698e-6add-4c9e-9741-08f8ae576b2e} @@ -188,7 +188,7 @@ - + @@ -204,7 +204,7 @@ This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - + + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/packages.config b/src/Notepads.DesktopExtension/packages.config index 4d226bc09..a6b596a22 100644 --- a/src/Notepads.DesktopExtension/packages.config +++ b/src/Notepads.DesktopExtension/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file From 846d460b1bbb12e7f26e29852ac5b53eafbc0177 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 13 Feb 2021 12:30:49 +0530 Subject: [PATCH 147/181] Use msbuild tasks instead of powershell script to generate manifest. --- src/Notepads/Notepads.csproj | 13 +++----- src/Notepads/UpdateAppxManifest.targets | 41 +++++++++++++++++++++++++ src/Notepads/build.ps1 | 21 ------------- 3 files changed, 45 insertions(+), 30 deletions(-) create mode 100644 src/Notepads/UpdateAppxManifest.targets delete mode 100644 src/Notepads/build.ps1 diff --git a/src/Notepads/Notepads.csproj b/src/Notepads/Notepads.csproj index 27bd0f089..f2867138d 100644 --- a/src/Notepads/Notepads.csproj +++ b/src/Notepads/Notepads.csproj @@ -443,19 +443,14 @@ + + + 14.0 - - - - - - - - - + + /DWINRT_NO_MAKE_DETECTION %(AdditionalOptions) + + + _WINRT_DLL;WIN32_LEAN_AND_MEAN;WINRT_LEAN_AND_MEAN;%(PreprocessorDefinitions) + $(WindowsSDK_WindowsMetadata);$(AdditionalUsingDirectories) + + + Console + false + Notepads.Core.def + + + + + _DEBUG;%(PreprocessorDefinitions) + + + + + NDEBUG;%(PreprocessorDefinitions) + + + true + true + + + + + + CoreKey.idl + + + + + CoreKey.idl + + + Create + + + + + + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + \ No newline at end of file diff --git a/src/Notepads.Core/packages.config b/src/Notepads.Core/packages.config new file mode 100644 index 000000000..a6b596a22 --- /dev/null +++ b/src/Notepads.Core/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/src/Notepads.Core/pch.h b/src/Notepads.Core/pch.h new file mode 100644 index 000000000..d7ceb0c61 --- /dev/null +++ b/src/Notepads.Core/pch.h @@ -0,0 +1,18 @@ +#pragma once +#include "winrt/base.h" + +#define APP_CENTER_SECRET L"" +#define PACKAGE_SID_STR L"PackageSidStr" +#define APP_CENTER_INSTALL_ID_STR L"AppCenterInstallIdStr" +#define LAST_CHANGED_SETTINGS_KEY_STR L"LastChangedSettingsKeyStr" +#define LAST_CHANGED_SETTINGS_APP_INSTANCE_ID_STR L"LastChangedSettingsAppInstanceIdStr" +#define LAUNCH_ELEVATED_PROCESS_SUCCESS_STR L"LaunchElevatedProcessSuccess" +#define LAUNCH_ELEVATED_PROCESS_FAILED_STR L"LaunchElevatedProcessFailed" +#define EXTENSION_PROCESS_LIFETIME_OBJ_NAME_STR L"ExtensionProcessLifetimeObj" +#define ELEVATED_PROCESS_LIFETIME_OBJ_NAME_STR L"ElevatedProcessLifetimeObj" +#define EXTENSION_UNBLOCK_EVENT_NAME_STR L"NotepadsExtensionUnblockEvent" +#define ELEVATED_WRITE_EVENT_NAME_STR L"NotepadsElevatedWriteEvent" +#define ELEVATED_RENAME_EVENT_NAME_STR L"NotepadsElevatedRenameEvent" +#define EXTENSION_UNBLOCK_PIPE_CONNECTION_NAME_STR L"NotepadsExtensionUnblockPipe" +#define ELEVATED_WRITE_PIPE_CONNECTION_NAME_STR L"NotepadsElevatedWritePipe" +#define ELEVATED_RENAME_PIPE_CONNECTION_NAME_STR L"NotepadsElevatedRenamePipe" \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index 88492fe80..6b30f3e00 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -191,6 +191,11 @@ + + + {022dc661-4fa2-4264-a869-5a560fb4cc92} + + diff --git a/src/Notepads.DesktopExtension/extension.cpp b/src/Notepads.DesktopExtension/extension.cpp index 6fa49f393..7f67cdd3f 100644 --- a/src/Notepads.DesktopExtension/extension.cpp +++ b/src/Notepads.DesktopExtension/extension.cpp @@ -99,7 +99,7 @@ VOID launchElevatedProcess() if (ShellExecuteEx(&shExInfo)) { ApplicationData::Current().LocalSettings().Values().Insert(LastChangedSettingsAppInstanceIdStr, box_value(L"")); - ApplicationData::Current().LocalSettings().Values().Insert(LastChangedSettingsKeyStr, box_value(LaunchElevetedProcessSuccessStr)); + ApplicationData::Current().LocalSettings().Values().Insert(LastChangedSettingsKeyStr, box_value(LaunchElevatedProcessSuccessStr)); printDebugMessage(L"Elevated Process has been launched."); properties.push_back(pair("Accepted", "True")); @@ -107,7 +107,7 @@ VOID launchElevatedProcess() else { ApplicationData::Current().LocalSettings().Values().Insert(LastChangedSettingsAppInstanceIdStr, box_value(L"")); - ApplicationData::Current().LocalSettings().Values().Insert(LastChangedSettingsKeyStr, box_value(LaunchElevetedProcessFailedStr)); + ApplicationData::Current().LocalSettings().Values().Insert(LastChangedSettingsKeyStr, box_value(LaunchElevatedProcessFailedStr)); printDebugMessage(L"Launching of Elevated Process was cancelled."); pair ex = getLastErrorDetails(); diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h index 6f8ec1c64..c8c931d84 100644 --- a/src/Notepads.DesktopExtension/pch.h +++ b/src/Notepads.DesktopExtension/pch.h @@ -14,6 +14,7 @@ #include "winrt/Windows.Storage.AccessCache.h" #include "winrt/Windows.System.h" #include "winrt/Windows.System.Profile.h" +#include "winrt/Notepads.Core.h" #include "boost/stacktrace.hpp" #include "fmt/core.h" @@ -24,25 +25,21 @@ #define PIPE_NAME_FORMAT L"\\\\.\\pipe\\Sessions\\{}\\AppContainerNamedObjects\\{}\\{}" #define NAMED_OBJECT_FORMAT L"AppContainerNamedObjects\\{}\\{}" -// These values depend upon constant fields described in ..\Notepads\Settings\SettingsKey.cs. -// Changing value in one place require changing variable with similar name in another. -///////////////////////////////////////////////////////////////////////////////////////////// -#define AppCenterSecret NULL -#define PackageSidStr L"PackageSidStr" -#define AppCenterInstallIdStr L"AppCenterInstallIdStr" -#define LastChangedSettingsKeyStr L"LastChangedSettingsKeyStr" -#define LastChangedSettingsAppInstanceIdStr L"LastChangedSettingsAppInstanceIdStr" -#define LaunchElevetedProcessSuccessStr L"LaunchElevetedProcessSuccess" -#define LaunchElevetedProcessFailedStr L"LaunchElevetedProcessFailed" -#define ExtensionProcessLifetimeObjNameStr L"ExtensionProcessLifetimeObj" -#define ElevatedProcessLifetimeObjNameStr L"ElevatedProcessLifetimeObj" -#define ExtensionUnblockEventNameStr L"NotepadsExtensionUnblockEvent" -#define ElevatedWriteEventNameStr L"NotepadsElevatedWriteEvent" -#define ElevatedRenameEventNameStr L"NotepadsElevatedRenameEvent" -#define ExtensionUnblockPipeConnectionNameStr L"NotepadsExtensionUnblockPipe" -#define ElevatedWritePipeConnectionNameStr L"NotepadsElevatedWritePipe" -#define ElevatedRenamePipeConnectionNameStr L"NotepadsElevatedRenamePipe" -///////////////////////////////////////////////////////////////////////////////////////////// +#define AppCenterSecret winrt::Notepads::Core::CoreKey::AppCenterSecret().c_str() +#define PackageSidStr winrt::Notepads::Core::CoreKey::PackageSidStr().c_str() +#define AppCenterInstallIdStr winrt::Notepads::Core::CoreKey::AppCenterInstallIdStr().c_str() +#define LastChangedSettingsKeyStr winrt::Notepads::Core::CoreKey::LastChangedSettingsKeyStr().c_str() +#define LastChangedSettingsAppInstanceIdStr winrt::Notepads::Core::CoreKey::LastChangedSettingsAppInstanceIdStr().c_str() +#define LaunchElevatedProcessSuccessStr winrt::Notepads::Core::CoreKey::LaunchElevatedProcessSuccessStr().c_str() +#define LaunchElevatedProcessFailedStr winrt::Notepads::Core::CoreKey::LaunchElevatedProcessFailedStr().c_str() +#define ExtensionProcessLifetimeObjNameStr winrt::Notepads::Core::CoreKey::ExtensionProcessLifetimeObjNameStr().c_str() +#define ElevatedProcessLifetimeObjNameStr winrt::Notepads::Core::CoreKey::ElevatedProcessLifetimeObjNameStr().c_str() +#define ExtensionUnblockEventNameStr winrt::Notepads::Core::CoreKey::ExtensionUnblockEventNameStr().c_str() +#define ElevatedWriteEventNameStr winrt::Notepads::Core::CoreKey::ElevatedWriteEventNameStr().c_str() +#define ElevatedRenameEventNameStr winrt::Notepads::Core::CoreKey::ElevatedRenameEventNameStr().c_str() +#define ExtensionUnblockPipeConnectionNameStr winrt::Notepads::Core::CoreKey::ExtensionUnblockPipeConnectionNameStr().c_str() +#define ElevatedWritePipeConnectionNameStr winrt::Notepads::Core::CoreKey::ElevatedWritePipeConnectionNameStr().c_str() +#define ElevatedRenamePipeConnectionNameStr winrt::Notepads::Core::CoreKey::ElevatedRenamePipeConnectionNameStr().c_str() VOID setExceptionHandling(); bool isElevatedProcess(); diff --git a/src/Notepads.sln b/src/Notepads.sln index 1cbed9975..46cea285d 100644 --- a/src/Notepads.sln +++ b/src/Notepads.sln @@ -19,6 +19,8 @@ Project("{C7167F0D-BC9F-4E6E-AFE1-012C56B48DB5}") = "Notepads.Package", "Notepad EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Notepads.DesktopExtension", "Notepads.DesktopExtension\Notepads.DesktopExtension.vcxproj", "{0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}" EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Notepads.Core", "Notepads.Core\Notepads.Core.vcxproj", "{022DC661-4FA2-4264-A869-5A560FB4CC92}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|ARM = Debug|ARM @@ -143,6 +145,30 @@ Global {0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}.Release|x64.Build.0 = Release|x64 {0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}.Release|x86.ActiveCfg = Release|Win32 {0A3B698E-6ADD-4C9E-9741-08F8AE576B2E}.Release|x86.Build.0 = Release|Win32 + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Debug|ARM.ActiveCfg = Debug|ARM + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Debug|ARM.Build.0 = Debug|ARM + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Debug|ARM64.ActiveCfg = Debug|ARM64 + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Debug|ARM64.Build.0 = Debug|ARM64 + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Debug|x64.ActiveCfg = Debug|x64 + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Debug|x64.Build.0 = Debug|x64 + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Debug|x86.ActiveCfg = Debug|Win32 + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Debug|x86.Build.0 = Debug|Win32 + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Production|ARM.ActiveCfg = Production|ARM + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Production|ARM.Build.0 = Production|ARM + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Production|ARM64.ActiveCfg = Production|ARM64 + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Production|ARM64.Build.0 = Production|ARM64 + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Production|x64.ActiveCfg = Production|x64 + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Production|x64.Build.0 = Production|x64 + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Production|x86.ActiveCfg = Production|Win32 + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Production|x86.Build.0 = Production|Win32 + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Release|ARM.ActiveCfg = Release|ARM + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Release|ARM.Build.0 = Release|ARM + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Release|ARM64.ActiveCfg = Release|ARM64 + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Release|ARM64.Build.0 = Release|ARM64 + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Release|x64.ActiveCfg = Release|x64 + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Release|x64.Build.0 = Release|x64 + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Release|x86.ActiveCfg = Release|Win32 + {022DC661-4FA2-4264-A869-5A560FB4CC92}.Release|x86.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/Notepads/App.xaml.cs b/src/Notepads/App.xaml.cs index 591b0f496..d0bbf6d66 100644 --- a/src/Notepads/App.xaml.cs +++ b/src/Notepads/App.xaml.cs @@ -9,6 +9,7 @@ using Microsoft.AppCenter.Analytics; using Microsoft.AppCenter.Crashes; using Microsoft.Toolkit.Uwp.Helpers; + using Notepads.Core; using Notepads.Services; using Notepads.Settings; using Notepads.Utilities; @@ -43,7 +44,7 @@ public App() TaskScheduler.UnobservedTaskException += OnUnobservedException; var services = new Type[] { typeof(Crashes), typeof(Analytics) }; - AppCenter.Start(SettingsKey.AppCenterSecret, services); + AppCenter.Start(CoreKey.AppCenterSecret, services); InstanceHandlerMutex = new Mutex(true, App.ApplicationName, out bool isNew); if (isNew) diff --git a/src/Notepads/Notepads.csproj b/src/Notepads/Notepads.csproj index 361ea8013..cab7d5996 100644 --- a/src/Notepads/Notepads.csproj +++ b/src/Notepads/Notepads.csproj @@ -476,6 +476,10 @@ {7aa5e631-b663-420e-a08f-002cd81df855} Notepads.Controls + + {022dc661-4fa2-4264-a869-5a560fb4cc92} + Notepads.Core + diff --git a/src/Notepads/Services/DesktopExtensionService.cs b/src/Notepads/Services/DesktopExtensionService.cs index 0ad2dfb3a..43fa88931 100644 --- a/src/Notepads/Services/DesktopExtensionService.cs +++ b/src/Notepads/Services/DesktopExtensionService.cs @@ -2,6 +2,7 @@ { using Microsoft.AppCenter; using Notepads.Controls.Dialog; + using Notepads.Core; using Notepads.Settings; using Notepads.Utilities; using System; @@ -56,31 +57,31 @@ public static async void Initialize() if (ExtensionProcessLifetimeObject == null) { - ExtensionProcessLifetimeObject = new Mutex(false, SettingsKey.ExtensionProcessLifetimeObjNameStr); + ExtensionProcessLifetimeObject = new Mutex(false, CoreKey.ExtensionProcessLifetimeObjNameStr); } if (ElevatedProcessLifetimeObject == null) { - ElevatedProcessLifetimeObject = new Mutex(false, SettingsKey.ElevatedProcessLifetimeObjNameStr); + ElevatedProcessLifetimeObject = new Mutex(false, CoreKey.ElevatedProcessLifetimeObjNameStr); } if (_extensionUnblockEvent == null) { - _extensionUnblockEvent = new EventWaitHandle(false, EventResetMode.ManualReset, SettingsKey.ExtensionUnblockEventNameStr); + _extensionUnblockEvent = new EventWaitHandle(false, EventResetMode.ManualReset, CoreKey.ExtensionUnblockEventNameStr); } if (_elevatedWriteEvent == null) { - _elevatedWriteEvent = new EventWaitHandle(false, EventResetMode.ManualReset, SettingsKey.ElevatedWriteEventNameStr); + _elevatedWriteEvent = new EventWaitHandle(false, EventResetMode.ManualReset, CoreKey.ElevatedWriteEventNameStr); } if (_elevatedRenameEvent == null) { - _elevatedRenameEvent = new EventWaitHandle(false, EventResetMode.ManualReset, SettingsKey.ElevatedRenameEventNameStr); + _elevatedRenameEvent = new EventWaitHandle(false, EventResetMode.ManualReset, CoreKey.ElevatedRenameEventNameStr); } - ApplicationSettingsStore.Write(SettingsKey.PackageSidStr, WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host.ToUpper()); - ApplicationSettingsStore.Write(SettingsKey.AppCenterInstallIdStr, (await AppCenter.GetInstallIdAsync())?.ToString()); + ApplicationSettingsStore.Write(CoreKey.PackageSidStr, WebAuthenticationBroker.GetCurrentApplicationCallbackUri().Host.ToUpper()); + ApplicationSettingsStore.Write(CoreKey.AppCenterInstallIdStr, (await AppCenter.GetInstallIdAsync())?.ToString()); await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync(); } @@ -108,7 +109,7 @@ public static async void UnblockFile(string filePath) if (!ShouldUseDesktopExtension) return; using (var pipeStream = new NamedPipeServerStream( - $"Local\\{SettingsKey.ExtensionUnblockPipeConnectionNameStr}", + $"Local\\{CoreKey.ExtensionUnblockPipeConnectionNameStr}", PipeDirection.Out, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, @@ -179,7 +180,7 @@ public static async Task SaveFileAsAdmin(string filePath, byte[] data) if (!ShouldUseDesktopExtension) return; using (var pipeStream = new NamedPipeServerStream( - $"Local\\{SettingsKey.ElevatedWritePipeConnectionNameStr}", + $"Local\\{CoreKey.ElevatedWritePipeConnectionNameStr}", PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, @@ -238,7 +239,7 @@ public static async Task RenameFileAsAdmin(StorageFile file, string if (!ShouldUseDesktopExtension) return null; using (var pipeStream = new NamedPipeServerStream( - $"Local\\{SettingsKey.ElevatedRenamePipeConnectionNameStr}", + $"Local\\{CoreKey.ElevatedRenamePipeConnectionNameStr}", PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Message, diff --git a/src/Notepads/Services/InterInstanceSyncService.cs b/src/Notepads/Services/InterInstanceSyncService.cs index 5210592b5..af595dc10 100644 --- a/src/Notepads/Services/InterInstanceSyncService.cs +++ b/src/Notepads/Services/InterInstanceSyncService.cs @@ -1,5 +1,6 @@ namespace Notepads.Services { + using Notepads.Core; using Notepads.Extensions; using Notepads.Settings; using Notepads.Views.MainPage; @@ -37,8 +38,8 @@ public static class InterInstanceSyncService { SettingsKey.EditorDefaultSearchEngineStr, AppSettingsService.InitializeSearchEngineSettings }, { SettingsKey.EditorEnableSmartCopyBool, AppSettingsService.InitializeSmartCopySettings }, { SettingsKey.AlwaysOpenNewWindowBool, AppSettingsService.InitializeAppOpeningPreferencesSettings }, - { SettingsKey.LaunchElevetedProcessFailedStr, DesktopExtensionService.OnElevetedProcessLaunchRequested }, - { SettingsKey.LaunchElevetedProcessSuccessStr, DesktopExtensionService.OnElevetedProcessLaunchRequested }, + { CoreKey.LaunchElevatedProcessFailedStr, DesktopExtensionService.OnElevetedProcessLaunchRequested }, + { CoreKey.LaunchElevatedProcessSuccessStr, DesktopExtensionService.OnElevetedProcessLaunchRequested }, { RecentFilesListKey, async (permission) => await _notepadsMainPage.BuildOpenRecentButtonSubItems(!permission) } }; @@ -50,25 +51,25 @@ public static void Initialize(NotepadsMainPage page) private static async void Application_OnDataChanged(ApplicationData sender, object args) { - if (ApplicationSettingsStore.Read(SettingsKey.LastChangedSettingsAppInstanceIdStr) is string lastChangedSettingsAppInstanceIdStr && + if (ApplicationSettingsStore.Read(CoreKey.LastChangedSettingsAppInstanceIdStr) is string lastChangedSettingsAppInstanceIdStr && lastChangedSettingsAppInstanceIdStr == App.Id.ToString()) { return; } - if (ApplicationSettingsStore.Read(SettingsKey.LastChangedSettingsKeyStr) is string lastChangedSettingsKeyStr && + if (ApplicationSettingsStore.Read(CoreKey.LastChangedSettingsKeyStr) is string lastChangedSettingsKeyStr && SyncManager.ContainsKey(lastChangedSettingsKeyStr) && _notepadsMainPage != null) { await DispatcherExtensions.CallOnUIThreadAsync(_notepadsMainPage.Dispatcher, () => { if (lastChangedSettingsKeyStr != RecentFilesListKey && - lastChangedSettingsKeyStr != SettingsKey.LaunchElevetedProcessSuccessStr && - lastChangedSettingsKeyStr != SettingsKey.LaunchElevetedProcessFailedStr) + lastChangedSettingsKeyStr != CoreKey.LaunchElevatedProcessSuccessStr && + lastChangedSettingsKeyStr != CoreKey.LaunchElevatedProcessFailedStr) { _notepadsMainPage.CloseSettingsPane(); } - if (lastChangedSettingsKeyStr == SettingsKey.LaunchElevetedProcessFailedStr) + if (lastChangedSettingsKeyStr == CoreKey.LaunchElevatedProcessFailedStr) { SyncManager[lastChangedSettingsKeyStr].Invoke(false); } diff --git a/src/Notepads/Settings/ApplicationSettings.cs b/src/Notepads/Settings/ApplicationSettings.cs index 8c5b785ef..537231590 100644 --- a/src/Notepads/Settings/ApplicationSettings.cs +++ b/src/Notepads/Settings/ApplicationSettings.cs @@ -1,6 +1,7 @@ namespace Notepads.Settings { using System; + using Notepads.Core; using Notepads.Services; using Windows.Storage; @@ -32,8 +33,8 @@ public static void SignalDataChanged(string key) { if (InterInstanceSyncService.SyncManager.ContainsKey(key)) { - _localSettings.Values[SettingsKey.LastChangedSettingsKeyStr] = key; - _localSettings.Values[SettingsKey.LastChangedSettingsAppInstanceIdStr] = App.Id.ToString(); + _localSettings.Values[CoreKey.LastChangedSettingsKeyStr] = key; + _localSettings.Values[CoreKey.LastChangedSettingsAppInstanceIdStr] = App.Id.ToString(); ApplicationData.Current.SignalDataChanged(); } } diff --git a/src/Notepads/Settings/SettingsKey.cs b/src/Notepads/Settings/SettingsKey.cs index 2d98ea225..3738f8288 100644 --- a/src/Notepads/Settings/SettingsKey.cs +++ b/src/Notepads/Settings/SettingsKey.cs @@ -34,24 +34,5 @@ internal static class SettingsKey internal const string EditorHighlightMisspelledWordsBool = "EditorHighlightMisspelledWordsBool"; internal const string EditorDefaultDisplayLineNumbersBool = "EditorDefaultDisplayLineNumbersBool"; internal const string EditorEnableSmartCopyBool = "EditorEnableSmartCopyBool"; - - // Interop related - // These values depend upon constant fields described in ..\Notepads.DesktopExtension\pch.h. - // Changing value in one place require changing variable with similar name in another. - internal const string AppCenterSecret = null; - internal const string PackageSidStr = "PackageSidStr"; - internal const string AppCenterInstallIdStr = "AppCenterInstallIdStr"; - internal const string LastChangedSettingsKeyStr = "LastChangedSettingsKeyStr"; - internal const string LastChangedSettingsAppInstanceIdStr = "LastChangedSettingsAppInstanceIdStr"; - internal const string LaunchElevetedProcessSuccessStr = "LaunchElevetedProcessSuccess"; - internal const string LaunchElevetedProcessFailedStr = "LaunchElevetedProcessFailed"; - internal const string ExtensionProcessLifetimeObjNameStr = "ExtensionProcessLifetimeObj"; - internal const string ElevatedProcessLifetimeObjNameStr = "ElevatedProcessLifetimeObj"; - internal const string ExtensionUnblockEventNameStr = "NotepadsExtensionUnblockEvent"; - internal const string ElevatedWriteEventNameStr = "NotepadsElevatedWriteEvent"; - internal const string ElevatedRenameEventNameStr = "NotepadsElevatedRenameEvent"; - internal const string ExtensionUnblockPipeConnectionNameStr = "NotepadsExtensionUnblockPipe"; - internal const string ElevatedWritePipeConnectionNameStr = "NotepadsElevatedWritePipe"; - internal const string ElevatedRenamePipeConnectionNameStr = "NotepadsElevatedRenamePipe"; } } \ No newline at end of file From 8de1086d435dacc422c98c7ab806f719a97db655 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Thu, 18 Feb 2021 19:57:55 +0530 Subject: [PATCH 153/181] Fixed CodeFactor issues. --- src/Notepads.Core/CoreKey.h | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/Notepads.Core/CoreKey.h b/src/Notepads.Core/CoreKey.h index 72fe99d73..7dd871509 100644 --- a/src/Notepads.Core/CoreKey.h +++ b/src/Notepads.Core/CoreKey.h @@ -27,8 +27,5 @@ namespace winrt::Notepads::Core::implementation namespace winrt::Notepads::Core::factory_implementation { - struct CoreKey : CoreKeyT - { - - }; + struct CoreKey : CoreKeyT { }; } \ No newline at end of file From 43583ee7226df432e7d82ab074908d4f4a21a3e7 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 26 Feb 2021 13:48:42 +0530 Subject: [PATCH 154/181] Refactor GitHub task. --- .github/workflows/Build.yml | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index e830198cb..38c39b858 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -24,16 +24,16 @@ jobs: - name: Setup MSBuild uses: microsoft/setup-msbuild@v1 - - name: Restore the application - run: msbuild $env:Solution_Name /t:Restore /p:Configuration=$env:Configuration - env: - Configuration: ${{ matrix.configuration }} - + # Add NuGet to the PATH: https://github.com/NuGet/setup-nuget - name: Setup NuGet uses: NuGet/setup-nuget@v1.0.5 - - name: Restore NuGet packages - run: nuget restore $env:Solution_Name + - name: Restore the application + run: | + msbuild $env:Solution_Name /t:Restore /p:Configuration=$env:Configuration + nuget restore $env:Solution_Name + env: + Configuration: ${{ matrix.configuration }} - name: Build run: | From 8c8fa4776ae7da7aac5bfd348a6fa1b772a12863 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sun, 28 Feb 2021 20:30:28 +0530 Subject: [PATCH 155/181] Provide default baseline for vcpkg manifest validation. --- src/Notepads.DesktopExtension/vcpkg.json | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Notepads.DesktopExtension/vcpkg.json b/src/Notepads.DesktopExtension/vcpkg.json index 9d3db4668..b6ba02dce 100644 --- a/src/Notepads.DesktopExtension/vcpkg.json +++ b/src/Notepads.DesktopExtension/vcpkg.json @@ -1,6 +1,7 @@ { "name": "notepads-desktopextension", "version": "1.0.0.0", + "builtin-baseline": "e25b620cf90d9bb311f91b03916b75d8798afd44", "dependencies": [ "boost-stacktrace", "curl", From 9ce996db180a5a1981bc67e25641843125c7b7b1 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 12 Mar 2021 16:21:00 +0530 Subject: [PATCH 156/181] Implement host triplet to fix cross compile. --- src/Notepads.Core/Notepads.Core.vcxproj | 10 ++++------ src/Notepads.Core/packages.config | 2 +- .../Notepads.DesktopExtension.vcxproj | 10 ++++++---- src/Notepads.DesktopExtension/packages.config | 2 +- src/Notepads.DesktopExtension/vcpkg.json | 8 ++++++-- 5 files changed, 18 insertions(+), 14 deletions(-) diff --git a/src/Notepads.Core/Notepads.Core.vcxproj b/src/Notepads.Core/Notepads.Core.vcxproj index 08aaa4055..29d561a33 100644 --- a/src/Notepads.Core/Notepads.Core.vcxproj +++ b/src/Notepads.Core/Notepads.Core.vcxproj @@ -1,6 +1,6 @@ - + 14.0 {022dc661-4fa2-4264-a869-5a560fb4cc92} @@ -150,19 +150,17 @@ - - - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - + + \ No newline at end of file diff --git a/src/Notepads.Core/packages.config b/src/Notepads.Core/packages.config index a6b596a22..6e14c903a 100644 --- a/src/Notepads.Core/packages.config +++ b/src/Notepads.Core/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index 6b30f3e00..5407d6f97 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -1,6 +1,6 @@ - + 15.0 {0a3b698e-6add-4c9e-9741-08f8ae576b2e} @@ -119,6 +119,8 @@ true true $(ProjectDir)$(BaseIntermediateOutputPath)$(Platform)\ + x86-windows + arm-windows @@ -199,7 +201,7 @@ - + @@ -215,7 +217,7 @@ This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - + + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/packages.config b/src/Notepads.DesktopExtension/packages.config index a6b596a22..6e14c903a 100644 --- a/src/Notepads.DesktopExtension/packages.config +++ b/src/Notepads.DesktopExtension/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/vcpkg.json b/src/Notepads.DesktopExtension/vcpkg.json index b6ba02dce..22a4aea9b 100644 --- a/src/Notepads.DesktopExtension/vcpkg.json +++ b/src/Notepads.DesktopExtension/vcpkg.json @@ -1,12 +1,16 @@ { "name": "notepads-desktopextension", "version": "1.0.0.0", - "builtin-baseline": "e25b620cf90d9bb311f91b03916b75d8798afd44", + "builtin-baseline": "75522bb1f2e7d863078bcd06322348f053a9e33f", "dependencies": [ "boost-stacktrace", "curl", "fmt", - "rapidjson" + "rapidjson", + { + "name": "boost-build", + "host": true + } ], "overrides": [ { From bd6261db9dfbcbbe40fe5146ec8d5be2cae21c59 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 12 Mar 2021 21:01:25 +0530 Subject: [PATCH 157/181] Implement vcpkg binary caching --- .github/workflows/Build.yml | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 38c39b858..173c98255 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -12,6 +12,9 @@ jobs: env: Solution_Name: src\Notepads.sln Project_Path: src\Notepads.Package\Notepads.Package.wapproj + Vcpkg_Path: src\packages\vcpkg + Vcpkg_Nuget_Package: ${{ github.repository_owner }}-${{ github.event.repository.name }} + VCPKG_BINARY_SOURCES: 'clear;nuget,${{ env.Vcpkg_Nuget_Package }},readwrite' runs-on: windows-latest steps: @@ -34,6 +37,19 @@ jobs: nuget restore $env:Solution_Name env: Configuration: ${{ matrix.configuration }} + + - name: 'Setup Vcpkg Binary Caching' + shell: 'pwsh' + run: | + $($env:Vcpkg_Nuget_Package\vcpkg fetch nuget | select -last 1) sources add ` + -source "https://nuget.pkg.github.com/$env:OWNER/index.json" ` + -storepasswordincleartext ` + -name "$env:Vcpkg_Nuget_Package" ` + -username "$env:OWNER" ` + -password "$env:PAT" + env: + OWNER: ${{ github.repository_owner }} + PAT: ${{ secrets.GITHUB_TOKEN }} - name: Build run: | From a20a8da768c2ab4a8cc04f8542296951d36e7247 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 12 Mar 2021 21:07:28 +0530 Subject: [PATCH 158/181] Removed empty spaces --- .github/workflows/Build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 173c98255..c0fbda0b3 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -37,7 +37,7 @@ jobs: nuget restore $env:Solution_Name env: Configuration: ${{ matrix.configuration }} - + - name: 'Setup Vcpkg Binary Caching' shell: 'pwsh' run: | From 5bd5d3c198f8a94f71b8e18b69f924cd75c90f91 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 12 Mar 2021 21:20:08 +0530 Subject: [PATCH 159/181] Fix workflow failing --- .github/workflows/Build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index c0fbda0b3..cee5248bf 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -14,7 +14,7 @@ jobs: Project_Path: src\Notepads.Package\Notepads.Package.wapproj Vcpkg_Path: src\packages\vcpkg Vcpkg_Nuget_Package: ${{ github.repository_owner }}-${{ github.event.repository.name }} - VCPKG_BINARY_SOURCES: 'clear;nuget,${{ env.Vcpkg_Nuget_Package }},readwrite' + VCPKG_BINARY_SOURCES: 'clear;nuget,$env:Vcpkg_Nuget_Package,readwrite' runs-on: windows-latest steps: From 406b0528fdeaef6050efc80cfd88c27e74b9d3d8 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 12 Mar 2021 21:31:06 +0530 Subject: [PATCH 160/181] Fix github workflow --- .github/workflows/Build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index cee5248bf..fe9ccd88a 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -41,7 +41,7 @@ jobs: - name: 'Setup Vcpkg Binary Caching' shell: 'pwsh' run: | - $($env:Vcpkg_Nuget_Package\vcpkg fetch nuget | select -last 1) sources add ` + $($env:Vcpkg_Path\vcpkg fetch nuget | select -last 1) sources add ` -source "https://nuget.pkg.github.com/$env:OWNER/index.json" ` -storepasswordincleartext ` -name "$env:Vcpkg_Nuget_Package" ` From eec7a515b390019ec4abd365a983e88d3bda6266 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 13 Mar 2021 09:22:38 +0530 Subject: [PATCH 161/181] Fix Github workflow. --- .github/workflows/Build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index fe9ccd88a..437f22535 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -14,7 +14,7 @@ jobs: Project_Path: src\Notepads.Package\Notepads.Package.wapproj Vcpkg_Path: src\packages\vcpkg Vcpkg_Nuget_Package: ${{ github.repository_owner }}-${{ github.event.repository.name }} - VCPKG_BINARY_SOURCES: 'clear;nuget,$env:Vcpkg_Nuget_Package,readwrite' + VCPKG_BINARY_SOURCES: 'clear;nuget,${{ github.repository_owner }}-${{ github.event.repository.name }},readwrite' runs-on: windows-latest steps: @@ -41,7 +41,7 @@ jobs: - name: 'Setup Vcpkg Binary Caching' shell: 'pwsh' run: | - $($env:Vcpkg_Path\vcpkg fetch nuget | select -last 1) sources add ` + $(src\packages\vcpkg\vcpkg fetch nuget | select -last 1) sources add ` -source "https://nuget.pkg.github.com/$env:OWNER/index.json" ` -storepasswordincleartext ` -name "$env:Vcpkg_Nuget_Package" ` From 6874bd9b5e1be214a5c8893246645609c70cee0f Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 13 Mar 2021 09:29:36 +0530 Subject: [PATCH 162/181] Fix Github workflow --- .github/workflows/Build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 437f22535..eb0921499 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -41,7 +41,7 @@ jobs: - name: 'Setup Vcpkg Binary Caching' shell: 'pwsh' run: | - $(src\packages\vcpkg\vcpkg fetch nuget | select -last 1) sources add ` + & $(src\packages\vcpkg\vcpkg fetch nuget | select -last 1) sources add ` -source "https://nuget.pkg.github.com/$env:OWNER/index.json" ` -storepasswordincleartext ` -name "$env:Vcpkg_Nuget_Package" ` From a81145022b17c2a11e0e885682db98be4c35d6d9 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 13 Mar 2021 10:00:30 +0530 Subject: [PATCH 163/181] Refactor github workflow. --- .github/workflows/Build.yml | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index eb0921499..010a14fb3 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -12,7 +12,6 @@ jobs: env: Solution_Name: src\Notepads.sln Project_Path: src\Notepads.Package\Notepads.Package.wapproj - Vcpkg_Path: src\packages\vcpkg Vcpkg_Nuget_Package: ${{ github.repository_owner }}-${{ github.event.repository.name }} VCPKG_BINARY_SOURCES: 'clear;nuget,${{ github.repository_owner }}-${{ github.event.repository.name }},readwrite' @@ -50,10 +49,17 @@ jobs: env: OWNER: ${{ github.repository_owner }} PAT: ${{ secrets.GITHUB_TOKEN }} + Vcpkg_Path: src\packages\vcpkg - name: Build + shell: 'pwsh' run: | - msbuild $env:Project_Path /p:Configuration=$env:Configuration /p:UapAppxPackageBuildMode=$env:Appx_Package_Build_Mode /p:AppxBundle=$env:Appx_Bundle /p:AppxPackageSigningEnabled=false /p:AppxBundlePlatforms="$env:Appx_Bundle_Platforms" + msbuild $env:Project_Path ` + /p:Configuration=$env:Configuration ` + /p:UapAppxPackageBuildMode=$env:Appx_Package_Build_Mode ` + /p:AppxBundle=$env:Appx_Bundle ` + /p:AppxPackageSigningEnabled=false ` + /p:AppxBundlePlatforms="$env:Appx_Bundle_Platforms" env: Appx_Bundle: Always Appx_Bundle_Platforms: x86|x64 From 72152a26731f3ece2613f05ae78f69341072e8c2 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 13 Mar 2021 10:38:25 +0530 Subject: [PATCH 164/181] Refactor github workflow. --- .github/workflows/Build.yml | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 010a14fb3..8b88b4843 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -12,8 +12,6 @@ jobs: env: Solution_Name: src\Notepads.sln Project_Path: src\Notepads.Package\Notepads.Package.wapproj - Vcpkg_Nuget_Package: ${{ github.repository_owner }}-${{ github.event.repository.name }} - VCPKG_BINARY_SOURCES: 'clear;nuget,${{ github.repository_owner }}-${{ github.event.repository.name }},readwrite' runs-on: windows-latest steps: @@ -32,10 +30,8 @@ jobs: - name: Restore the application run: | - msbuild $env:Solution_Name /t:Restore /p:Configuration=$env:Configuration + msbuild $env:Solution_Name /t:Restore nuget restore $env:Solution_Name - env: - Configuration: ${{ matrix.configuration }} - name: 'Setup Vcpkg Binary Caching' shell: 'pwsh' @@ -50,6 +46,7 @@ jobs: OWNER: ${{ github.repository_owner }} PAT: ${{ secrets.GITHUB_TOKEN }} Vcpkg_Path: src\packages\vcpkg + Vcpkg_Nuget_Package: ${{ github.repository_owner }}-${{ github.event.repository.name }} - name: Build shell: 'pwsh' @@ -65,3 +62,4 @@ jobs: Appx_Bundle_Platforms: x86|x64 Appx_Package_Build_Mode: StoreUpload Configuration: ${{ matrix.configuration }} + VCPKG_BINARY_SOURCES: 'clear;nuget,${{ github.repository_owner }}-${{ github.event.repository.name }},readwrite' From 4336e8b271540e2bb9216e9bc03cd10fbdae745d Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 13 Mar 2021 11:15:40 +0530 Subject: [PATCH 165/181] Refactor github workflow. --- .github/workflows/Build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 8b88b4843..e3585d9cb 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -12,6 +12,7 @@ jobs: env: Solution_Name: src\Notepads.sln Project_Path: src\Notepads.Package\Notepads.Package.wapproj + Vcpkg_Nuget_Package: ${{ github.repository_owner }}-${{ github.event.repository.name }} runs-on: windows-latest steps: @@ -46,7 +47,6 @@ jobs: OWNER: ${{ github.repository_owner }} PAT: ${{ secrets.GITHUB_TOKEN }} Vcpkg_Path: src\packages\vcpkg - Vcpkg_Nuget_Package: ${{ github.repository_owner }}-${{ github.event.repository.name }} - name: Build shell: 'pwsh' @@ -62,4 +62,4 @@ jobs: Appx_Bundle_Platforms: x86|x64 Appx_Package_Build_Mode: StoreUpload Configuration: ${{ matrix.configuration }} - VCPKG_BINARY_SOURCES: 'clear;nuget,${{ github.repository_owner }}-${{ github.event.repository.name }},readwrite' + VCPKG_BINARY_SOURCES: 'clear;nuget,${{ env.Vcpkg_Nuget_Package }},readwrite' From efd25ba2f8d24c37d23c149363adefe351e5d348 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 13 Mar 2021 11:49:03 +0530 Subject: [PATCH 166/181] Refactor github task. --- .github/workflows/Build.yml | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index e3585d9cb..4a4785fad 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -30,6 +30,7 @@ jobs: uses: NuGet/setup-nuget@v1.0.5 - name: Restore the application + shell: 'pwsh' run: | msbuild $env:Solution_Name /t:Restore nuget restore $env:Solution_Name @@ -37,16 +38,16 @@ jobs: - name: 'Setup Vcpkg Binary Caching' shell: 'pwsh' run: | - & $(src\packages\vcpkg\vcpkg fetch nuget | select -last 1) sources add ` - -source "https://nuget.pkg.github.com/$env:OWNER/index.json" ` + & $($env:Vcpkg_Path fetch nuget | select -last 1) sources add ` + -source "https://nuget.pkg.github.com/$env:Owner/index.json" ` -storepasswordincleartext ` -name "$env:Vcpkg_Nuget_Package" ` - -username "$env:OWNER" ` - -password "$env:PAT" + -username "$env:Owner" ` + -password "$env:Key" env: - OWNER: ${{ github.repository_owner }} - PAT: ${{ secrets.GITHUB_TOKEN }} - Vcpkg_Path: src\packages\vcpkg + Owner: ${{ github.repository_owner }} + Key: ${{ secrets.GITHUB_TOKEN }} + Vcpkg_Path: src\packages\vcpkg\vcpkg - name: Build shell: 'pwsh' From d50403f1925e1229b0e91e53fffb32f57d8c8c00 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 13 Mar 2021 12:19:31 +0530 Subject: [PATCH 167/181] Refactor Github workflow. --- .github/workflows/Build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 4a4785fad..5798c2a3c 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -38,7 +38,7 @@ jobs: - name: 'Setup Vcpkg Binary Caching' shell: 'pwsh' run: | - & $($env:Vcpkg_Path fetch nuget | select -last 1) sources add ` + & $(& $env:Vcpkg_Path fetch nuget | select -last 1) sources add ` -source "https://nuget.pkg.github.com/$env:Owner/index.json" ` -storepasswordincleartext ` -name "$env:Vcpkg_Nuget_Package" ` From e6affaa1c4f97abc2b2e851870511baac5a4f094 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 13 Mar 2021 13:30:21 +0530 Subject: [PATCH 168/181] Update nuget packages. --- src/Notepads.Core/Notepads.Core.vcxproj | 8 ++++---- src/Notepads.Core/packages.config | 2 +- .../Notepads.DesktopExtension.vcxproj | 8 ++++---- src/Notepads.DesktopExtension/packages.config | 2 +- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Notepads.Core/Notepads.Core.vcxproj b/src/Notepads.Core/Notepads.Core.vcxproj index 29d561a33..c5d10b8be 100644 --- a/src/Notepads.Core/Notepads.Core.vcxproj +++ b/src/Notepads.Core/Notepads.Core.vcxproj @@ -1,6 +1,6 @@ - + 14.0 {022dc661-4fa2-4264-a869-5a560fb4cc92} @@ -154,13 +154,13 @@ - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - + + \ No newline at end of file diff --git a/src/Notepads.Core/packages.config b/src/Notepads.Core/packages.config index 6e14c903a..c7a3eef2f 100644 --- a/src/Notepads.Core/packages.config +++ b/src/Notepads.Core/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index 5407d6f97..63681438e 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -1,6 +1,6 @@ - + 15.0 {0a3b698e-6add-4c9e-9741-08f8ae576b2e} @@ -201,7 +201,7 @@ - + @@ -217,7 +217,7 @@ This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - + + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/packages.config b/src/Notepads.DesktopExtension/packages.config index 6e14c903a..c7a3eef2f 100644 --- a/src/Notepads.DesktopExtension/packages.config +++ b/src/Notepads.DesktopExtension/packages.config @@ -1,4 +1,4 @@  - + \ No newline at end of file From feaf0c3f67c59b6d94f8cb41395d8554e8ddb344 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sun, 14 Mar 2021 12:22:54 +0530 Subject: [PATCH 169/181] Implemented vcpkg use Nuget cache. --- .github/workflows/Build.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 5798c2a3c..519a2ce6d 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -64,3 +64,4 @@ jobs: Appx_Package_Build_Mode: StoreUpload Configuration: ${{ matrix.configuration }} VCPKG_BINARY_SOURCES: 'clear;nuget,${{ env.Vcpkg_Nuget_Package }},readwrite' + VCPKG_USE_NUGET_CACHE: 'true' \ No newline at end of file From b9a2960967c7f6ad2711d4fc6b863a97d01dbefc Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sun, 14 Mar 2021 12:52:50 +0530 Subject: [PATCH 170/181] Fix Github package upload. --- .github/workflows/Build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 519a2ce6d..9f3243f2d 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -63,5 +63,5 @@ jobs: Appx_Bundle_Platforms: x86|x64 Appx_Package_Build_Mode: StoreUpload Configuration: ${{ matrix.configuration }} - VCPKG_BINARY_SOURCES: 'clear;nuget,${{ env.Vcpkg_Nuget_Package }},readwrite' + VCPKG_BINARY_SOURCES: 'clear;nuget,${{ env.Vcpkg_Nuget_Package }},readwrite;interactive' VCPKG_USE_NUGET_CACHE: 'true' \ No newline at end of file From 00f083620ac651dc4e04fdbb54f198a924ab23b1 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sun, 14 Mar 2021 14:46:08 +0530 Subject: [PATCH 171/181] Fix failing to upload to Github packages. --- .github/workflows/Build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 9f3243f2d..4167c0036 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -45,7 +45,7 @@ jobs: -username "$env:Owner" ` -password "$env:Key" env: - Owner: ${{ github.repository_owner }} + Owner: ${{ github.actor }} Key: ${{ secrets.GITHUB_TOKEN }} Vcpkg_Path: src\packages\vcpkg\vcpkg From e0bd174de81a3537b1d9ba114d1f95ef409f9f55 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sun, 14 Mar 2021 15:14:01 +0530 Subject: [PATCH 172/181] Change username to repository owner. --- .github/workflows/Build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 4167c0036..9f3243f2d 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -45,7 +45,7 @@ jobs: -username "$env:Owner" ` -password "$env:Key" env: - Owner: ${{ github.actor }} + Owner: ${{ github.repository_owner }} Key: ${{ secrets.GITHUB_TOKEN }} Vcpkg_Path: src\packages\vcpkg\vcpkg From 851a30e88a7f443d43cd6563c3008875d91fb0e5 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Tue, 20 Apr 2021 15:16:39 +0530 Subject: [PATCH 173/181] chore: move more methods to winrt --- src/Notepads.DesktopExtension/extension.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/Notepads.DesktopExtension/extension.cpp b/src/Notepads.DesktopExtension/extension.cpp index 7f67cdd3f..85fc22e78 100644 --- a/src/Notepads.DesktopExtension/extension.cpp +++ b/src/Notepads.DesktopExtension/extension.cpp @@ -43,9 +43,8 @@ DWORD WINAPI unblockFileFromPipeData(LPVOID /* param */) } while (byteRead >= (PIPE_READ_BUFFER - 1) * sizeof(TCHAR)); hstring filePath(pipeData.str()); - com_ptr pFile; - if (SUCCEEDED(CoCreateInstance(CLSID_PersistentZoneIdentifier, 0, CLSCTX_ALL, __uuidof(pFile), pFile.put_void())) && - SUCCEEDED(pFile->Load(filePath.c_str(), STGM_READWRITE))) + com_ptr pFile = create_instance(CLSID_PersistentZoneIdentifier); + if (SUCCEEDED(pFile->Load(filePath.c_str(), STGM_READWRITE))) { LPTSTR lastWriterPackageFamilyName; if (SUCCEEDED(pFile.as()->GetLastWriterPackageFamilyName(&lastWriterPackageFamilyName)) && @@ -83,7 +82,7 @@ VOID launchElevatedProcess() GetModuleFileName(NULL, fileName, MAX_PATH); SHELLEXECUTEINFO shExInfo - { + { .cbSize = sizeof(shExInfo), .fMask = SEE_MASK_NOCLOSEPROCESS, .hwnd = 0, From 4a62549ded67052f60d12645c897e325bfdd4c94 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 22 May 2021 17:07:53 +0530 Subject: [PATCH 174/181] chore: code refactor --- src/Notepads.Core/CoreKey.cpp | 5 - src/Notepads.Core/CoreKey.h | 1 - src/Notepads.Core/CoreKey.idl | 1 - src/Notepads.Core/pch.h | 1 - src/Notepads.DesktopExtension/.gitignore | 3 - src/Notepads.DesktopExtension/AssemblyInfo.rc | 21 +- .../Notepads.DesktopExtension.vcxproj | 47 ++- .../Notepads.DesktopExtension.vcxproj.filters | 51 ++- src/Notepads.DesktopExtension/appcenter.cpp | 162 --------- src/Notepads.DesktopExtension/appcenter.h | 103 +++++- src/Notepads.DesktopExtension/build.ps1 | 11 - src/Notepads.DesktopExtension/curl_client.h | 73 ++++ src/Notepads.DesktopExtension/device.h | 259 +++++++------- src/Notepads.DesktopExtension/elevated.cpp | 331 +++++++++--------- src/Notepads.DesktopExtension/error.h | 265 ++++++++++++++ .../error_attachment_report.h | 73 ++++ src/Notepads.DesktopExtension/error_report.h | 42 +++ src/Notepads.DesktopExtension/event_report.h | 66 ++++ src/Notepads.DesktopExtension/exception.h | 114 ------ src/Notepads.DesktopExtension/extension.cpp | 304 +++++++++------- src/Notepads.DesktopExtension/frame.h | 177 ++++++++++ .../handled_error_report.h | 65 ++++ src/Notepads.DesktopExtension/log.h | 217 ------------ src/Notepads.DesktopExtension/logger.h | 93 +++++ src/Notepads.DesktopExtension/main.cpp | 122 +++---- .../managed_error_report.h | 82 +++++ src/Notepads.DesktopExtension/pch.cpp | 135 +------ src/Notepads.DesktopExtension/pch.h | 60 ++-- src/Notepads.DesktopExtension/report.h | 128 +++++++ src/Notepads.DesktopExtension/resource.h | 17 - src/Notepads.DesktopExtension/settings_key.h | 29 ++ src/Notepads.DesktopExtension/vcpkg.json | 11 +- src/Notepads/App.xaml.cs | 6 +- src/Notepads/Utilities/FileSystemUtility.cs | 4 +- 34 files changed, 1820 insertions(+), 1259 deletions(-) delete mode 100644 src/Notepads.DesktopExtension/.gitignore delete mode 100644 src/Notepads.DesktopExtension/appcenter.cpp delete mode 100644 src/Notepads.DesktopExtension/build.ps1 create mode 100644 src/Notepads.DesktopExtension/curl_client.h create mode 100644 src/Notepads.DesktopExtension/error.h create mode 100644 src/Notepads.DesktopExtension/error_attachment_report.h create mode 100644 src/Notepads.DesktopExtension/error_report.h create mode 100644 src/Notepads.DesktopExtension/event_report.h delete mode 100644 src/Notepads.DesktopExtension/exception.h create mode 100644 src/Notepads.DesktopExtension/frame.h create mode 100644 src/Notepads.DesktopExtension/handled_error_report.h delete mode 100644 src/Notepads.DesktopExtension/log.h create mode 100644 src/Notepads.DesktopExtension/logger.h create mode 100644 src/Notepads.DesktopExtension/managed_error_report.h create mode 100644 src/Notepads.DesktopExtension/report.h delete mode 100644 src/Notepads.DesktopExtension/resource.h create mode 100644 src/Notepads.DesktopExtension/settings_key.h diff --git a/src/Notepads.Core/CoreKey.cpp b/src/Notepads.Core/CoreKey.cpp index f36dd13de..e5da6b707 100644 --- a/src/Notepads.Core/CoreKey.cpp +++ b/src/Notepads.Core/CoreKey.cpp @@ -4,11 +4,6 @@ namespace winrt::Notepads::Core::implementation { - hstring CoreKey::AppCenterSecret() - { - return APP_CENTER_SECRET; - } - hstring CoreKey::PackageSidStr() { return PACKAGE_SID_STR; diff --git a/src/Notepads.Core/CoreKey.h b/src/Notepads.Core/CoreKey.h index 7dd871509..ad05ed893 100644 --- a/src/Notepads.Core/CoreKey.h +++ b/src/Notepads.Core/CoreKey.h @@ -7,7 +7,6 @@ namespace winrt::Notepads::Core::implementation { CoreKey() = default; - static hstring AppCenterSecret(); static hstring PackageSidStr(); static hstring AppCenterInstallIdStr(); static hstring LastChangedSettingsKeyStr(); diff --git a/src/Notepads.Core/CoreKey.idl b/src/Notepads.Core/CoreKey.idl index 0636259a1..02ef83077 100644 --- a/src/Notepads.Core/CoreKey.idl +++ b/src/Notepads.Core/CoreKey.idl @@ -3,7 +3,6 @@ namespace Notepads.Core [default_interface] static runtimeclass CoreKey { - static String AppCenterSecret { get; }; static String PackageSidStr { get; }; static String AppCenterInstallIdStr { get; }; static String LastChangedSettingsKeyStr { get; }; diff --git a/src/Notepads.Core/pch.h b/src/Notepads.Core/pch.h index d7ceb0c61..76e833a70 100644 --- a/src/Notepads.Core/pch.h +++ b/src/Notepads.Core/pch.h @@ -1,7 +1,6 @@ #pragma once #include "winrt/base.h" -#define APP_CENTER_SECRET L"" #define PACKAGE_SID_STR L"PackageSidStr" #define APP_CENTER_INSTALL_ID_STR L"AppCenterInstallIdStr" #define LAST_CHANGED_SETTINGS_KEY_STR L"LastChangedSettingsKeyStr" diff --git a/src/Notepads.DesktopExtension/.gitignore b/src/Notepads.DesktopExtension/.gitignore deleted file mode 100644 index d516abcb1..000000000 --- a/src/Notepads.DesktopExtension/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -# AppCenter version file # -########################## -appcenter-sdk-version.txt \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/AssemblyInfo.rc b/src/Notepads.DesktopExtension/AssemblyInfo.rc index 7ee16b2c8..c8032a45e 100644 --- a/src/Notepads.DesktopExtension/AssemblyInfo.rc +++ b/src/Notepads.DesktopExtension/AssemblyInfo.rc @@ -1,6 +1,13 @@ // Microsoft Visual C++ generated resource script. // -#include "resource.h" +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 101 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 103 +#endif +#endif #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// @@ -41,13 +48,8 @@ BEGIN BEGIN BLOCK "000004b0" BEGIN -#ifdef _PRODUCTION - VALUE "FileDescription", "Notepads" - VALUE "ProductName", "Notepads" -#else VALUE "FileDescription", "Notepads-Dev" VALUE "ProductName", "Notepads-Dev" -#endif VALUE "FileVersion", "1.0.0.0" VALUE "InternalName", "Notepads.DesktopExtension" VALUE "LegalCopyright", "Copyright 2020 Jackie Liu" @@ -61,12 +63,5 @@ BEGIN END END -///////////////////////////////////////////////////////////////////////////// -// -// Text File -// - -APPCENTER_SDK_VERSION TEXTFILE "appcenter-sdk-version.txt" - #endif // Neutral resources ///////////////////////////////////////////////////////////////////////////// \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index 63681438e..332b1af18 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -132,9 +132,6 @@ %(AdditionalOptions) /permissive- /bigobj stdcpplatest - - powershell -ExecutionPolicy Unrestricted $(ProjectDir)build.ps1 -project_dir $(ProjectDir) - @@ -171,13 +168,20 @@ - - + + + + + + + + + + - + - @@ -186,7 +190,6 @@ - @@ -220,4 +223,32 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters index b2459d4ef..7aa4019f0 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters @@ -13,9 +13,6 @@ {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - {de4d9f33-9346-4bce-97fe-469f12bf39a5} - @@ -27,9 +24,6 @@ Source Files - - AppCenter - Source Files @@ -38,27 +32,48 @@ Header Files - + Header Files - - AppCenter + + Header Files - - AppCenter + + Header Files - - AppCenter + + Header Files + + + Header Files - - AppCenter + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files - - Resource Files - diff --git a/src/Notepads.DesktopExtension/appcenter.cpp b/src/Notepads.DesktopExtension/appcenter.cpp deleted file mode 100644 index f7bae8c7f..000000000 --- a/src/Notepads.DesktopExtension/appcenter.cpp +++ /dev/null @@ -1,162 +0,0 @@ -// Documentation is at https://docs.microsoft.com/en-us/appcenter/diagnostics/upload-crashes -#include "pch.h" -#include "appcenter.h" -#include "log.h" -#include "rapidjson/stringbuffer.h" - -#define APPCENTER_ENDPOINT "https://in.appcenter.ms/logs?Api-Version=1.0.0" - -using namespace fmt; -using namespace rapidjson; -using namespace std; -using namespace winrt; -using namespace AppCenter; -using namespace Windows::ApplicationModel; -using namespace Windows::Storage; -using namespace Windows::System; - -IInspectable readSettingsKey(hstring key) -{ - return ApplicationData::Current().LocalSettings().Values().TryLookup(key); -} - -VOID AppCenter::start() -{ - if (!AppCenterSecret || wcslen(AppCenterSecret) == 0) return; - - hstring installId = unbox_value_or(readSettingsKey(AppCenterInstallIdStr), L""); - if (installId.empty()) return; - - if (!headerList) - { - headerList = curl_slist_append(headerList, "Content-Type: application/json"); - headerList = curl_slist_append(headerList, format("app-secret: {}", to_string(AppCenterSecret)).c_str()); - headerList = curl_slist_append(headerList, format("install-id: {}", to_string(installId)).c_str()); - } - - if (!deviceInfo) - { - deviceInfo = new Device(); - } -} - -VOID AppCenter::trackError(bool isFatal, DWORD errorCode, const string& message, const stacktrace& stackTrace) -{ - if (!headerList) return; - - TCHAR locale[LOCALE_NAME_MAX_LENGTH + 1]; - LCIDToLocaleName(GetThreadLocale(), locale, LOCALE_NAME_MAX_LENGTH, 0); - TCHAR localeDisplayName[LOCALE_NAME_MAX_LENGTH + 1]; - GetLocaleInfoEx(locale, LOCALE_SENGLISHDISPLAYNAME, localeDisplayName, LOCALE_NAME_MAX_LENGTH); - - string isElevated = isElevatedProcess() ? "True" : "False"; - string eventType = isFatal ? "OnWin32UnhandledException" : "OnWin32UnexpectedException"; - - string attachmentData = base64_encode(format("Exception: Win32Exception code no. {}\nMessage: {}\nIsDesktopExtension: True, IsElevated: {}", - errorCode, message, isElevated)); - - vector> properties - { - pair("Exception", format("Win32Exception: Exception of code no. {} was thrown.", errorCode)), - pair("Message", message), - pair("Culture", to_string(localeDisplayName)), - pair("AvailableMemory", to_string((FLOAT)MemoryManager::AppMemoryUsageLimit() / 1024 / 1024)), - pair("FirstUseTimeUTC", getTimeStamp("%m/%d/%Y %T")), - pair("OSArchitecture", to_string(Package::Current().Id().Architecture())), - pair("OSVersion", deviceInfo->getOsVersion()), - pair("IsDesktopExtension", "True"), - pair("IsElevated", isElevated) - }; - - vector errorReportSet - { - Log(LogType::managedError, isFatal, new Exception(message, stackTrace)), - Log(LogType::handledError, isFatal, new Exception(message), properties) - }; - errorReportSet.insert(errorReportSet.end(), - { - Log(LogType::errorAttachment, errorReportSet[0].Id(), attachmentData), - Log(LogType::errorAttachment, errorReportSet[1].Id(), attachmentData), - Log(LogType::event, errorReportSet[0].Sid(), eventType, properties) - }); - - StringBuffer errorReport; -#ifdef _DEBUG - PrettyWriter writer(errorReport); -#else - Writer writer(errorReport); -#endif - - writer.StartObject(); - writer.String("logs"); - writer.StartArray(); - for (vector::const_iterator report = errorReportSet.begin(); report != errorReportSet.end(); ++report) - { - report->Serialize(writer); - } - writer.EndArray(); - writer.EndObject(); - - CURL* curl = curl_easy_init(); - if (curl) - { - curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerList); - curl_easy_setopt(curl, CURLOPT_URL, APPCENTER_ENDPOINT); - curl_easy_setopt(curl, CURLOPT_POSTFIELDS, errorReport.GetString()); - -#ifdef _DEBUG - curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); -#endif - - CURLcode res = curl_easy_perform(curl); - if (res != CURLE_OK) - { - printDebugMessage(format(L"curl_easy_perform() failed: {}", to_hstring(curl_easy_strerror(res))).c_str()); - } - } - curl_easy_cleanup(curl); -} - -VOID AppCenter::trackEvent(const string& name, const vector>& properties, const string& sid) -{ - if (!headerList) return; - - StringBuffer eventReport; -#ifdef _DEBUG - PrettyWriter writer(eventReport); -#else - Writer writer(eventReport); -#endif - - writer.StartObject(); - writer.String("logs"); - writer.StartArray(); - Log(LogType::event, sid, name, properties).Serialize(writer); - writer.EndArray(); - writer.EndObject(); - - CURL* curl = curl_easy_init(); - if (curl) - { - curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerList); - curl_easy_setopt(curl, CURLOPT_URL, APPCENTER_ENDPOINT); - curl_easy_setopt(curl, CURLOPT_POSTFIELDS, eventReport.GetString()); - -#ifdef _DEBUG - curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); -#endif - - CURLcode res = curl_easy_perform(curl); - if (res != CURLE_OK) - { - printDebugMessage(format(L"curl_easy_perform() failed: {}", to_hstring(curl_easy_strerror(res))).c_str()); - } - } - curl_easy_cleanup(curl); -} - -VOID AppCenter::exit() -{ - if (headerList) LocalFree(headerList); - if (deviceInfo) LocalFree(deviceInfo); -} \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/appcenter.h b/src/Notepads.DesktopExtension/appcenter.h index 2899ac494..c35054c22 100644 --- a/src/Notepads.DesktopExtension/appcenter.h +++ b/src/Notepads.DesktopExtension/appcenter.h @@ -1,25 +1,96 @@ #pragma once #include "pch.h" -#include "curl/curl.h" +#include "error.h" +#include "device.h" +#include "curl_client.h" +#include "error_report.h" +#include "event_report.h" +#include "settings_key.h" +#include "rapidjson/stringbuffer.h" -#ifdef _DEBUG -#include "rapidjson/prettywriter.h" -#else -#include "rapidjson/writer.h" -#endif +// Documentation is at https://docs.microsoft.com/en-us/appcenter/diagnostics/upload-crashes +#define APP_CENTER_ENDPOINT "https://in.appcenter.ms/logs?Api-Version=1.0.0" -namespace AppCenter +__declspec(selectany) curl_slist_handle header { nullptr }; + +struct appcenter { - using namespace boost::stacktrace; - using namespace std; + static void start() noexcept + { + if (!APP_CENTER_SECRET || strlen(APP_CENTER_SECRET) == 0) return; + + auto install_id = winrt::unbox_value_or(settings_key::read(APP_CENTER_INSTALL_ID_STR), L""); + if (install_id.empty()) return; + + struct curl_slist* slist = nullptr; + slist = curl_slist_append(slist, "Content-Type: application/json"); + slist = curl_slist_append(slist, fmt::format("app-secret: {}", APP_CENTER_SECRET).c_str()); + slist = curl_slist_append(slist, fmt::format("install-id: {}", winrt::to_string(install_id)).c_str()); + header.attach(slist); + } + +private: - namespace + appcenter() noexcept = default; + appcenter(appcenter&&) noexcept = default; + appcenter(appcenter const& other) noexcept = default; +}; + +struct crashes +{ + static void track_error( + winrt_error const& error, + report::dictionary const& properties, + std::string const& attachment = "" + ) noexcept { - static struct curl_slist* headerList = NULL; + if (!header) return; + + rapidjson::StringBuffer report; + report::json_writer writer(report); + + writer.StartObject(); + writer.String("logs"); + writer.StartArray(); + error_report(error, properties, attachment).serialize(writer); + writer.EndArray(); + writer.EndObject(); + + curl_client::post(APP_CENTER_ENDPOINT, header, report.GetString()); } - VOID start(); - VOID trackError(bool isFatal, DWORD errorCode, const string& message, const stacktrace& stackTrace); - VOID trackEvent(const string& name, const vector>& properties, const string& sid = ""); - VOID exit(); -} \ No newline at end of file +private: + + crashes() noexcept = default; + crashes(crashes&&) noexcept = default; + crashes(crashes const& other) noexcept = default; +}; + +struct analytics +{ + static void track_event( + std::string const& name, + report::dictionary const& properties + ) noexcept + { + if (!header) return; + + rapidjson::StringBuffer report; + report::json_writer writer(report); + + writer.StartObject(); + writer.String("logs"); + writer.StartArray(); + event_report(name, properties).serialize(writer); + writer.EndArray(); + writer.EndObject(); + + curl_client::post(APP_CENTER_ENDPOINT, header, report.GetString()); + } + +private: + + analytics() noexcept = default; + analytics(analytics&&) noexcept = default; + analytics(analytics const& other) noexcept = default; +}; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/build.ps1 b/src/Notepads.DesktopExtension/build.ps1 deleted file mode 100644 index 616b1c351..000000000 --- a/src/Notepads.DesktopExtension/build.ps1 +++ /dev/null @@ -1,11 +0,0 @@ -param ( - [string]$project_dir = $(throw "-project_dir= is required") -) - -$project_dir = Resolve-Path $project_dir.TrimEnd("\") -$appcenter_file = "${project_dir}\appcenter-sdk-version.txt" -$uwp_project_file = "${project_dir}\..\Notepads\Notepads.csproj" - -# Keep appcenter sdk version same as AppCenter nuget package version -[xml]$sdk_target = Get-Content $uwp_project_file -$sdk_target.Project.ItemGroup.PackageReference | ForEach-Object {if($_.Include -eq 'Microsoft.AppCenter.Crashes'){$_.Version | Set-Content $appcenter_file -NoNewline}} \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/curl_client.h b/src/Notepads.DesktopExtension/curl_client.h new file mode 100644 index 000000000..b0807f21d --- /dev/null +++ b/src/Notepads.DesktopExtension/curl_client.h @@ -0,0 +1,73 @@ +#pragma once +#include "pch.h" +#include "logger.h" +#include "curl/curl.h" + +struct curl_slist_handle_traits +{ + using type = struct curl_slist*; + + static void close(type value) noexcept + { + curl_slist_free_all(value); + } + + static constexpr type invalid() noexcept + { + return nullptr; + } +}; + +struct curl_handle_traits +{ + using type = CURL*; + + static void close(type value) noexcept + { + curl_easy_cleanup(value); + } + + static constexpr type invalid() noexcept + { + return nullptr; + } +}; + +using curl_slist_handle = winrt::handle_type; +using curl_handle = winrt::handle_type; + +struct curl_client +{ + static void post(char const* url, curl_slist_handle const& header, std::string const& data) noexcept + { + curl_handle curl{ curl_easy_init() }; + curl_easy_setopt(curl.get(), CURLOPT_URL, url); + curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, header.get()); + curl_easy_setopt(curl.get(), CURLOPT_COPYPOSTFIELDS, data.c_str()); + +#ifdef _DEBUG + logger::print(L"\n\n\n"); + logger::print(winrt::to_hstring(data), 2000); + logger::print(L"\n\n\n"); + curl_easy_setopt(curl.get(), CURLOPT_VERBOSE, 1L); +#endif + + auto res = curl_easy_perform(curl.get()); + if (res != CURLE_OK) + { + logger::print( + fmt::format( + L"curl_easy_perform() failed: {}", + winrt::to_hstring(curl_easy_strerror(res) + ) + ).c_str() + ); + } + } + +private: + + curl_client() noexcept = default; + curl_client(curl_client&&) = default; + curl_client(curl_client const& other) noexcept = default; +}; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/device.h b/src/Notepads.DesktopExtension/device.h index 1573f65d4..6f88adb68 100644 --- a/src/Notepads.DesktopExtension/device.h +++ b/src/Notepads.DesktopExtension/device.h @@ -1,140 +1,131 @@ #pragma once #include "pch.h" -#include "resource.h" +#include "constants.h" +#include "appcenter.h" -namespace AppCenter +struct device { - using namespace fmt; - using namespace rapidjson; - using namespace std; - using namespace winrt; - using namespace Windows::ApplicationModel; - using namespace Windows::Security::ExchangeActiveSyncProvisioning; - using namespace Windows::System::Profile; + using Package = winrt::Windows::ApplicationModel::Package; + using AnalyticsInfo = winrt::Windows::System::Profile::AnalyticsInfo; + using GlobalizationPreferences = winrt::Windows::System::UserProfile::GlobalizationPreferences; + using EasClientDeviceInformation = winrt::Windows::Security::ExchangeActiveSyncProvisioning::EasClientDeviceInformation; - class Device + device() noexcept { - public: - Device() - { - auto packageVersion = Package::Current().Id().Version(); - _appVersion = format("{}.{}.{}.{}", packageVersion.Major, packageVersion.Minor, packageVersion.Build, packageVersion.Revision); - _appBuild = _appVersion; - - HMODULE appModule = GetModuleHandle(NULL); - _sdkVersion = static_cast(LockResource(LoadResource(appModule, - FindResource(appModule, MAKEINTRESOURCE(APPCENTER_SDK_VERSION), MAKEINTRESOURCE(TEXTFILE))))); - - EasClientDeviceInformation oemInfo = EasClientDeviceInformation(); - _osName = to_string(oemInfo.OperatingSystem()); - - ULONGLONG version = stoull(AnalyticsInfo::VersionInfo().DeviceFamilyVersion().c_str()); - ULONGLONG major = (version & 0xFFFF000000000000L) >> 48; - ULONGLONG minor = (version & 0x0000FFFF00000000L) >> 32; - ULONGLONG build = (version & 0x00000000FFFF0000L) >> 16; - ULONGLONG revision = (version & 0x000000000000FFFFL); - _osVersion = format("{}.{}.{}", major, minor, build); - _osBuild = format("{}.{}.{}.{}", major, minor, build, revision); - - _model = to_string(oemInfo.SystemProductName()); - _oemName = to_string(oemInfo.SystemManufacturer()); - - RECT desktop; - GetWindowRect(GetDesktopWindow(), &desktop); - _screenSize = format("{}x{}", desktop.right, desktop.bottom); - - TCHAR locale[LOCALE_NAME_MAX_LENGTH + 1]; - LCIDToLocaleName(GetThreadLocale(), locale, LOCALE_NAME_MAX_LENGTH, 0); - TCHAR localeDisplayName[LOCALE_NAME_MAX_LENGTH + 1]; - GetLocaleInfoEx(locale, LOCALE_SENGLISHDISPLAYNAME, localeDisplayName, LOCALE_NAME_MAX_LENGTH); - _locale = to_string(locale); - - TIME_ZONE_INFORMATION timeZoneInfo; - GetTimeZoneInformation(&timeZoneInfo); - _timeZoneOffset = -1 * timeZoneInfo.Bias; - } - - Device(const Device& device) : - _appVersion(device._appVersion), _appBuild(device._appBuild), _sdkVersion(device._sdkVersion), - _osName(device._osName), _osVersion(device._osVersion), _osBuild(device._osBuild), - _model(device._model), _oemName(device._oemName), _screenSize(device._screenSize), - _locale(device._locale), _timeZoneOffset(device._timeZoneOffset) {} - - ~Device() {} - - Device& operator=(const Device& device) - { - if (this == &device) return *this; - - _appNamespace = device._appNamespace; - _appVersion = device._appVersion; - _appBuild = device._appBuild; - _sdkName = device._sdkName; - _sdkVersion = device._sdkVersion; - _osName = device._osName; - _osVersion = device._osVersion; - _osBuild = device._osBuild; - _model = device._model; - _oemName = device._oemName; - _screenSize = device._screenSize; - _locale = device._locale; - _timeZoneOffset = device._timeZoneOffset; - return *this; - } - - template - VOID Serialize(Writer& writer) const - { - writer.StartObject(); - - writer.String("appNamespace"); - writer.String(_appNamespace.c_str(), static_cast(_appNamespace.length())); - writer.String("appVersion"); - writer.String(_appVersion.c_str(), static_cast(_appVersion.length())); - writer.String("appBuild"); - writer.String(_appBuild.c_str(), static_cast(_appBuild.length())); - writer.String("sdkName"); - writer.String(_sdkName.c_str(), static_cast(_sdkName.length())); - writer.String("sdkVersion"); - writer.String(_sdkVersion.c_str(), static_cast(_sdkVersion.length())); - writer.String("osName"); - writer.String(_osName.c_str(), static_cast(_osName.length())); - writer.String("osVersion"); - writer.String(_osVersion.c_str(), static_cast(_osVersion.length())); - writer.String("osBuild"); - writer.String(_osBuild.c_str(), static_cast(_osBuild.length())); - writer.String("model"); - writer.String(_model.c_str(), static_cast(_model.length())); - writer.String("oemName"); - writer.String(_oemName.c_str(), static_cast(_oemName.length())); - writer.String("screenSize"); - writer.String(_screenSize.c_str(), static_cast(_screenSize.length())); - writer.String("locale"); - writer.String(_locale.c_str(), static_cast(_locale.length())); - writer.String("timeZoneOffset"); - writer.Uint(_timeZoneOffset); - - writer.EndObject(); - } - - string getOsVersion() - { - return _osBuild; - } - - private: - string _appNamespace = "Notepads.DesktopExtension"; - string _appVersion; - string _appBuild; - string _sdkName = "appcenter.uwp"; - string _sdkVersion; - string _osName; - string _osVersion; - string _osBuild; - string _model; - string _oemName; - string _screenSize; - string _locale; - unsigned _timeZoneOffset; - }; -} \ No newline at end of file + auto package_version = Package::Current().Id().Version(); + m_build = m_version = fmt::format("{}.{}.{}.{}", package_version.Major, package_version.Minor, package_version.Build, package_version.Revision); + + auto oem_info = EasClientDeviceInformation(); + m_os = to_string(oem_info.OperatingSystem()); + + auto version = std::stoull(AnalyticsInfo::VersionInfo().DeviceFamilyVersion().c_str()); + auto major = (version & 0xFFFF000000000000L) >> 48; + auto minor = (version & 0x0000FFFF00000000L) >> 32; + auto build = (version & 0x00000000FFFF0000L) >> 16; + auto revision = (version & 0x000000000000FFFFL); + m_osversion = fmt::format("{}.{}.{}", major, minor, build); + m_osbuild = fmt::format("{}.{}.{}.{}", major, minor, build, revision); + + m_model = to_string(oem_info.SystemProductName()); + m_oem = to_string(oem_info.SystemManufacturer()); + + RECT desktop; + GetWindowRect(GetDesktopWindow(), &desktop); + m_screen = fmt::format("{}x{}", desktop.right, desktop.bottom); + + m_locale = to_string( + GlobalizationPreferences::Languages().Size() > 0 + ? GlobalizationPreferences::Languages().First().Current() + : L"" + ); + + TIME_ZONE_INFORMATION timeZoneInfo; + GetTimeZoneInformation(&timeZoneInfo); + m_timezone = -1 * timeZoneInfo.Bias; + } + + device(device const& device) noexcept : + m_version(device.m_version), + m_build(device.m_build), + m_sdkversion(device.m_sdkversion), + m_os(device.m_os), + m_osversion(device.m_osversion), + m_osbuild(device.m_osbuild), + m_model(device.m_model), + m_oem(device.m_oem), + m_screen(device.m_screen), + m_locale(device.m_locale), + m_timezone(device.m_timezone) + {} + + device& operator=(device const& device) noexcept + { + m_namespace = device.m_namespace; + m_version = device.m_version; + m_build = device.m_build; + m_sdk = device.m_sdk; + m_sdkversion = device.m_sdkversion; + m_os = device.m_os; + m_osversion = device.m_osversion; + m_osbuild = device.m_osbuild; + m_model = device.m_model; + m_oem = device.m_oem; + m_screen = device.m_screen; + m_locale = device.m_locale; + m_timezone = device.m_timezone; + return *this; + } + + template + void serialize(Writer& writer) const noexcept + { + writer.StartObject(); + writer.String("appNamespace"); + writer.String(m_namespace.c_str(), static_cast(m_namespace.length())); + writer.String("appVersion"); + writer.String(m_version.c_str(), static_cast(m_version.length())); + writer.String("appBuild"); + writer.String(m_build.c_str(), static_cast(m_build.length())); + writer.String("sdkName"); + writer.String(m_sdk.c_str(), static_cast(m_sdk.length())); + writer.String("sdkVersion"); + writer.String(m_sdkversion.c_str(), static_cast(m_sdkversion.length())); + writer.String("osName"); + writer.String(m_os.c_str(), static_cast(m_os.length())); + writer.String("osVersion"); + writer.String(m_osversion.c_str(), static_cast(m_osversion.length())); + writer.String("osBuild"); + writer.String(m_osbuild.c_str(), static_cast(m_osbuild.length())); + writer.String("model"); + writer.String(m_model.c_str(), static_cast(m_model.length())); + writer.String("oemName"); + writer.String(m_oem.c_str(), static_cast(m_oem.length())); + writer.String("screenSize"); + writer.String(m_screen.c_str(), static_cast(m_screen.length())); + writer.String("locale"); + writer.String(m_locale.c_str(), static_cast(m_locale.length())); + writer.String("timeZoneOffset"); + writer.Uint(m_timezone); + writer.EndObject(); + } + + std::string osbuild() const noexcept + { + return m_osbuild; + } + +private: + std::string m_namespace = "Notepads.DesktopExtension"; + std::string m_version; + std::string m_build; + std::string m_sdk = "appcenter.uwp"; + std::string m_sdkversion = APP_CENTER_SDK_VERSION; + std::string m_os; + std::string m_osversion; + std::string m_osbuild; + std::string m_model; + std::string m_oem; + std::string m_screen; + std::string m_locale; + unsigned m_timezone; +}; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/elevated.cpp b/src/Notepads.DesktopExtension/elevated.cpp index 055b548a3..ab50148b0 100644 --- a/src/Notepads.DesktopExtension/elevated.cpp +++ b/src/Notepads.DesktopExtension/elevated.cpp @@ -1,4 +1,5 @@ #include "pch.h" +#include "logger.h" #include "appcenter.h" #include "fmt/format.h" @@ -8,229 +9,217 @@ using namespace winrt; using namespace Windows::ApplicationModel; using namespace Windows::Storage::AccessCache; -extern DWORD sessionId; -extern hstring packageSid; +extern DWORD session_id; +extern hstring package_sid; -HANDLE elevatedWriteEvent = NULL; -HANDLE elevatedRenameEvent = NULL; - -wstring writePipeName; -wstring renamePipeName; +hstring write_pipe; +hstring rename_pipe; DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) { - setExceptionHandling(); + try + { + handle elevated_write_event = handle(OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, format(NAMED_OBJECT_FORMAT, package_sid, ELEVATED_WRITE_EVENT_NAME_STR).c_str())); - vector> properties; - LPCTSTR result = L"Failed"; + check_bool(!WaitForSingleObject(elevated_write_event.get(), INFINITE)); + check_bool(ResetEvent(elevated_write_event.get())); + check_bool(WaitNamedPipe(write_pipe.c_str(), NMPWAIT_WAIT_FOREVER)); - HANDLE hPipe = INVALID_HANDLE_VALUE; - if (!WaitForSingleObject(elevatedWriteEvent, INFINITE) && - ResetEvent(elevatedWriteEvent) && - WaitNamedPipe(writePipeName.c_str(), NMPWAIT_WAIT_FOREVER)) - { - hPipe = CreateFile(writePipeName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); - } + auto h_pipe = handle(CreateFile(write_pipe.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr)); + check_bool(bool(h_pipe)); - if (hPipe) - { - CreateThread(NULL, 0, saveFileFromPipeData, NULL, 0, NULL); + CreateThread(nullptr, 0, saveFileFromPipeData, nullptr, 0, nullptr); - TCHAR readBuffer[PIPE_READ_BUFFER]; - wstringstream pipeData; - DWORD byteRead; + TCHAR read_buffer[PIPE_READ_BUFFER]; + wstringstream pipe_data; + DWORD byte_read; do { - fill(begin(readBuffer), end(readBuffer), '\0'); - if (ReadFile(hPipe, readBuffer, (PIPE_READ_BUFFER - 1) * sizeof(TCHAR), &byteRead, NULL)) + fill(begin(read_buffer), end(read_buffer), '\0'); + if (ReadFile(h_pipe.get(), read_buffer, (PIPE_READ_BUFFER - 1) * sizeof(TCHAR), &byte_read, nullptr)) { - pipeData << readBuffer; + pipe_data << read_buffer; } - } while (byteRead >= (PIPE_READ_BUFFER - 1) * sizeof(TCHAR)); + } while (byte_read >= (PIPE_READ_BUFFER - 1) * sizeof(TCHAR)); wstring filePath; - wstring memoryMapId; - wstring dataArrayLengthStr; - getline(pipeData, filePath, L'|'); - getline(pipeData, memoryMapId, L'|'); - getline(pipeData, dataArrayLengthStr); - - INT dataArrayLength = stoi(dataArrayLengthStr); - wstring memoryMapName = format(NAMED_OBJECT_FORMAT, packageSid, memoryMapId); - HANDLE hMemory = OpenFileMapping(FILE_MAP_READ, FALSE, memoryMapName.c_str()); - if (hMemory) - { - LPVOID mapView = MapViewOfFile(hMemory, FILE_MAP_READ, 0, 0, dataArrayLength); - if (mapView) - { - HANDLE hFile = CreateFile( - filePath.c_str(), - GENERIC_READ | GENERIC_WRITE, - 0, - NULL, - TRUNCATE_EXISTING, - 0, - NULL); - - if (hFile) - { - if (WriteFile(hFile, mapView, dataArrayLength, NULL, NULL) && FlushFileBuffers(hFile)) - { - result = L"Success"; - } - - CloseHandle(hFile); - } - - UnmapViewOfFile(mapView); - } + wstring memory_map_id; + wstring data_length_str; + getline(pipe_data, filePath, L'|'); + getline(pipe_data, memory_map_id, L'|'); + getline(pipe_data, data_length_str); - CloseHandle(hMemory); - } + int data_length = stoi(data_length_str); + wstring memory_map = format(NAMED_OBJECT_FORMAT, package_sid, memory_map_id); - if (WriteFile(hPipe, result, wcslen(result) * sizeof(TCHAR), NULL, NULL)) FlushFileBuffers(hPipe); - CloseHandle(hPipe); + auto h_memory = handle(OpenFileMapping(FILE_MAP_READ, FALSE, memory_map.c_str())); + check_bool(bool(h_memory)); - properties.push_back(pair("Result", to_string(result))); - if (wcscmp(result, L"Success") == 0) - { - printDebugMessage(format(L"Successfully wrote to \"{}\"", filePath).c_str()); - } - else + auto map_view = MapViewOfFile(h_memory.get(), FILE_MAP_READ, 0, 0, data_length); + check_bool(map_view); + + auto h_file = handle(CreateFile(filePath.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, TRUNCATE_EXISTING, 0, nullptr)); + check_bool(bool(h_file)); + check_bool(WriteFile(h_file.get(), map_view, data_length, nullptr, nullptr)); + check_bool(FlushFileBuffers(h_file.get())); + + UnmapViewOfFile(map_view); + + auto result = L"Success"; + check_bool(WriteFile(h_pipe.get(), result, static_cast(wcslen(result) * sizeof(TCHAR)), nullptr, nullptr)); + check_bool(FlushFileBuffers(h_pipe.get())); + + report::dictionary properties { - pair ex = getLastErrorDetails(); - properties.insert(properties.end(), - { - pair("Error Code", to_string(ex.first)), - pair("Error Message", winrt::to_string(ex.second)) - }); - printDebugMessage(format(L"Failed to write to \"{}\"", filePath).c_str()); - } - printDebugMessage(L"Waiting on uwp app to send data."); - - AppCenter::trackEvent("OnWriteToSystemFileRequested", properties); + pair("Result", to_string(result)) + }; + logger::log_info(format(L"Successfully wrote to \"{}\"", filePath).c_str(), true); + logger::log_info(L"Waiting on uwp app to send data.", true); + + analytics::track_event("OnWriteToSystemFileRequested", properties); + return 0; } - else + catch (hresult_error const& e) { - pair ex = getLastErrorDetails(); - properties.insert(properties.end(), - { - pair("Result", to_string(result)), - pair("Error Code", to_string(ex.first)), - pair("Error Message", winrt::to_string(ex.second)) - }); - AppCenter::trackEvent("OnWriteToSystemFileRequested", properties); - exitApp(); + winrt_error error{ e, true, 3 }; + report::dictionary properties + { + pair("Result", "Failed") + }; + report::add_device_metadata(properties); + logger::log_error(error); + crashes::track_error(error, properties); + analytics::track_event("OnWriteToSystemFileRequested", properties); + exit_app(e.code()); + return e.code(); } - - return 0; } DWORD WINAPI renameFileFromPipeData(LPVOID /* param */) { - setExceptionHandling(); + hstring old_name; + wstring new_name; + try + { + handle elevated_rename_event = handle(OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, format(NAMED_OBJECT_FORMAT, package_sid, ELEVATED_RENAME_EVENT_NAME_STR).c_str())); - vector> properties; - LPCTSTR result = L"Failed"; + check_bool(!WaitForSingleObject(elevated_rename_event.get(), INFINITE)); + check_bool(ResetEvent(elevated_rename_event.get())); + check_bool(WaitNamedPipe(rename_pipe.c_str(), NMPWAIT_WAIT_FOREVER)); - HANDLE hPipe = INVALID_HANDLE_VALUE; - if (!WaitForSingleObject(elevatedRenameEvent, INFINITE) && - ResetEvent(elevatedRenameEvent) && - WaitNamedPipe(renamePipeName.c_str(), NMPWAIT_WAIT_FOREVER)) - { - hPipe = CreateFile(renamePipeName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); - } + auto h_pipe = handle(CreateFile(rename_pipe.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr)); + check_bool(bool(h_pipe)); - if (hPipe) - { - CreateThread(NULL, 0, renameFileFromPipeData, NULL, 0, NULL); + CreateThread(nullptr, 0, renameFileFromPipeData, nullptr, 0, nullptr); - TCHAR readBuffer[PIPE_READ_BUFFER]; - wstringstream pipeData; - DWORD byteRead; + TCHAR read_buffer[PIPE_READ_BUFFER]; + wstringstream pipe_data; + DWORD byte_read; do { - fill(begin(readBuffer), end(readBuffer), '\0'); - if (ReadFile(hPipe, readBuffer, (PIPE_READ_BUFFER - 1) * sizeof(TCHAR), &byteRead, NULL)) + fill(begin(read_buffer), end(read_buffer), '\0'); + if (ReadFile(h_pipe.get(), read_buffer, (PIPE_READ_BUFFER - 1) * sizeof(TCHAR), &byte_read, nullptr)) { - pipeData << readBuffer; + pipe_data << read_buffer; } - } while (byteRead >= (PIPE_READ_BUFFER - 1) * sizeof(TCHAR)); + } while (byte_read >= (PIPE_READ_BUFFER - 1) * sizeof(TCHAR)); - wstring fileToken; - wstring newName; - getline(pipeData, fileToken, L'|'); - getline(pipeData, newName, L'|'); + wstring file_token; + getline(pipe_data, file_token, L'|'); + getline(pipe_data, new_name, L'|'); - auto file = StorageApplicationPermissions::FutureAccessList().GetFileAsync(fileToken).get(); - StorageApplicationPermissions::FutureAccessList().Remove(fileToken); - auto oldName = file.Path(); - file.RenameAsync(newName).get(); - result = StorageApplicationPermissions::FutureAccessList().Add(file).c_str(); + auto file = StorageApplicationPermissions::FutureAccessList().GetFileAsync(file_token).get(); + StorageApplicationPermissions::FutureAccessList().Remove(file_token); + old_name = file.Path(); + file.RenameAsync(new_name).get(); - if (WriteFile(hPipe, result, wcslen(result) * sizeof(TCHAR), NULL, NULL)) FlushFileBuffers(hPipe); - CloseHandle(hPipe); + auto result = StorageApplicationPermissions::FutureAccessList().Add(file).c_str(); - if (wcscmp(result, L"Failed") == 0) - { - pair ex = getLastErrorDetails(); - properties.insert(properties.end(), - { - pair("Result", to_string(result)), - pair("Error Code", to_string(ex.first)), - pair("Error Message", winrt::to_string(ex.second)) - }); - printDebugMessage(format(L"Failed to rename \"{}\" to \"{}\"", oldName, newName).c_str()); - } - else + check_bool(WriteFile(h_pipe.get(), result, static_cast(wcslen(result) * sizeof(TCHAR)), nullptr, nullptr)); + check_bool(FlushFileBuffers(h_pipe.get())); + + logger::log_info(format(L"Successfully renamed \"{}\" to \"{}\"", old_name, new_name).c_str(), true); + logger::log_info(L"Waiting on uwp app to send data.", true); + + report::dictionary properties { - properties.push_back(pair("Result", "Success")); - printDebugMessage(format(L"Successfully renamed \"{}\" to \"{}\"", oldName, newName).c_str()); - } - printDebugMessage(L"Waiting on uwp app to send data."); + pair("Result", "Success") + }; - AppCenter::trackEvent("OnRenameToSystemFileRequested", properties); + analytics::track_event("OnRenameToSystemFileRequested", properties); + return 0; } - else + catch (hresult_error const& e) { - pair ex = getLastErrorDetails(); - properties.insert(properties.end(), - { - pair("Result", to_string(result)), - pair("Error Code", to_string(ex.first)), - pair("Error Message", winrt::to_string(ex.second)) - }); - AppCenter::trackEvent("OnRenameToSystemFileRequested", properties); - exitApp(); + winrt_error error{ e, true, 3 }; + logger::log_info( + old_name.empty() + ? new_name.empty() + ? L"Failed to rename file" + : format(L"Failed to rename file to \"{}\"", new_name).c_str() + : format(L"Failed to rename \"{}\" to \"{}\"", old_name, new_name).c_str(), + true + ); + + report::dictionary properties + { + pair("Result", "Failed") + }; + report::add_device_metadata(properties); + logger::log_error(error); + crashes::track_error(error, properties); + analytics::track_event("OnRenameToSystemFileRequested", properties); + exit_app(e.code()); + return e.code(); } - - return 0; } -VOID initializeElevatedService() +void initialize_elevated_service() { - if (!isFirstInstance(ElevatedMutexName)) return; - - ProcessIdToSessionId(GetCurrentProcessId(), &sessionId); - packageSid = unbox_value_or(readSettingsKey(PackageSidStr), L""); + if (!is_first_instance(ELEVATED_MUTEX_NAME)) return; - elevatedWriteEvent = OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, format(NAMED_OBJECT_FORMAT, packageSid, ElevatedWriteEventNameStr).c_str()); - elevatedRenameEvent = OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, format(NAMED_OBJECT_FORMAT, packageSid, ElevatedRenameEventNameStr).c_str()); + try + { + check_bool(ProcessIdToSessionId(GetCurrentProcessId(), &session_id)); + package_sid = unbox_value(settings_key::read(PACKAGE_SID_STR)); - writePipeName = format(PIPE_NAME_FORMAT, sessionId, packageSid, ElevatedWritePipeConnectionNameStr); - renamePipeName = format(PIPE_NAME_FORMAT, sessionId, packageSid, ElevatedRenamePipeConnectionNameStr); + write_pipe = format(PIPE_NAME_FORMAT, session_id, package_sid, ELEVATED_WRITE_PIPE_CONNECTION_NAME_STR); + rename_pipe = format(PIPE_NAME_FORMAT, session_id, package_sid, ELEVATED_RENAME_PIPE_CONNECTION_NAME_STR); - printDebugMessage(L"Successfully started Elevated Process."); - printDebugMessage(L"Waiting on uwp app to send data."); + logger::log_info(L"Successfully started Elevated Process.", true); + logger::log_info(L"Waiting on uwp app to send data.", true); - CreateThread(NULL, 0, saveFileFromPipeData, NULL, 0, NULL); - CreateThread(NULL, 0, renameFileFromPipeData, NULL, 0, NULL); + auto write_thread = handle(CreateThread(nullptr, 0, saveFileFromPipeData, nullptr, 0, nullptr)); + auto rename_thread = handle(CreateThread(nullptr, 0, renameFileFromPipeData, nullptr, 0, nullptr)); + check_bool(bool(write_thread)); + } + catch (hresult_error const& e) + { + winrt_error error{ e, true, 3 }; + report::dictionary properties{}; + report::add_device_metadata(properties); + logger::log_error(error); + crashes::track_error(error, properties); + analytics::track_event("OnInitializationForExtensionFailed", properties); + exit_app(e.code()); + } LifeTimeCheck: - HANDLE lifeTimeObj = OpenMutex(SYNCHRONIZE, FALSE, format(L"AppContainerNamedObjects\\{}\\{}", packageSid, ElevatedProcessLifetimeObjNameStr).c_str()); - if (lifeTimeObj) + auto life_time_obj = handle( + OpenMutex( + SYNCHRONIZE, + FALSE, + format( + L"AppContainerNamedObjects\\{}\\{}", + package_sid, + ELEVATED_PROCESS_LIFETIME_OBJ_NAME_STR + ).c_str() + ) + ); + + if (life_time_obj) { - CloseHandle(lifeTimeObj); + life_time_obj.close(); Sleep(1000); goto LifeTimeCheck; } diff --git a/src/Notepads.DesktopExtension/error.h b/src/Notepads.DesktopExtension/error.h new file mode 100644 index 000000000..a44b57866 --- /dev/null +++ b/src/Notepads.DesktopExtension/error.h @@ -0,0 +1,265 @@ +#pragma once +#include "pch.h" +#include "frame.h" +#include "restrictederrorinfo.h" + +#define TRACED_FRAMES_COUNT 5 +#define SKIPPED_FRAMES_COUNT 3 + +struct winrt_error +{ + using from_abi_t = winrt::take_ownership_from_abi_t; + static constexpr auto from_abi{ winrt::take_ownership_from_abi }; + + winrt_error() noexcept = default; + winrt_error(winrt_error&&) = default; + winrt_error& operator=(winrt_error&&) = default; + + winrt_error(winrt_error const& other) noexcept : + m_code(other.m_code), + m_info(other.m_info), + m_trace(other.m_trace), + m_fatal(other.m_fatal) + { + } + + winrt_error& operator=(winrt_error const& other) noexcept + { + m_code = other.m_code; + m_info = other.m_info; + m_trace = other.m_trace; + m_fatal = other.m_fatal; + return *this; + } + + explicit winrt_error(winrt::hresult const code, bool fatal, uint48_t skip = 0) noexcept : + m_code(verify_error(code)), + m_fatal(fatal) + { + originate(code, nullptr, skip + SKIPPED_FRAMES_COUNT); + } + + explicit winrt_error(winrt::hresult_error const& error, bool fatal = true, uint48_t skip = 0) noexcept : + m_code(error.code()), + m_info(error.try_as()), + m_fatal(fatal) + { + trace_stack(skip + SKIPPED_FRAMES_COUNT); + } + + winrt_error(winrt::hresult const code, winrt::param::hstring const& message) noexcept : m_code(verify_error(code)) + { + originate(code, winrt::param::get_abi(message), SKIPPED_FRAMES_COUNT); + } + + winrt_error(winrt::hresult const code, winrt::take_ownership_from_abi_t) noexcept : m_code(verify_error(code)) + { + winrt::com_ptr info; + WINRT_IMPL_GetErrorInfo(0, info.put_void()); + + if ((m_info = info.try_as())) + { + WINRT_VERIFY_(0, m_info->GetReference(m_debug_reference.put())); + + if (auto info2 = m_info.try_as()) + { + WINRT_VERIFY_(0, info2->CapturePropagationContext(nullptr)); + } + } + else + { + winrt::impl::bstr_handle legacy; + + if (info) + { + info->GetDescription(legacy.put()); + } + + winrt::hstring message; + + if (legacy) + { + message = winrt::impl::trim_hresult_message(legacy.get(), WINRT_IMPL_SysStringLen(legacy.get())); + } + + originate(code, get_abi(message), SKIPPED_FRAMES_COUNT); + } + } + + winrt::hresult code() const noexcept + { + return m_code; + } + + winrt::hstring message() const noexcept + { + if (m_info) + { + int32_t code{}; + winrt::impl::bstr_handle fallback; + winrt::impl::bstr_handle message; + winrt::impl::bstr_handle unused; + + if (0 == m_info->GetErrorDetails(fallback.put(), &code, message.put(), unused.put())) + { + if (code == m_code) + { + if (message) + { + return winrt::impl::trim_hresult_message(message.get(), WINRT_IMPL_SysStringLen(message.get())); + } + else + { + return winrt::impl::trim_hresult_message(fallback.get(), WINRT_IMPL_SysStringLen(fallback.get())); + } + } + } + } + + return winrt::impl::message_from_hresult(m_code); + } + + winrt::hstring stacktrace() const noexcept + { + if (!m_info || m_trace.empty()) return L""; + + std::wstringstream stacktrace{ L"" }; + for (auto& trace : m_trace) + { + stacktrace << L" at " << trace.name().c_str() << L" in " << trace.file().c_str() << L" :line" << trace.line() << L"\n"; + } + + return stacktrace.str().c_str(); + } + + winrt_error inner() const noexcept + { + winrt::com_ptr info; + m_info.try_as()->GetPreviousLanguageExceptionErrorInfo(info.put()); + + winrt_error inner; + if (inner.m_info = info.try_as()) + { + inner.trace_stack(0, true); + } + return inner; + } + + bool fatal() const noexcept + { + return m_fatal; + } + + template + auto try_as() const noexcept + { + return m_info.try_as(); + } + + winrt::hresult to_abi() const noexcept + { + if (m_info) + { + WINRT_IMPL_SetErrorInfo(0, m_info.try_as().get()); + } + + return m_code; + } + + template + void serialize(json_writer& writer) const noexcept + { + auto error = winrt::to_string(fmt::format(L"HResult: {}", code())); + auto msg = winrt::to_string(message()); + auto st = winrt::to_string(stacktrace()); + + writer.StartObject(); + writer.String("type"); + writer.String(error.c_str(), static_cast(error.length())); + writer.String("message"); + writer.String(msg.c_str(), static_cast(msg.length())); + /*writer.String("stackTrace"); + writer.String(st.c_str(), static_cast(st.size()));*/ + writer.String("frames"); + writer.StartArray(); + for (auto& frame : m_trace) + { + frame.serialize(writer); + } + writer.EndArray(); + writer.EndObject(); + } + + static winrt_error get_last_error() noexcept + { + return winrt_error(winrt::impl::hresult_from_win32(GetLastError()), false); + } + +private: + + static int32_t __stdcall fallback_RoOriginateLanguageException(int32_t error, void* message, void*) noexcept + { + winrt::com_ptr info(new (std::nothrow) winrt::impl::error_info_fallback(error, message), winrt::take_ownership_from_abi); + WINRT_VERIFY_(0, WINRT_IMPL_SetErrorInfo(0, info.get())); + return 1; + } + + void originate(winrt::hresult const code, void* message, uint48_t skip = 0) noexcept + { + static int32_t(__stdcall * handler)(int32_t error, void* message, void* exception) noexcept; + winrt::impl::load_runtime_function("RoOriginateLanguageException", handler, fallback_RoOriginateLanguageException); + WINRT_VERIFY(handler(code, message, nullptr)); + + winrt::com_ptr info; + WINRT_VERIFY_(0, WINRT_IMPL_GetErrorInfo(0, info.put_void())); + WINRT_VERIFY(info.try_as(m_info)); + + trace_stack(skip); + } + + void trace_stack(uint48_t skip = 0, bool original = false) noexcept + { + auto infoWithStackTrace = m_info.try_as(); + uint64_t traces[TRACED_FRAMES_COUNT]{ 0 }; + uint48_t count = TRACED_FRAMES_COUNT; + if (infoWithStackTrace || original) + { + infoWithStackTrace->GetStackBackTrace(TRACED_FRAMES_COUNT, traces, &count); + } + else + { + CaptureStackBackTrace(skip, TRACED_FRAMES_COUNT, (void**)traces, nullptr); + } + + if (count <= 0) return; + frame* frames = new frame[count]; + for (uint48_t i = 0; i < count; ++i) + { + frames[i] = traces[i]; + } + + m_trace = winrt::array_view(frames, count); + } + + static winrt::hresult verify_error(winrt::hresult const code) noexcept + { + WINRT_ASSERT(code < 0); + return code; + } + +#ifdef __clang__ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wunused-private-field" +#endif + + winrt::impl::bstr_handle m_debug_reference; + uint32_t m_debug_magic{ 0xAABBCCDD }; + winrt::hresult m_code{ winrt::impl::error_fail }; + winrt::com_ptr m_info; + winrt::array_view m_trace; + bool m_fatal = true; + +#ifdef __clang__ +#pragma clang diagnostic pop +#endif +}; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/error_attachment_report.h b/src/Notepads.DesktopExtension/error_attachment_report.h new file mode 100644 index 000000000..ea1d958e6 --- /dev/null +++ b/src/Notepads.DesktopExtension/error_attachment_report.h @@ -0,0 +1,73 @@ +#pragma once +#include "pch.h" +#include "report.h" + +struct error_attachment_report : report +{ + explicit error_attachment_report(std::string const& id, std::string const& attachment) noexcept : + report(), m_errorid(id), m_attachment(base64_encode(attachment)) + { + } + + error_attachment_report(error_attachment_report const& other) noexcept : + report(other), + m_errorid(other.m_errorid), + m_content(other.m_content), + m_attachment(other.m_attachment) + { + } + + error_attachment_report(error_attachment_report&& other) noexcept : + report(other) + { + } + + //From https://stackoverflow.com/a/34571089/5155484 + static std::string base64_encode(std::string const& in) noexcept + { + static const std::string base64_str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + std::string out; + + int val = 0, valb = -6; + for (auto c : in) { + val = (val << 8) + c; + valb += 8; + while (valb >= 0) { + out.push_back(base64_str[(val >> valb) & 0x3F]); + valb -= 6; + } + } + if (valb > -6) out.push_back(base64_str[((val << 8) >> (valb + 8)) & 0x3F]); + while (out.size() % 4) out.push_back('='); + return out; + } + +protected: + + virtual void append_type_data(json_writer& writer) const noexcept + { + writer.String("type"); + writer.String("errorAttachment"); + } + + virtual void append_additional_data(json_writer& writer) const noexcept + { + report::append_additional_data(writer); + + writer.String("contentType"); + writer.String(m_content.c_str(), static_cast(m_content.length())); + writer.String("data"); + writer.String(m_attachment.c_str(), static_cast(m_attachment.length())); + writer.String("errorId"); + writer.String(m_errorid.c_str(), static_cast(m_errorid.length())); + } + + virtual void append_report(json_writer& writer) const noexcept + { + report::append_report(writer); + } + + std::string m_errorid; + std::string m_content = "text/plain"; + std::string m_attachment; +}; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/error_report.h b/src/Notepads.DesktopExtension/error_report.h new file mode 100644 index 000000000..320ec707a --- /dev/null +++ b/src/Notepads.DesktopExtension/error_report.h @@ -0,0 +1,42 @@ +#pragma once +#include "pch.h" +#include "managed_error_report.h" +#include "handled_error_report.h" + +struct error_report : report +{ + explicit error_report( + winrt_error const& error, + report::dictionary const& properties, + std::string const& attachment = "" + ) noexcept : + m_handled_error_report(error, properties, attachment), m_managed_error_report(error, attachment) + { + } + + error_report(error_report const& other) noexcept : + report(other), + m_managed_error_report(other.m_managed_error_report), + m_handled_error_report(other.m_handled_error_report) + { + } + + error_report(error_report&& other) noexcept : + report(other), + m_managed_error_report(other.m_managed_error_report), + m_handled_error_report(other.m_handled_error_report) + { + } + + virtual void serialize(json_writer& writer) const noexcept + { + m_managed_error_report.serialize(writer); + m_handled_error_report.serialize(writer); + last_error_report_sid = m_managed_error_report.sid(); + } + +protected: + + managed_error_report m_managed_error_report; + handled_error_report m_handled_error_report; +}; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/event_report.h b/src/Notepads.DesktopExtension/event_report.h new file mode 100644 index 000000000..9ac6a5b0c --- /dev/null +++ b/src/Notepads.DesktopExtension/event_report.h @@ -0,0 +1,66 @@ +#pragma once +#include "pch.h" +#include "error.h" +#include "report.h" + +struct event_report : report +{ + explicit event_report(std::string const& name, report::dictionary const& properties) noexcept : + report(), m_sid(last_error_report_sid), m_name(name), m_properties(properties) + { + last_error_report_sid = ""; + } + + event_report(event_report const& other) noexcept : + report(other), + m_sid(other.m_sid), + m_name(other.m_name), + m_properties(other.m_properties) + { + } + + event_report(event_report&& other) noexcept : + report(other) + { + } + +protected: + + virtual void append_type_data(json_writer& writer) const noexcept + { + writer.String("type"); + writer.String("event"); + } + + virtual void append_additional_data(json_writer& writer) const noexcept + { + report::append_additional_data(writer); + + writer.String("sid"); + writer.String(m_sid.c_str(), static_cast(m_sid.length())); + writer.String("name"); + writer.String(m_name.c_str(), static_cast(m_name.length())); + + // Write custom properties if available + if (!m_properties.empty()) + { + writer.String("properties"); + writer.StartObject(); + for (auto& property : m_properties) + { + writer.String(property.first.c_str(), static_cast(property.first.length())); + writer.String(property.second.c_str(), static_cast(property.second.length())); + } + writer.EndObject(); + } + } + + virtual void append_report(json_writer& writer) const noexcept + { + report::append_report(writer); + } + + std::string m_sid; + std::string m_name; + report::dictionary m_properties; +}; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/exception.h b/src/Notepads.DesktopExtension/exception.h deleted file mode 100644 index 4647aef60..000000000 --- a/src/Notepads.DesktopExtension/exception.h +++ /dev/null @@ -1,114 +0,0 @@ -#pragma once -#include "pch.h" - -#define IGNORED_FRAME_COUNT 6 - -namespace AppCenter -{ - using namespace boost::stacktrace; - using namespace std; - - class Frame - { - public: - Frame(const frame& frame) : _methodName(frame.name()), _fileName(frame.source_file()), _lineNumber(frame.source_line()) {} - Frame(const Frame& frame) : _methodName(frame._methodName), _fileName(frame._fileName), _lineNumber(frame._lineNumber) {} - - ~Frame() {} - - Frame& operator=(const Frame& frame) - { - if (this == &frame) return *this; - - _methodName = frame._methodName; - _fileName = frame._fileName; - _lineNumber = frame._lineNumber; - return *this; - } - - template - VOID Serialize(Writer& writer) const - { - if (_lineNumber <= 0 && _fileName.empty()) return; - - writer.StartObject(); - - writer.String("methodName"); - writer.String(_methodName.c_str(), static_cast(_methodName.length())); - writer.String("fileName"); - writer.String(_fileName.c_str(), static_cast(_fileName.length())); - writer.String("lineNumber"); - writer.Uint(_lineNumber); - - writer.EndObject(); - } - - private: - string _methodName; - string _fileName; - unsigned _lineNumber; - }; - - class Exception - { - public: - Exception(const string& message) : _message(message) {} - Exception(const string& message, const string& stackTrace) : _message(message), _stackTrace(stackTrace) {} - Exception(const Exception& exception) : _message(exception._message), _stackTrace(exception._stackTrace), _frames(exception._frames) {} - Exception(const exception& exception) : _message(exception.what()) {} - - Exception(const string& message, const stacktrace& stackTrace) : _message(message) - { - _frames.assign(stackTrace.as_vector().begin() + IGNORED_FRAME_COUNT, stackTrace.as_vector().end()); - } - - ~Exception() {} - - Exception& operator=(const Exception& exception) - { - if (this == &exception) return *this; - - _type = exception._type; - _message = exception._message; - _stackTrace = exception._stackTrace; - _frames = exception._frames; - return *this; - } - - template - VOID Serialize(Writer& writer) const - { - writer.StartObject(); - - writer.String("type"); - writer.String(_type.c_str(), static_cast(_type.length())); - writer.String("message"); - writer.String(_message.c_str(), static_cast(_message.length())); - - if (!_stackTrace.empty()) - { - writer.String("stackTrace"); - writer.String(_stackTrace.c_str(), static_cast(_stackTrace.length())); - } - - if (!_frames.empty()) - { - writer.String("frames"); - writer.StartArray(); - for (Frame frame : _frames) - { - frame.Serialize(writer); - } - writer.EndArray(); - } - - writer.EndObject(); - } - - private: - string _type = "Win32Exception"; - string _message; - string _stackTrace = ""; - vector _frames; - }; -} \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/extension.cpp b/src/Notepads.DesktopExtension/extension.cpp index 85fc22e78..24fd96c6b 100644 --- a/src/Notepads.DesktopExtension/extension.cpp +++ b/src/Notepads.DesktopExtension/extension.cpp @@ -1,171 +1,241 @@ #include "pch.h" +#include "logger.h" #include "appcenter.h" +#include "settings_key.h" +#include "shellapi.h" -using namespace fmt; using namespace std; using namespace winrt; using namespace Windows::ApplicationModel; using namespace Windows::Storage; -DWORD sessionId; -hstring packageSid; +DWORD session_id; +hstring package_sid; +hstring unblock_pipe; -wstring extensionUnblockPipeName; - -HANDLE extensionUnblockEvent = NULL; - -DWORD WINAPI unblockFileFromPipeData(LPVOID /* param */) +DWORD WINAPI unblock_file_from_pipe_data(LPVOID /* param */) { - setExceptionHandling(); - - HANDLE hPipe = INVALID_HANDLE_VALUE; - if (!WaitForSingleObject(extensionUnblockEvent, INFINITE) && - ResetEvent(extensionUnblockEvent) && - WaitNamedPipe(extensionUnblockPipeName.c_str(), NMPWAIT_WAIT_FOREVER)) - { - hPipe = CreateFile(extensionUnblockPipeName.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, NULL); - } - - if (hPipe) + hstring file_path{}; + try { - CreateThread(NULL, 0, unblockFileFromPipeData, NULL, 0, NULL); - - TCHAR readBuffer[PIPE_READ_BUFFER]; - wstringstream pipeData; - DWORD byteRead; + auto extension_unblock_event = handle( + OpenEvent( + SYNCHRONIZE | EVENT_MODIFY_STATE, + FALSE, + fmt::format( + NAMED_OBJECT_FORMAT, + package_sid, + EXTENSION_UNBLOCK_EVENT_NAME_STR + ).c_str() + ) + ); + + check_bool(!WaitForSingleObject(extension_unblock_event.get(), INFINITE)); + check_bool(ResetEvent(extension_unblock_event.get())); + check_bool(WaitNamedPipe(unblock_pipe.c_str(), NMPWAIT_WAIT_FOREVER)); + + CreateThread(nullptr, 0, unblock_file_from_pipe_data, nullptr, 0, nullptr); + + auto h_pipe = handle( + CreateFile( + unblock_pipe.c_str(), + GENERIC_READ, + 0, + nullptr, + OPEN_EXISTING, + 0, + nullptr + ) + ); + + check_bool(bool(h_pipe)); + + auto read_buffer = wstring(PIPE_READ_BUFFER, '\0'); + auto pipe_data = wstringstream(); + auto byte_read = DWORD(0); do { - fill(begin(readBuffer), end(readBuffer), '\0'); - if (ReadFile(hPipe, readBuffer, (PIPE_READ_BUFFER - 1) * sizeof(TCHAR), &byteRead, NULL)) + fill(read_buffer.begin(), read_buffer.end(), '\0'); + if (ReadFile(h_pipe.get(), &read_buffer[0], (PIPE_READ_BUFFER - 1) * sizeof(TCHAR), &byte_read, nullptr)) { - pipeData << readBuffer; + pipe_data << read_buffer; } - } while (byteRead >= (PIPE_READ_BUFFER - 1) * sizeof(TCHAR)); + } while (byte_read >= (PIPE_READ_BUFFER - 1) * sizeof(TCHAR)); - hstring filePath(pipeData.str()); - com_ptr pFile = create_instance(CLSID_PersistentZoneIdentifier); - if (SUCCEEDED(pFile->Load(filePath.c_str(), STGM_READWRITE))) - { - LPTSTR lastWriterPackageFamilyName; - if (SUCCEEDED(pFile.as()->GetLastWriterPackageFamilyName(&lastWriterPackageFamilyName)) && - Package::Current().Id().FamilyName() == lastWriterPackageFamilyName && - SUCCEEDED(pFile.as()->Remove()) && - SUCCEEDED(pFile->Save(filePath.c_str(), TRUE))) - { - printDebugMessage(format(L"Successfully unblocked file \"{}\"", filePath).c_str()); - } - else - { - printDebugMessage(format(L"Failed to unblock file \"{}\"", filePath).c_str()); - } - } - else - { - printDebugMessage(format(L"Failed to unblock file \"{}\"", filePath).c_str()); - } - pFile.~com_ptr(); + file_path = pipe_data.str(); + auto p_file = create_instance(CLSID_PersistentZoneIdentifier); + check_hresult(p_file->Load(file_path.c_str(), STGM_READWRITE)); + + LPTSTR last_writer_package_family; + check_hresult(p_file.as()->GetLastWriterPackageFamilyName(&last_writer_package_family)); + check_bool(Package::Current().Id().FamilyName() == last_writer_package_family); + check_hresult(p_file.as()->Remove()); + check_hresult(p_file->Save(file_path.c_str(), TRUE)); - CloseHandle(hPipe); - printDebugMessage(L"Waiting on uwp app to send data."); + logger::log_info(fmt::format(L"Successfully unblocked file \"{}\"", file_path).c_str(), true); + logger::log_info(L"Waiting on uwp app to send data.", true); + return 0; } - else + catch (hresult_error const& e) { - exitApp(); + winrt_error error{ e, true, 3 }; + + logger::log_info( + file_path.empty() + ? L"Failed to unblock file" + : fmt::format(L"Failed to unblock file \"{}\"", file_path).c_str(), + true + ); + + report::dictionary properties{}; + report::add_device_metadata(properties); + logger::log_error(error); + crashes::track_error(error, properties); + analytics::track_event("OnFileUnblockFailed", properties); + + exit_app(error.code()); + return error.code(); } - - return 0; } -VOID launchElevatedProcess() +void launchElevatedProcess() { - TCHAR fileName[MAX_PATH]; - GetModuleFileName(NULL, fileName, MAX_PATH); + report::dictionary properties{}; - SHELLEXECUTEINFO shExInfo + auto handle_launch_error = [&](winrt_error const& ex) { - .cbSize = sizeof(shExInfo), - .fMask = SEE_MASK_NOCLOSEPROCESS, - .hwnd = 0, - .lpVerb = L"runas", - .lpFile = fileName, - .lpParameters = L"", - .lpDirectory = 0, - .nShow = SW_SHOW, - .hInstApp = 0 + settings_key::write(LAST_CHANGED_SETTINGS_APP_INSTANCE_ID_STR, box_value(L"")); + settings_key::write(LAST_CHANGED_SETTINGS_KEY_STR, box_value(LAUNCH_ELEVATED_PROCESS_FAILED_STR)); + + logger::log_info(L"Launching of Elevated Process was cancelled.", true); + properties.insert( + properties.end(), + { + pair("Denied", "True"), + pair("Error Code", to_string(ex.code())), + pair("Error Message", to_string(ex.message())) + } + ); }; - vector> properties; - if (ShellExecuteEx(&shExInfo)) + try { - ApplicationData::Current().LocalSettings().Values().Insert(LastChangedSettingsAppInstanceIdStr, box_value(L"")); - ApplicationData::Current().LocalSettings().Values().Insert(LastChangedSettingsKeyStr, box_value(LaunchElevatedProcessSuccessStr)); + auto file_name = wstring(MAX_PATH, '\0'); + + GetModulePath: + auto result = GetModuleFileName(nullptr, &file_name[0], static_cast(file_name.size())); + check_bool(result); + if (result == file_name.size() && GetLastError() == ERROR_INSUFFICIENT_BUFFER) + { + file_name.resize(2 * file_name.size(), '\0'); + goto GetModulePath; + } - printDebugMessage(L"Elevated Process has been launched."); - properties.push_back(pair("Accepted", "True")); + auto sh_ex_info = SHELLEXECUTEINFO + { + .cbSize = sizeof(SHELLEXECUTEINFO), + .fMask = SEE_MASK_NOCLOSEPROCESS, + .hwnd = 0, + .lpVerb = L"runas", + .lpFile = file_name.c_str(), + .lpParameters = L"", + .lpDirectory = 0, + .nShow = SW_SHOW, + .hInstApp = 0 + }; + + if (ShellExecuteEx(&sh_ex_info)) + { + settings_key::write(LAST_CHANGED_SETTINGS_APP_INSTANCE_ID_STR, box_value(L"")); + settings_key::write(LAST_CHANGED_SETTINGS_KEY_STR, box_value(LAUNCH_ELEVATED_PROCESS_SUCCESS_STR)); + + logger::log_info(L"Elevated Process has been launched.", true); + properties.push_back(pair("Accepted", "True")); + } + else + { + handle_launch_error(winrt_error::get_last_error()); + } + settings_key::signal_changed(); } - else + catch (hresult_error const& e) { - ApplicationData::Current().LocalSettings().Values().Insert(LastChangedSettingsAppInstanceIdStr, box_value(L"")); - ApplicationData::Current().LocalSettings().Values().Insert(LastChangedSettingsKeyStr, box_value(LaunchElevatedProcessFailedStr)); + winrt_error error{ e, true, 3 }; + handle_launch_error(error); + settings_key::signal_changed(); - printDebugMessage(L"Launching of Elevated Process was cancelled."); - pair ex = getLastErrorDetails(); - properties.insert(properties.end(), - { - pair("Denied", "True"), - pair("Error Code", to_string(ex.first)), - pair("Error Message", to_string(ex.second)) - }); + report::add_device_metadata(properties); + logger::log_error(error); + crashes::track_error(error, properties); } - ApplicationData::Current().SignalDataChanged(); - AppCenter::trackEvent("OnAdminstratorPrivilageRequested", properties); + analytics::track_event("OnAdminstratorPrivilageRequested", properties); } -VOID launchElevatedProcessIfRequested() +void launchElevatedProcessIfRequested() { - LPWSTR* szArglist = NULL; - INT nArgs; - szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs); - if (szArglist) + auto n_args = 0; + auto args = array_view(CommandLineToArgvW(GetCommandLineW(), &n_args), 4); + if (n_args < 4) return; + + // Assumed first entry is for uwp app + auto praid = wstring(Package::Current().GetAppListEntries().GetAt(0).AppUserModelId()); + praid.erase(0, praid.find(L"!") + 1); + if (wcscmp(args[1], L"/InvokerPRAID:") == 0 && + wcscmp(args[2], praid.c_str()) == 0 && + wcscmp(args[3], L"/admin") == 0 + ) { - // Assumed first entry is for uwp app - auto aumid = Package::Current().GetAppListEntries().GetAt(0).AppUserModelId(); - wstring praid(aumid); - praid.erase(0, praid.find(L"!") + 1); - if (nArgs > 3 && - wcscmp(szArglist[1], L"/InvokerPRAID:") == 0 && - wcscmp(szArglist[2], praid.c_str()) == 0 && - wcscmp(szArglist[3], L"/admin") == 0) - { - launchElevatedProcess(); - } + launchElevatedProcess(); } - LocalFree(szArglist); } -VOID initializeExtensionService() +void initialize_extension_service() { launchElevatedProcessIfRequested(); - if (!isFirstInstance(ExtensionMutexName)) return; + if (!is_first_instance(EXTENSION_MUTEX_NAME)) return; - ProcessIdToSessionId(GetCurrentProcessId(), &sessionId); - packageSid = unbox_value_or(readSettingsKey(PackageSidStr), L""); + try + { + check_bool(ProcessIdToSessionId(GetCurrentProcessId(), &session_id)); + package_sid = unbox_value(settings_key::read(PACKAGE_SID_STR)); - extensionUnblockEvent = OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, format(NAMED_OBJECT_FORMAT, packageSid, ExtensionUnblockEventNameStr).c_str()); - extensionUnblockPipeName = format(PIPE_NAME_FORMAT, sessionId, packageSid, ExtensionUnblockPipeConnectionNameStr); + unblock_pipe = fmt::format(PIPE_NAME_FORMAT, session_id, package_sid, EXTENSION_UNBLOCK_PIPE_CONNECTION_NAME_STR); - printDebugMessage(L"Successfully started Desktop Extension."); - printDebugMessage(L"Waiting on uwp app to send data."); + logger::log_info(L"Successfully started Desktop Extension.", true); + logger::log_info(L"Waiting on uwp app to send data.", true); - CreateThread(NULL, 0, unblockFileFromPipeData, NULL, 0, NULL); + auto thread = handle(CreateThread(nullptr, 0, unblock_file_from_pipe_data, nullptr, 0, nullptr)); + check_bool(bool(thread)); + } + catch (hresult_error const& e) + { + winrt_error error{ e, true, 3 }; + report::dictionary properties{}; + report::add_device_metadata(properties); + logger::log_error(error); + crashes::track_error(error, properties); + analytics::track_event("OnInitializationForExtensionFailed", properties); + exit_app(e.code()); + } LifeTimeCheck: - HANDLE lifeTimeObj = OpenMutex(SYNCHRONIZE, FALSE, format(L"AppContainerNamedObjects\\{}\\{}", packageSid, ExtensionProcessLifetimeObjNameStr).c_str()); - if (lifeTimeObj) + auto life_time_obj = handle( + OpenMutex( + SYNCHRONIZE, + FALSE, + fmt::format( + L"AppContainerNamedObjects\\{}\\{}", + package_sid, + EXTENSION_PROCESS_LIFETIME_OBJ_NAME_STR + ).c_str() + ) + ); + + if (life_time_obj) { - CloseHandle(lifeTimeObj); + life_time_obj.close(); Sleep(1000); goto LifeTimeCheck; } diff --git a/src/Notepads.DesktopExtension/frame.h b/src/Notepads.DesktopExtension/frame.h new file mode 100644 index 000000000..8b4bce94a --- /dev/null +++ b/src/Notepads.DesktopExtension/frame.h @@ -0,0 +1,177 @@ +#pragma once +#pragma comment(lib, "dbgeng.lib") +#include "pch.h" +#include "dbgeng.h" + +#ifdef _DEBUG +#include "rapidjson/prettywriter.h" +#else +#include "rapidjson/writer.h" +#endif + +__declspec(selectany) winrt::com_ptr symbols; + +struct frame +{ + using from_abi_t = winrt::take_ownership_from_abi_t; + static constexpr auto from_abi{ winrt::take_ownership_from_abi }; + + frame() noexcept = default; + frame(frame&&) = default; + frame& operator=(frame&&) = default; + + frame(frame const& other) noexcept : + m_offset(other.m_offset) + { + } + + frame& operator=(frame const& other) noexcept + { + m_offset = other.m_offset; + return *this; + } + + frame& operator=(uint64_t addr) noexcept + { + m_offset = addr; + return *this; + } + + explicit frame(uint64_t addr) noexcept + : m_offset(addr) + { + } + + template + explicit frame(T* addr) noexcept + : m_offset(reinterpret_cast(addr)) + { + } + + winrt::hstring name() const noexcept + { + originate(); + + if (!symbols) return winrt::to_hstring(m_offset); + + auto name = std::string(256, '\0'); + auto size = uint48_t(0); + auto result = SUCCEEDED( + symbols->GetNameByOffset( + m_offset, + &name[0], + static_cast(name.size()), + &size, + nullptr + ) + ); + + if (!result && size > name.size()) + { + name.resize(size); + result = SUCCEEDED( + symbols->GetNameByOffset( + m_offset, + &name[0], + static_cast(name.size()), + &size, + nullptr + ) + ); + } + + return winrt::to_hstring(name.data()); + } + + winrt::hstring file() const noexcept + { + originate(); + + if (!symbols) return L""; + + auto file = std::string(256, '\0'); + auto size = uint48_t(0); + auto result = SUCCEEDED( + symbols->GetLineByOffset( + m_offset, + nullptr, + &file[0], + static_cast(file.size()), + &size, + nullptr + ) + ); + + if (!result && size > file.size()) + { + file.resize(size); + result = SUCCEEDED( + symbols->GetLineByOffset( + m_offset, + nullptr, + &file[0], + static_cast(file.size()), + &size, + nullptr + ) + ); + } + + return winrt::to_hstring(file.data()); + } + + uint48_t line() const noexcept + { + originate(); + + if (!symbols) return 0; + + auto line = uint48_t(0); + auto result = SUCCEEDED( + symbols->GetLineByOffset(m_offset, &line, 0, 0, 0, 0) + ); + + return (result ? line : 0); + } + + template + void serialize(json_writer& writer) const noexcept + { + if (m_offset <= 0) return; + + auto full_name = winrt::to_string(name()); + auto file_name = winrt::to_string(file()); + auto line_number = line(); + + auto delimiter = full_name.find_first_of('!'); + auto class_name = delimiter == std::string::npos ? full_name : full_name.substr(0, delimiter); + auto method_name = delimiter == std::string::npos ? "" : full_name.substr(delimiter + 1, full_name.length()); + + writer.StartObject(); + writer.String("className"); + writer.String(class_name.c_str(), static_cast(class_name.length())); + writer.String("methodName"); + writer.String(method_name.c_str(), static_cast(method_name.length())); + writer.String("fileName"); + writer.String(file_name.c_str(), static_cast(file_name.length())); + writer.String("lineNumber"); + writer.Uint(line_number); + writer.EndObject(); + } + +private: + + static void originate() noexcept + { + if (!symbols) + { + winrt::com_ptr client = nullptr; + DebugCreate(winrt::guid_of(), client.put_void()); + client->AttachProcess(0, GetCurrentProcessId(), DEBUG_ATTACH_NONINVASIVE | DEBUG_ATTACH_NONINVASIVE_NO_SUSPEND); + client.as()->WaitForEvent(DEBUG_WAIT_DEFAULT, INFINITE); + client.as(symbols); + } + } + + uint64_t m_offset{ 0 }; +}; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/handled_error_report.h b/src/Notepads.DesktopExtension/handled_error_report.h new file mode 100644 index 000000000..b4211bac4 --- /dev/null +++ b/src/Notepads.DesktopExtension/handled_error_report.h @@ -0,0 +1,65 @@ +#pragma once +#include "pch.h" +#include "error.h" +#include "managed_error_report.h" + +struct handled_error_report : managed_error_report +{ + explicit handled_error_report( + winrt_error const& error, + std::vector> const& properties, + std::string const& attachment = "" + ) noexcept : + managed_error_report(error, attachment), m_properties(properties) + { + } + + handled_error_report(handled_error_report const& other) noexcept : + managed_error_report(other), + m_properties(other.m_properties) + { + } + + handled_error_report(handled_error_report&& other) noexcept : + managed_error_report(other) + { + } + +protected: + + virtual void append_type_data(json_writer& writer) const noexcept + { + writer.String("type"); + writer.String("handledError"); + } + + virtual void append_additional_data(json_writer& writer) const noexcept + { + managed_error_report::append_additional_data(writer); + + // Write custom properties if available + if (!m_properties.empty()) + { + writer.String("properties"); + writer.StartObject(); + for (auto& property : m_properties) + { + writer.String(property.first.c_str(), static_cast(property.first.length())); + writer.String(property.second.c_str(), static_cast(property.second.length())); + } + writer.EndObject(); + } + } + + /*virtual void append_report(json_writer& writer) const noexcept + { + report::append_report(writer); + + if (!m_attachment.empty()) + { + error_attachment_report(m_id, m_attachment).serialize(writer); + } + }*/ + + std::vector> m_properties; +}; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/log.h b/src/Notepads.DesktopExtension/log.h deleted file mode 100644 index 478b918cd..000000000 --- a/src/Notepads.DesktopExtension/log.h +++ /dev/null @@ -1,217 +0,0 @@ -#pragma once -#include "pch.h" -#include "device.h" -#include "exception.h" - -namespace AppCenter -{ - using namespace rapidjson; - using namespace std; - using namespace Windows::Foundation; - - enum LogType - { - managedError, - handledError, - errorAttachment, - event - }; - - namespace - { - static const string logTypes[] = { "managedError", "handledError", "errorAttachment", "event" }; - static string launchTimeStamp = getTimeStamp(); - static Device* deviceInfo = NULL; - } - - class Log - { - public: - #pragma region Constructors for managed error report - - Log(LogType type, bool isFatal, Exception* exception) : - _type(type), _fatal(isFatal), _exception(exception) - { - InitializeLog(); - } - - #pragma endregion - - #pragma region Constructors for handled error report - - Log(LogType type, bool isFatal, Exception* exception, const vector>& properties) : - _type(type), _fatal(isFatal), _exception(exception), _properties(properties) - { - InitializeLog(); - } - - #pragma endregion - - #pragma region Constructor for error attachment - - Log(LogType type, const string& errorId, const string& data) : - _type(type), _errorId(errorId), _data(data) - { - InitializeLog(); - } - - #pragma endregion - - #pragma region Constructor for event report - - Log(LogType type, const string& sid, const string& name, const vector>& properties) : - _type(type), _sid(sid), _name(name), _properties(properties) - { - InitializeLog(); - } - - #pragma endregion - - Log(const Log& log) : - _type(log._type), _contentType(log._contentType), _name(log._name), _timestamp(log._timestamp), - _processId(log._processId), _id(log._id), _sid(log._sid), _fatal(log._fatal), _processName(log._processName), - _errorThreadId(log._errorThreadId), _data(log._data), _errorId(log._errorId), - _exception(NULL), _properties(log._properties) - { - _exception = (log._exception == 0) ? 0 : new Exception(*log._exception); - } - - ~Log() - { - delete _exception; - } - - Log& operator=(const Log& log) - { - if (this == &log) return *this; - - delete _exception; - _type = log._type; - _timestamp = log._timestamp; - _id = log._id; - _sid = log._sid; - _processId = log._processId; - _fatal = log._fatal; - _processName = log._processName; - _errorThreadId = log._errorThreadId; - _exception = (log._exception == 0) ? 0 : new Exception(*log._exception); - _contentType = log._contentType; - _data = log._data; - _errorId = log._errorId; - _name = log._name; - _properties = log._properties; - return *this; - } - - template - VOID Serialize(Writer& writer) const - { - writer.StartObject(); - - writer.String("type"); - writer.String(logTypes[_type].c_str(), static_cast(logTypes[_type].length())); - writer.String("timestamp"); - writer.String(_timestamp.c_str(), static_cast(_timestamp.length())); - writer.String("appLaunchTimestamp"); - writer.String(launchTimeStamp.c_str(), static_cast(launchTimeStamp.length())); - writer.String("id"); - writer.String(_id.c_str(), static_cast(_id.length())); - - if (!_sid.empty()) - { - writer.String("sid"); - writer.String(_sid.c_str(), static_cast(_sid.length())); - } - - switch (_type) - { - case LogType::managedError: - case LogType::handledError: - writer.String("processId"); - writer.Uint(_processId); - writer.String("fatal"); - writer.Bool(_fatal); - writer.String("processName"); - writer.String(_processName.c_str(), static_cast(_processName.length())); - writer.String("errorThreadId"); - writer.Uint(_errorThreadId); - - // Write exception data - writer.String("exception"); - _exception->Serialize(writer); - break; - case LogType::errorAttachment: - writer.String("contentType"); - writer.String(_contentType.c_str(), static_cast(_contentType.length())); - writer.String("data"); - writer.String(_data.c_str(), static_cast(_data.length())); - writer.String("errorId"); - writer.String(_errorId.c_str(), static_cast(_errorId.length())); - break; - case LogType::event: - writer.String("name"); - writer.String(_name.c_str(), static_cast(_name.length())); - break; - } - - // Write device specific data - writer.String("device"); - deviceInfo->Serialize(writer); - - // Write custom properties if available - if (!_properties.empty()) - { - writer.String("properties"); - writer.StartObject(); - for (vector>::const_iterator property = _properties.begin(); property != _properties.end(); ++property) - { - writer.String(property->first); - writer.String(property->second.c_str(), static_cast(property->second.length())); - } - writer.EndObject(); - } - - writer.EndObject(); - } - - inline const string& Id() { return _id; } - inline const string& Sid() { return _sid; } - - private: - LogType _type; - string _contentType = "text/plain"; - string _name; - string _timestamp = getTimeStamp(); - unsigned _processId; - string _id; - string _sid; - bool _fatal = false; - string _processName = "Notepads32.exe"; - unsigned _errorThreadId = 0; - string _data; - string _errorId; - Exception* _exception = NULL; - vector> _properties; - - VOID InitializeLog() - { - _id = to_string(to_hstring(GuidHelper::CreateNewGuid())); - _id.erase(0, _id.find_first_not_of('{')).erase(_id.find_last_not_of('}') + 1); - - switch (_type) - { - case LogType::managedError: - case LogType::handledError: - _sid = to_string(to_hstring(GuidHelper::CreateNewGuid())); - _sid.erase(0, _sid.find_first_not_of('{')).erase(_sid.find_last_not_of('}') + 1); - _processId = GetCurrentProcessId(); - _errorThreadId = GetCurrentThreadId(); - break; - case LogType::errorAttachment: - break; - case LogType::event: - break; - } - } - }; -} \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/logger.h b/src/Notepads.DesktopExtension/logger.h new file mode 100644 index 000000000..0b092dd33 --- /dev/null +++ b/src/Notepads.DesktopExtension/logger.h @@ -0,0 +1,93 @@ +#pragma once +#include "pch.h" +#include "error.h" + +#define LOG_FILE_FORMAT L"{year.full}{month.integer(2)}{day.integer(2)}" \ + "T{hour.integer(2)}{minute.integer(2)}{second.integer(2)}" +#define LOG_FORMAT L"{month.integer(2)}/{day.integer(2)}/{year.full} " \ + "{hour.integer(2)}:{minute.integer(2)}:{second.integer(2)}" + +__declspec(selectany) winrt::Windows::Storage::StorageFile log_file = nullptr; + +struct logger +{ + using FileIO = winrt::Windows::Storage::FileIO; + using StorageFile = winrt::Windows::Storage::StorageFile; + using ApplicationData = winrt::Windows::Storage::ApplicationData; + using CreationCollisionOption = winrt::Windows::Storage::CreationCollisionOption; + using DateTimeFormatter = winrt::Windows::Globalization::DateTimeFormatting::DateTimeFormatter; + + static winrt::fire_and_forget start(bool elevated) noexcept + { + DateTimeFormatter log_file_formatter{ LOG_FILE_FORMAT }; + auto local_folder = ApplicationData::Current().LocalFolder(); + auto log_folder = co_await local_folder.CreateFolderAsync(L"Logs", CreationCollisionOption::OpenIfExists); + log_file = co_await log_folder.CreateFileAsync( + log_file_formatter.Format(winrt::clock::now()) + + winrt::to_hstring(elevated ? L"-extension.log" : L"-elevated-extension.log"), + CreationCollisionOption::OpenIfExists + ); + } + + static void log_error(winrt_error const& error) noexcept + { + std::wstring formatted_message = fmt::format( + L"{} [Error] HResult Error {}: {}\n{}\n", + get_time_stamp(LOG_FORMAT), + error.code(), + error.message(), + error.stacktrace() + ); + + logger::print(formatted_message.c_str()); + + if (log_file) + { + FileIO::AppendTextAsync(log_file, formatted_message).get(); + } + } + + static void log_info(winrt::hstring const& message, bool console_only = true) noexcept + { + std::wstring formatted_message = fmt::format( + L"{} [Info] {}\n", + get_time_stamp(LOG_FORMAT), + message + ); + + logger::print(formatted_message.c_str()); + + if (!console_only && log_file) + { + FileIO::AppendTextAsync(log_file, formatted_message).get(); + } + } + +#ifdef _DEBUG + static void print(winrt::hstring const& message, uint48_t sleep = 0) noexcept + { + wprintf_s(L"%ls", message.c_str()); + Sleep(sleep); +#else + static void print(winrt::hstring const& message, uint48_t /* sleep */) noexcept + { +#endif + OutputDebugStringW(message.c_str()); + } + + static winrt::hstring get_time_stamp(winrt::hstring const& format) noexcept + { + return DateTimeFormatter(format).Format(winrt::clock::now()); + } + + static winrt::hstring get_utc_time_stamp(winrt::hstring const& format) noexcept + { + return DateTimeFormatter(format).Format(winrt::clock::now(), L"UTC"); + } + +private: + + logger() noexcept = default; + logger(logger&&) noexcept = default; + logger(logger const& other) noexcept = default; +}; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index ce11e7599..50f9a3676 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -1,111 +1,99 @@ #include "pch.h" +#include "logger.h" #include "appcenter.h" +using namespace std; using namespace winrt; +using namespace Windows::ApplicationModel; +using namespace Windows::System; +using namespace Windows::System::UserProfile; -extern HANDLE extensionUnblockEvent; -extern HANDLE elevatedWriteEvent; -extern HANDLE elevatedRenameEvent; - -INT releaseResources() +void exit_app(int code) { - CloseHandle(extensionUnblockEvent); - CloseHandle(elevatedWriteEvent); - CloseHandle(elevatedRenameEvent); - AppCenter::exit(); uninit_apartment(); - return 0; -} - -VOID exitApp() -{ - exit(0); -} - -VOID onUnhandledException() -{ - logLastError(true).get(); - exitApp(); + exit(code); } -VOID onUnexpectedException() -{ - logLastError(false).get(); - exitApp(); -} - -VOID setExceptionHandling() -{ - set_terminate(onUnhandledException); - set_unexpected(onUnexpectedException); -} - -bool isFirstInstance(LPCTSTR mutexName) +bool is_first_instance(hstring mutex_name) { auto result = true; - HANDLE hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, mutexName); + auto hMutex = handle(OpenMutex(MUTEX_ALL_ACCESS, FALSE, mutex_name.c_str())); if (!hMutex) { - CreateMutex(NULL, FALSE, mutexName); + try + { + check_bool(CreateMutex(nullptr, FALSE, mutex_name.c_str())); + } + catch (hresult_error const& e) + { + winrt_error error{ e, true, 3 }; + report::dictionary properties{}; + report::add_device_metadata(properties); + logger::log_error(error); + crashes::track_error(error, properties); + analytics::track_event("OnExtensionInstanceDetectionFailed", properties); + exit_app(e.code()); + } #ifdef _DEBUG - initializeLogging(wcscmp(mutexName, ExtensionMutexName) == 0 ? L"-extension.log" : L"-elevated-extension.log"); + logger::start(mutex_name == EXTENSION_MUTEX_NAME); #endif } else { result = false; - printDebugMessage(L"Closing this instance as another instance is already running.", 3000); - exitApp(); + logger::print(L"Closing this instance as another instance is already running.\n", 3000); + exit_app(); } - if (hMutex) ReleaseMutex(hMutex); - + return result; } -bool isElevatedProcess() +bool is_elevated_process() { - auto result = false; - - HANDLE hToken = NULL; - if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken)) + try { - TOKEN_ELEVATION Elevation; - DWORD cbSize = sizeof(TOKEN_ELEVATION); - if (GetTokenInformation(hToken, TokenElevation, &Elevation, sizeof(Elevation), &cbSize)) - { - result = Elevation.TokenIsElevated; - } + handle h_token; + check_bool(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, h_token.put())); + TOKEN_ELEVATION elevation; + auto size = static_cast(sizeof(elevation)); + check_bool(GetTokenInformation(h_token.get(), TokenElevation, &elevation, sizeof(elevation), &size)); + return elevation.TokenIsElevated; } - - if (hToken) + catch (hresult_error const& e) { - CloseHandle(hToken); + winrt_error error{ e, true, 3 }; + report::dictionary properties{}; + report::add_device_metadata(properties); + crashes::track_error(error, properties); + analytics::track_event("OnPrivilageDetectionFailed", properties); + return false; } - - return result; } #ifndef _DEBUG -INT APIENTRY wWinMain(_In_ HINSTANCE /* hInstance */, _In_opt_ HINSTANCE /* hPrevInstance */, _In_ LPWSTR /* lpCmdLine */, _In_ INT /* nCmdShow */) +int APIENTRY wWinMain( + _In_ HINSTANCE /* hInstance */, + _In_opt_ HINSTANCE /* hPrevInstance */, + _In_ LPWSTR /* lpCmdLine */, + _In_ int /* nCmdShow */ +) #else -INT main() +int main() #endif { - setExceptionHandling(); - SetErrorMode(SEM_NOGPFAULTERRORBOX); - _onexit(releaseResources); - init_apartment(); - AppCenter::start(); + appcenter::start(); - if (isElevatedProcess()) + if (is_elevated_process()) { - initializeElevatedService(); + initialize_elevated_service(); } else { - initializeExtensionService(); + initialize_extension_service(); } + + uninit_apartment(); } \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/managed_error_report.h b/src/Notepads.DesktopExtension/managed_error_report.h new file mode 100644 index 000000000..3fe5db90d --- /dev/null +++ b/src/Notepads.DesktopExtension/managed_error_report.h @@ -0,0 +1,82 @@ +#pragma once +#include "pch.h" +#include "error.h" +#include "error_attachment_report.h" + +struct managed_error_report : report +{ + explicit managed_error_report(winrt_error const& error, std::string const& attachment = "") noexcept : + report(), m_error(error), m_attachment(attachment) + { + m_sid = winrt::to_string(winrt::to_hstring(winrt::Windows::Foundation::GuidHelper::CreateNewGuid())); + m_sid.erase(0, m_sid.find_first_not_of('{')).erase(m_sid.find_last_not_of('}') + 1); + } + + managed_error_report(managed_error_report const& other) noexcept : + report(other), + m_pid(other.m_pid), + m_thread(other.m_thread), + m_sid(other.m_sid), + m_process(other.m_process), + m_error(other.m_error), + m_attachment(other.m_attachment) + { + } + + managed_error_report(managed_error_report&& other) noexcept : + report(other), + m_error(other.m_error), + m_attachment(other.m_attachment) + { + } + + std::string sid() const noexcept + { + return m_sid; + } + +protected: + + virtual void append_type_data(json_writer& writer) const noexcept + { + writer.String("type"); + writer.String("managedError"); + } + + virtual void append_additional_data(json_writer& writer) const noexcept + { + report::append_additional_data(writer); + + writer.String("sid"); + writer.String(m_sid.c_str(), static_cast(m_sid.length())); + writer.String("processId"); + writer.Uint(m_pid); + writer.String("fatal"); + writer.Bool(m_error.fatal()); + writer.String("processName"); + writer.String(m_process.c_str(), static_cast(m_process.length())); + writer.String("errorThreadId"); + writer.Uint(m_thread); + + // Write exception data + writer.String("exception"); + m_error.serialize(writer); + } + + virtual void append_report(json_writer& writer) const noexcept + { + report::append_report(writer); + + if (!m_attachment.empty()) + { + error_attachment_report(m_id, m_attachment).serialize(writer); + } + } + + unsigned m_pid = GetCurrentProcessId(); + unsigned m_thread = GetCurrentThreadId(); + std::string m_sid; + std::string m_process = "Notepads32.exe"; + std::string m_attachment; + winrt_error m_error; +}; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/pch.cpp b/src/Notepads.DesktopExtension/pch.cpp index 772a0d164..331e647d7 100644 --- a/src/Notepads.DesktopExtension/pch.cpp +++ b/src/Notepads.DesktopExtension/pch.cpp @@ -1,134 +1 @@ -#include "pch.h" -#include "appcenter.h" - -#define MAX_TIME_STR 20 -#define MAX_DATE_STR 20 -#define MAX_DATETIME_STR 100 - -using namespace boost::stacktrace; -using namespace boost::stacktrace::detail; -using namespace fmt; -using namespace std; -using namespace winrt; -using namespace Windows::Foundation; -using namespace Windows::Storage; -using namespace Windows::System; - -StorageFile logFile = NULL; - -VOID printDebugMessage([[maybe_unused]] LPCTSTR message, [[maybe_unused]] DWORD sleepTime) { -#ifdef _DEBUG - wcout << message << endl; - Sleep(sleepTime); -#endif -} - -string to_string(ProcessorArchitecture arch) -{ - switch (arch) - { - case ProcessorArchitecture::Arm: - return "Arm"; - case ProcessorArchitecture::Arm64: - return "Arm64"; - case ProcessorArchitecture::X86OnArm64: - return "X86OnArm64"; - case ProcessorArchitecture::X86: - return "X86"; - case ProcessorArchitecture::X64: - return "X64"; - case ProcessorArchitecture::Neutral: - return "Neutral"; - default: - return "Unknown"; - } -} - -string getTimeStamp() -{ - SYSTEMTIME systemTime; - GetSystemTime(&systemTime); - return format("{}.{}Z", getTimeStamp("%FT%T"), systemTime.wMilliseconds); -} - -string getTimeStamp(const CHAR* format) -{ - time_t timePast = time(NULL); - tm utcTime; - gmtime_s(&utcTime, &timePast); - CHAR timeStamp[MAX_DATETIME_STR]; - strftime(timeStamp, sizeof(timeStamp), format, &utcTime); - return timeStamp; -} - -//From https://stackoverflow.com/a/34571089/5155484 -static const string b = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -string base64_encode(const string& in) -{ - string out; - - INT val = 0, valb = -6; - for (UCHAR c : in) { - val = (val << 8) + c; - valb += 8; - while (valb >= 0) { - out.push_back(b[(val >> valb) & 0x3F]); - valb -= 6; - } - } - if (valb > -6) out.push_back(b[((val << 8) >> (valb + 8)) & 0x3F]); - while (out.size() % 4) out.push_back('='); - return out; -} - -pair getLastErrorDetails() -{ - LPVOID msgBuf; - DWORD errorCode = GetLastError(); - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - errorCode, - 0, - (LPTSTR)&msgBuf, - 0, - NULL); - - wstring msg; - getline(wstringstream((LPCTSTR)msgBuf), msg, L'\r'); - LocalFree(msgBuf); - - return pair { errorCode, msg }; -} - -IAsyncAction logLastError(bool isFatal) -{ - stacktrace st = stacktrace(); - hstring stackTrace = to_hstring(to_string(&st.as_vector()[0], st.size())); - - pair ex = getLastErrorDetails(); - - printDebugMessage(stackTrace.c_str(), 5000); - AppCenter::trackError(isFatal, ex.first, to_string(ex.second), st); - - if (logFile) - { - SYSTEMTIME systemTime; - GetSystemTime(&systemTime); - TCHAR timeStr[MAX_TIME_STR]; - GetTimeFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, NULL, timeStr, MAX_TIME_STR); - TCHAR dateStr[MAX_DATE_STR]; - GetDateFormatEx(LOCALE_NAME_INVARIANT, 0, &systemTime, NULL, dateStr, MAX_DATE_STR, NULL); - wstring debugMsg = format(L"{} {} [Error] [Error Code: {}] {}{}\n{}\n", - dateStr, timeStr, ex.first, isFatal ? L"OnUnhandledException: " : L"OnUnexpectedException: ", ex.second, stackTrace); - - co_await PathIO::AppendTextAsync(logFile.Path(), debugMsg); - } -} - -fire_and_forget initializeLogging(LPCTSTR trailStr) -{ - auto localFolder = ApplicationData::Current().LocalFolder(); - auto logFolder = co_await localFolder.CreateFolderAsync(L"Logs", CreationCollisionOption::OpenIfExists); - logFile = co_await logFolder.CreateFileAsync(to_hstring(getTimeStamp("%Y%m%dT%H%M%S")) + to_hstring(trailStr), CreationCollisionOption::OpenIfExists); -} \ No newline at end of file +#include "pch.h" \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h index c8c931d84..5b8e125f1 100644 --- a/src/Notepads.DesktopExtension/pch.h +++ b/src/Notepads.DesktopExtension/pch.h @@ -3,58 +3,48 @@ #include "iostream" #include "sstream" #include "windows.h" -#include "shellapi.h" #include "shlobj_core.h" #include "winrt/Windows.ApplicationModel.h" #include "winrt/Windows.ApplicationModel.Core.h" #include "winrt/Windows.Foundation.h" #include "winrt/Windows.Foundation.Collections.h" +#include "winrt/Windows.Globalization.DateTimeFormatting.h" #include "winrt/Windows.Security.ExchangeActiveSyncProvisioning.h" #include "winrt/Windows.Storage.h" #include "winrt/Windows.Storage.AccessCache.h" #include "winrt/Windows.System.h" #include "winrt/Windows.System.Profile.h" +#include "winrt/Windows.System.UserProfile.h" #include "winrt/Notepads.Core.h" -#include "boost/stacktrace.hpp" #include "fmt/core.h" -#define ExtensionMutexName L"ExtensionMutex" -#define ElevatedMutexName L"ElevatedMutex" +#define EXTENSION_MUTEX_NAME L"ExtensionMutex" +#define ELEVATED_MUTEX_NAME L"ElevatedMutex" #define PIPE_READ_BUFFER 2 * MAX_PATH + 10 #define PIPE_NAME_FORMAT L"\\\\.\\pipe\\Sessions\\{}\\AppContainerNamedObjects\\{}\\{}" #define NAMED_OBJECT_FORMAT L"AppContainerNamedObjects\\{}\\{}" -#define AppCenterSecret winrt::Notepads::Core::CoreKey::AppCenterSecret().c_str() -#define PackageSidStr winrt::Notepads::Core::CoreKey::PackageSidStr().c_str() -#define AppCenterInstallIdStr winrt::Notepads::Core::CoreKey::AppCenterInstallIdStr().c_str() -#define LastChangedSettingsKeyStr winrt::Notepads::Core::CoreKey::LastChangedSettingsKeyStr().c_str() -#define LastChangedSettingsAppInstanceIdStr winrt::Notepads::Core::CoreKey::LastChangedSettingsAppInstanceIdStr().c_str() -#define LaunchElevatedProcessSuccessStr winrt::Notepads::Core::CoreKey::LaunchElevatedProcessSuccessStr().c_str() -#define LaunchElevatedProcessFailedStr winrt::Notepads::Core::CoreKey::LaunchElevatedProcessFailedStr().c_str() -#define ExtensionProcessLifetimeObjNameStr winrt::Notepads::Core::CoreKey::ExtensionProcessLifetimeObjNameStr().c_str() -#define ElevatedProcessLifetimeObjNameStr winrt::Notepads::Core::CoreKey::ElevatedProcessLifetimeObjNameStr().c_str() -#define ExtensionUnblockEventNameStr winrt::Notepads::Core::CoreKey::ExtensionUnblockEventNameStr().c_str() -#define ElevatedWriteEventNameStr winrt::Notepads::Core::CoreKey::ElevatedWriteEventNameStr().c_str() -#define ElevatedRenameEventNameStr winrt::Notepads::Core::CoreKey::ElevatedRenameEventNameStr().c_str() -#define ExtensionUnblockPipeConnectionNameStr winrt::Notepads::Core::CoreKey::ExtensionUnblockPipeConnectionNameStr().c_str() -#define ElevatedWritePipeConnectionNameStr winrt::Notepads::Core::CoreKey::ElevatedWritePipeConnectionNameStr().c_str() -#define ElevatedRenamePipeConnectionNameStr winrt::Notepads::Core::CoreKey::ElevatedRenamePipeConnectionNameStr().c_str() +typedef unsigned long uint48_t; +typedef winrt::Notepads::Core::CoreKey CoreKey; -VOID setExceptionHandling(); -bool isElevatedProcess(); -bool isFirstInstance(LPCTSTR mutexName); -VOID initializeExtensionService(); -VOID initializeElevatedService(); -VOID exitApp(); +#define PACKAGE_SID_STR CoreKey::PackageSidStr().c_str() +#define APP_CENTER_INSTALL_ID_STR CoreKey::AppCenterInstallIdStr().c_str() +#define LAST_CHANGED_SETTINGS_KEY_STR CoreKey::LastChangedSettingsKeyStr().c_str() +#define LAST_CHANGED_SETTINGS_APP_INSTANCE_ID_STR CoreKey::LastChangedSettingsAppInstanceIdStr().c_str() +#define LAUNCH_ELEVATED_PROCESS_SUCCESS_STR CoreKey::LaunchElevatedProcessSuccessStr().c_str() +#define LAUNCH_ELEVATED_PROCESS_FAILED_STR CoreKey::LaunchElevatedProcessFailedStr().c_str() +#define EXTENSION_PROCESS_LIFETIME_OBJ_NAME_STR CoreKey::ExtensionProcessLifetimeObjNameStr().c_str() +#define ELEVATED_PROCESS_LIFETIME_OBJ_NAME_STR CoreKey::ElevatedProcessLifetimeObjNameStr().c_str() +#define EXTENSION_UNBLOCK_EVENT_NAME_STR CoreKey::ExtensionUnblockEventNameStr().c_str() +#define ELEVATED_WRITE_EVENT_NAME_STR CoreKey::ElevatedWriteEventNameStr().c_str() +#define ELEVATED_RENAME_EVENT_NAME_STR CoreKey::ElevatedRenameEventNameStr().c_str() +#define EXTENSION_UNBLOCK_PIPE_CONNECTION_NAME_STR CoreKey::ExtensionUnblockPipeConnectionNameStr().c_str() +#define ELEVATED_WRITE_PIPE_CONNECTION_NAME_STR CoreKey::ElevatedWritePipeConnectionNameStr().c_str() +#define ELEVATED_RENAME_PIPE_CONNECTION_NAME_STR CoreKey::ElevatedRenamePipeConnectionNameStr().c_str() -VOID printDebugMessage([[maybe_unused]] LPCTSTR message, [[maybe_unused]] DWORD sleepTime = 0); -std::string getTimeStamp(); -std::string getTimeStamp(const CHAR* format); -std::string to_string(winrt::Windows::System::ProcessorArchitecture arch); -std::string base64_encode(const std::string& in); - -winrt::Windows::Foundation::IInspectable readSettingsKey(winrt::hstring key); -std::pair getLastErrorDetails(); -winrt::Windows::Foundation::IAsyncAction logLastError(bool isFatal); -winrt::fire_and_forget initializeLogging(LPCTSTR trailStr); \ No newline at end of file +bool is_elevated_process(); +bool is_first_instance(winrt::hstring mutexName); +void initialize_extension_service(); +void initialize_elevated_service(); +void exit_app(int code = 0); \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/report.h b/src/Notepads.DesktopExtension/report.h new file mode 100644 index 000000000..d86c274e6 --- /dev/null +++ b/src/Notepads.DesktopExtension/report.h @@ -0,0 +1,128 @@ +#pragma once +#include "pch.h" +#include "logger.h" + +#define APP_CENTER_FORMAT L"{year.full}-{month.integer(2)}-{day.integer(2)}" \ + "T{hour.integer(2)}:{minute.integer(2)}:{second.integer(2)}Z" + +const std::string launch_time_stamp = winrt::to_string( + logger::get_utc_time_stamp(APP_CENTER_FORMAT) +); + +__declspec(selectany) std::string last_error_report_sid = ""; +__declspec(selectany) device device_info {}; + +struct report +{ +#ifdef _DEBUG + using json_writer = rapidjson::PrettyWriter; +#else + using json_writer = rapidjson::Writer; +#endif + using Package = winrt::Windows::ApplicationModel::Package; + using MemoryManager = winrt::Windows::System::MemoryManager; + using dictionary = std::vector>; + using ProcessorArchitecture = winrt::Windows::System::ProcessorArchitecture; + + virtual void serialize(json_writer& writer) const noexcept + { + writer.StartObject(); + + // Write report type data + append_type_data(writer); + + writer.String("id"); + writer.String(m_id.c_str(), static_cast(m_id.length())); + writer.String("timestamp"); + writer.String(m_timestamp.c_str(), static_cast(m_timestamp.length())); + writer.String("appLaunchTimestamp"); + writer.String(launch_time_stamp.c_str(), static_cast(launch_time_stamp.length())); + writer.String("architecture"); + writer.String(m_arch.c_str(), static_cast(m_arch.length())); + + // Write report specific data + append_additional_data(writer); + + // Write device specific data + writer.String("device"); + device_info.serialize(writer); + + writer.EndObject(); + + // Write additional report data + append_report(writer); + } + + static std::string to_string(ProcessorArchitecture arch) noexcept + { + switch (arch) + { + case ProcessorArchitecture::Arm: + return "Arm"; + case ProcessorArchitecture::Arm64: + return "Arm64"; + case ProcessorArchitecture::X86OnArm64: + return "X86OnArm64"; + case ProcessorArchitecture::X86: + return "X86"; + case ProcessorArchitecture::X64: + return "X64"; + case ProcessorArchitecture::Neutral: + return "Neutral"; + default: + return "Unknown"; + } + } + + static void add_device_metadata(dictionary& properties) noexcept + { + properties.insert( + properties.end(), + { + std::pair("AvailableMemory", std::to_string((float)MemoryManager::AppMemoryUsageLimit() / 1024 / 1024)), + std::pair("OSArchitecture", to_string(Package::Current().Id().Architecture())), + std::pair("OSVersion",device_info.osbuild()), + std::pair("IsDesktopExtension", "True"), + std::pair("IsElevated", is_elevated_process() ? "True" : "False") + } + ); + } + +protected: + + report() noexcept + { + m_id = winrt::to_string(winrt::to_hstring(winrt::Windows::Foundation::GuidHelper::CreateNewGuid())); + m_id.erase(0, m_id.find_first_not_of('{')).erase(m_id.find_last_not_of('}') + 1); + } + + report(report const& other) noexcept : + m_id(other.m_id), + m_process(other.m_process), + m_arch(other.m_arch), + m_timestamp(other.m_timestamp) + { + } + + report(report&&) noexcept = default; + + virtual void append_type_data(json_writer& /* writer */) const noexcept + { + // override in child classes + } + + virtual void append_additional_data(json_writer& /* writer */) const noexcept + { + // override in child classes + } + + virtual void append_report(json_writer& /* writer */) const noexcept + { + // override in child classes + } + + std::string m_id; + std::string m_process = "Notepads32.exe"; + std::string m_arch = to_string(Package::Current().Id().Architecture()); + std::string m_timestamp = winrt::to_string(logger::get_utc_time_stamp(APP_CENTER_FORMAT)); +}; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/resource.h b/src/Notepads.DesktopExtension/resource.h deleted file mode 100644 index 72d6e0329..000000000 --- a/src/Notepads.DesktopExtension/resource.h +++ /dev/null @@ -1,17 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by AssemblyInfo.rc -// -#define APPCENTER_SDK_VERSION 101 -#define TEXTFILE 256 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 103 -#endif -#endif diff --git a/src/Notepads.DesktopExtension/settings_key.h b/src/Notepads.DesktopExtension/settings_key.h new file mode 100644 index 000000000..857fefa2d --- /dev/null +++ b/src/Notepads.DesktopExtension/settings_key.h @@ -0,0 +1,29 @@ +#pragma once +#include "pch.h" + +struct settings_key +{ + using IInspectable = winrt::Windows::Foundation::IInspectable; + using ApplicationData = winrt::Windows::Storage::ApplicationData; + + static IInspectable read(winrt::hstring key) noexcept + { + return ApplicationData::Current().LocalSettings().Values().TryLookup(key); + } + + static void write(winrt::hstring key, IInspectable data) noexcept + { + ApplicationData::Current().LocalSettings().Values().Insert(key, data); + } + + static void signal_changed() noexcept + { + ApplicationData::Current().SignalDataChanged(); + } + +private: + + settings_key() noexcept = default; + settings_key(settings_key&&) noexcept = default; + settings_key(settings_key const& other) noexcept = default; +}; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/vcpkg.json b/src/Notepads.DesktopExtension/vcpkg.json index 22a4aea9b..efc24636c 100644 --- a/src/Notepads.DesktopExtension/vcpkg.json +++ b/src/Notepads.DesktopExtension/vcpkg.json @@ -3,20 +3,11 @@ "version": "1.0.0.0", "builtin-baseline": "75522bb1f2e7d863078bcd06322348f053a9e33f", "dependencies": [ - "boost-stacktrace", "curl", "fmt", - "rapidjson", - { - "name": "boost-build", - "host": true - } + "rapidjson" ], "overrides": [ - { - "name": "boost-stacktrace", - "version": "1.75.0" - }, { "name": "curl", "version": "7.74.0", diff --git a/src/Notepads/App.xaml.cs b/src/Notepads/App.xaml.cs index d0bbf6d66..bf713de47 100644 --- a/src/Notepads/App.xaml.cs +++ b/src/Notepads/App.xaml.cs @@ -9,7 +9,6 @@ using Microsoft.AppCenter.Analytics; using Microsoft.AppCenter.Crashes; using Microsoft.Toolkit.Uwp.Helpers; - using Notepads.Core; using Notepads.Services; using Notepads.Settings; using Notepads.Utilities; @@ -32,6 +31,9 @@ sealed partial class App : Application public static bool IsPrimaryInstance = false; public static bool IsGameBarWidget = false; + // Notepads GitHub CD workflow will swap null with production value getting from Github Secrets + private const string AppCenterSecret = null; + public static Mutex InstanceHandlerMutex { get; set; } /// @@ -44,7 +46,7 @@ public App() TaskScheduler.UnobservedTaskException += OnUnobservedException; var services = new Type[] { typeof(Crashes), typeof(Analytics) }; - AppCenter.Start(CoreKey.AppCenterSecret, services); + AppCenter.Start(AppCenterSecret, services); InstanceHandlerMutex = new Mutex(true, App.ApplicationName, out bool isNew); if (isNew) diff --git a/src/Notepads/Utilities/FileSystemUtility.cs b/src/Notepads/Utilities/FileSystemUtility.cs index 3c4097c9f..4f4e02064 100644 --- a/src/Notepads/Utilities/FileSystemUtility.cs +++ b/src/Notepads/Utilities/FileSystemUtility.cs @@ -206,7 +206,7 @@ public static string GetAbsolutePathFromCommandLine(string dir, string args, str } } - // Replace all forward slash with platform supported directory separator + // Replace all forward slash with platform supported directory separator path = path.Trim('/').Replace('/', Path.DirectorySeparatorChar); if (IsFullPath(path)) @@ -585,7 +585,7 @@ public static async Task WriteToFile(string text, Encoding encoding, StorageFile await DesktopExtensionService.SaveFileAsAdmin(file.Path, result); } } - else // Use StorageFile API to save + else // Use StorageFile API to save { using (var stream = await file.OpenStreamForWriteAsync()) using (var writer = new StreamWriter(stream, encoding)) From 312df810ca784ba95397b1f8060891e10bfe49dd Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 22 May 2021 22:06:16 +0530 Subject: [PATCH 175/181] chore: code refactor. --- src/Notepads.DesktopExtension/AssemblyInfo.rc | 5 + src/Notepads.DesktopExtension/curl_client.h | 51 +++++++- src/Notepads.DesktopExtension/device.h | 10 +- src/Notepads.DesktopExtension/elevated.cpp | 118 +++++++++++++----- src/Notepads.DesktopExtension/error.h | 2 +- src/Notepads.DesktopExtension/extension.cpp | 58 ++++----- src/Notepads.DesktopExtension/frame.h | 6 +- .../handled_error_report.h | 4 +- src/Notepads.DesktopExtension/logger.h | 7 +- src/Notepads.DesktopExtension/main.cpp | 12 +- 10 files changed, 189 insertions(+), 84 deletions(-) diff --git a/src/Notepads.DesktopExtension/AssemblyInfo.rc b/src/Notepads.DesktopExtension/AssemblyInfo.rc index c8032a45e..3753c120b 100644 --- a/src/Notepads.DesktopExtension/AssemblyInfo.rc +++ b/src/Notepads.DesktopExtension/AssemblyInfo.rc @@ -48,8 +48,13 @@ BEGIN BEGIN BLOCK "000004b0" BEGIN +#ifdef _PRODUCTION + VALUE "FileDescription", "Notepads" + VALUE "ProductName", "Notepads" +#else VALUE "FileDescription", "Notepads-Dev" VALUE "ProductName", "Notepads-Dev" +#endif VALUE "FileVersion", "1.0.0.0" VALUE "InternalName", "Notepads.DesktopExtension" VALUE "LegalCopyright", "Copyright 2020 Jackie Liu" diff --git a/src/Notepads.DesktopExtension/curl_client.h b/src/Notepads.DesktopExtension/curl_client.h index b0807f21d..7bccf16f7 100644 --- a/src/Notepads.DesktopExtension/curl_client.h +++ b/src/Notepads.DesktopExtension/curl_client.h @@ -46,20 +46,17 @@ struct curl_client curl_easy_setopt(curl.get(), CURLOPT_COPYPOSTFIELDS, data.c_str()); #ifdef _DEBUG - logger::print(L"\n\n\n"); - logger::print(winrt::to_hstring(data), 2000); - logger::print(L"\n\n\n"); + curl_easy_setopt(curl.get(), CURLOPT_DEBUGFUNCTION, debug_callback); curl_easy_setopt(curl.get(), CURLOPT_VERBOSE, 1L); #endif auto res = curl_easy_perform(curl.get()); if (res != CURLE_OK) { - logger::print( + logger::log_info( fmt::format( L"curl_easy_perform() failed: {}", - winrt::to_hstring(curl_easy_strerror(res) - ) + winrt::to_hstring(curl_easy_strerror(res)) ).c_str() ); } @@ -67,6 +64,48 @@ struct curl_client private: +#ifdef _DEBUG + static int debug_callback(curl_handle /* handle */, curl_infotype type, char* data, size_t size, void* /* userp */) + { + std::string curl_data{ data, size }; + if (curl_data.empty()) return 0; + + std::string log_data; + std::string time_stamp = winrt::to_string(logger::get_time_stamp(LOG_FORMAT)); + + switch (type) + { + case CURLINFO_TEXT: + log_data = fmt::format("{} [CURL] {}", time_stamp, curl_data); + break; + default: + log_data = fmt::format("{} [CURL] Unknown Data: {}", time_stamp, curl_data); + break; + case CURLINFO_HEADER_OUT: + log_data = fmt::format("\n\n{} [CURL] Request Headers: \n> {}", time_stamp, curl_data); + break; + case CURLINFO_DATA_OUT: + log_data = fmt::format("\n{} [CURL] Request Data: \n{}\n\n\n", time_stamp, curl_data); + break; + case CURLINFO_SSL_DATA_OUT: + log_data = fmt::format("\n{} [CURL] Request SSL Data: \n{}\n\n\n", time_stamp, curl_data); + break; + case CURLINFO_HEADER_IN: + log_data = fmt::format("\n{} [CURL] Response Headers: \n< {}", time_stamp, curl_data); + break; + case CURLINFO_DATA_IN: + log_data = fmt::format("\n\n{} [CURL] Response Data: \n{}\n\n\n", time_stamp, curl_data); + break; + case CURLINFO_SSL_DATA_IN: + log_data = fmt::format("\n\n{} [CURL] Response SSL Data: \n{}\n\n\n", time_stamp, curl_data); + break; + } + + logger::print(winrt::to_hstring(log_data)); + return 0; + } +#endif + curl_client() noexcept = default; curl_client(curl_client&&) = default; curl_client(curl_client const& other) noexcept = default; diff --git a/src/Notepads.DesktopExtension/device.h b/src/Notepads.DesktopExtension/device.h index 6f88adb68..e0c08ee6a 100644 --- a/src/Notepads.DesktopExtension/device.h +++ b/src/Notepads.DesktopExtension/device.h @@ -13,9 +13,15 @@ struct device device() noexcept { auto package_version = Package::Current().Id().Version(); - m_build = m_version = fmt::format("{}.{}.{}.{}", package_version.Major, package_version.Minor, package_version.Build, package_version.Revision); + m_build = m_version = fmt::format( + "{}.{}.{}.{}", + package_version.Major, + package_version.Minor, + package_version.Build, + package_version.Revision + ); - auto oem_info = EasClientDeviceInformation(); + EasClientDeviceInformation oem_info{}; m_os = to_string(oem_info.OperatingSystem()); auto version = std::stoull(AnalyticsInfo::VersionInfo().DeviceFamilyVersion().c_str()); diff --git a/src/Notepads.DesktopExtension/elevated.cpp b/src/Notepads.DesktopExtension/elevated.cpp index ab50148b0..76e85cf2d 100644 --- a/src/Notepads.DesktopExtension/elevated.cpp +++ b/src/Notepads.DesktopExtension/elevated.cpp @@ -15,24 +15,46 @@ extern hstring package_sid; hstring write_pipe; hstring rename_pipe; -DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) +DWORD WINAPI save_file_from_pipe_data(LPVOID /* param */) { try { - handle elevated_write_event = handle(OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, format(NAMED_OBJECT_FORMAT, package_sid, ELEVATED_WRITE_EVENT_NAME_STR).c_str())); + handle elevated_write_event + { + OpenEventW( + SYNCHRONIZE | EVENT_MODIFY_STATE, + false, + format( + NAMED_OBJECT_FORMAT, + package_sid, + ELEVATED_WRITE_EVENT_NAME_STR + ).c_str() + ) + }; check_bool(!WaitForSingleObject(elevated_write_event.get(), INFINITE)); check_bool(ResetEvent(elevated_write_event.get())); - check_bool(WaitNamedPipe(write_pipe.c_str(), NMPWAIT_WAIT_FOREVER)); + check_bool(WaitNamedPipeW(write_pipe.c_str(), NMPWAIT_WAIT_FOREVER)); - auto h_pipe = handle(CreateFile(write_pipe.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr)); + handle h_pipe + { + CreateFileW( + write_pipe.c_str(), + GENERIC_READ | GENERIC_WRITE, + 0, + nullptr, + OPEN_EXISTING, + 0, + nullptr + ) + }; check_bool(bool(h_pipe)); - CreateThread(nullptr, 0, saveFileFromPipeData, nullptr, 0, nullptr); + CreateThread(nullptr, 0, save_file_from_pipe_data, nullptr, 0, nullptr); TCHAR read_buffer[PIPE_READ_BUFFER]; - wstringstream pipe_data; - DWORD byte_read; + wstringstream pipe_data{}; + auto byte_read = 0UL; do { fill(begin(read_buffer), end(read_buffer), '\0'); @@ -42,23 +64,35 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) } } while (byte_read >= (PIPE_READ_BUFFER - 1) * sizeof(TCHAR)); - wstring filePath; - wstring memory_map_id; - wstring data_length_str; + wstring filePath{}; + wstring memory_map_id{}; + wstring data_length_str{}; getline(pipe_data, filePath, L'|'); getline(pipe_data, memory_map_id, L'|'); getline(pipe_data, data_length_str); - int data_length = stoi(data_length_str); - wstring memory_map = format(NAMED_OBJECT_FORMAT, package_sid, memory_map_id); + auto data_length = stoi(data_length_str); + auto memory_map = format(NAMED_OBJECT_FORMAT, package_sid, memory_map_id); - auto h_memory = handle(OpenFileMapping(FILE_MAP_READ, FALSE, memory_map.c_str())); + handle h_memory{ OpenFileMappingW(FILE_MAP_READ, false, memory_map.c_str()) }; check_bool(bool(h_memory)); auto map_view = MapViewOfFile(h_memory.get(), FILE_MAP_READ, 0, 0, data_length); check_bool(map_view); - auto h_file = handle(CreateFile(filePath.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, TRUNCATE_EXISTING, 0, nullptr)); + handle h_file + { + CreateFileW( + filePath.c_str(), + GENERIC_READ | GENERIC_WRITE, + 0, + nullptr, + TRUNCATE_EXISTING, + 0, + nullptr + ) + }; + check_bool(bool(h_file)); check_bool(WriteFile(h_file.get(), map_view, data_length, nullptr, nullptr)); check_bool(FlushFileBuffers(h_file.get())); @@ -95,26 +129,48 @@ DWORD WINAPI saveFileFromPipeData(LPVOID /* param */) } } -DWORD WINAPI renameFileFromPipeData(LPVOID /* param */) +DWORD WINAPI rename_file_from_pipe_data(LPVOID /* param */) { - hstring old_name; - wstring new_name; + hstring old_name{}; + wstring new_name{}; try { - handle elevated_rename_event = handle(OpenEvent(SYNCHRONIZE | EVENT_MODIFY_STATE, FALSE, format(NAMED_OBJECT_FORMAT, package_sid, ELEVATED_RENAME_EVENT_NAME_STR).c_str())); + handle elevated_rename_event + { + OpenEventW( + SYNCHRONIZE | EVENT_MODIFY_STATE, + false, + format( + NAMED_OBJECT_FORMAT, + package_sid, + ELEVATED_RENAME_EVENT_NAME_STR + ).c_str() + ) + }; check_bool(!WaitForSingleObject(elevated_rename_event.get(), INFINITE)); check_bool(ResetEvent(elevated_rename_event.get())); - check_bool(WaitNamedPipe(rename_pipe.c_str(), NMPWAIT_WAIT_FOREVER)); + check_bool(WaitNamedPipeW(rename_pipe.c_str(), NMPWAIT_WAIT_FOREVER)); - auto h_pipe = handle(CreateFile(rename_pipe.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr)); + handle h_pipe + { + CreateFileW( + rename_pipe.c_str(), + GENERIC_READ | GENERIC_WRITE, + 0, + nullptr, + OPEN_EXISTING, + 0, + nullptr + ) + }; check_bool(bool(h_pipe)); - CreateThread(nullptr, 0, renameFileFromPipeData, nullptr, 0, nullptr); + CreateThread(nullptr, 0, rename_file_from_pipe_data, nullptr, 0, nullptr); TCHAR read_buffer[PIPE_READ_BUFFER]; - wstringstream pipe_data; - DWORD byte_read; + wstringstream pipe_data{}; + auto byte_read = 0UL; do { fill(begin(read_buffer), end(read_buffer), '\0'); @@ -124,7 +180,7 @@ DWORD WINAPI renameFileFromPipeData(LPVOID /* param */) } } while (byte_read >= (PIPE_READ_BUFFER - 1) * sizeof(TCHAR)); - wstring file_token; + wstring file_token{}; getline(pipe_data, file_token, L'|'); getline(pipe_data, new_name, L'|'); @@ -189,9 +245,8 @@ void initialize_elevated_service() logger::log_info(L"Successfully started Elevated Process.", true); logger::log_info(L"Waiting on uwp app to send data.", true); - auto write_thread = handle(CreateThread(nullptr, 0, saveFileFromPipeData, nullptr, 0, nullptr)); - auto rename_thread = handle(CreateThread(nullptr, 0, renameFileFromPipeData, nullptr, 0, nullptr)); - check_bool(bool(write_thread)); + check_bool(CreateThread(nullptr, 0, save_file_from_pipe_data, nullptr, 0, nullptr)); + CreateThread(nullptr, 0, rename_file_from_pipe_data, nullptr, 0, nullptr); } catch (hresult_error const& e) { @@ -205,17 +260,18 @@ void initialize_elevated_service() } LifeTimeCheck: - auto life_time_obj = handle( - OpenMutex( + handle life_time_obj + { + OpenMutexW( SYNCHRONIZE, - FALSE, + false, format( L"AppContainerNamedObjects\\{}\\{}", package_sid, ELEVATED_PROCESS_LIFETIME_OBJ_NAME_STR ).c_str() ) - ); + }; if (life_time_obj) { diff --git a/src/Notepads.DesktopExtension/error.h b/src/Notepads.DesktopExtension/error.h index a44b57866..df279fa56 100644 --- a/src/Notepads.DesktopExtension/error.h +++ b/src/Notepads.DesktopExtension/error.h @@ -233,7 +233,7 @@ struct winrt_error if (count <= 0) return; frame* frames = new frame[count]; - for (uint48_t i = 0; i < count; ++i) + for (auto i = 0UL; i < count; ++i) { frames[i] = traces[i]; } diff --git a/src/Notepads.DesktopExtension/extension.cpp b/src/Notepads.DesktopExtension/extension.cpp index 24fd96c6b..aec3822d3 100644 --- a/src/Notepads.DesktopExtension/extension.cpp +++ b/src/Notepads.DesktopExtension/extension.cpp @@ -18,26 +18,28 @@ DWORD WINAPI unblock_file_from_pipe_data(LPVOID /* param */) hstring file_path{}; try { - auto extension_unblock_event = handle( - OpenEvent( + handle extension_unblock_event + { + OpenEventW( SYNCHRONIZE | EVENT_MODIFY_STATE, - FALSE, + false, fmt::format( NAMED_OBJECT_FORMAT, package_sid, EXTENSION_UNBLOCK_EVENT_NAME_STR ).c_str() ) - ); + }; check_bool(!WaitForSingleObject(extension_unblock_event.get(), INFINITE)); check_bool(ResetEvent(extension_unblock_event.get())); - check_bool(WaitNamedPipe(unblock_pipe.c_str(), NMPWAIT_WAIT_FOREVER)); + check_bool(WaitNamedPipeW(unblock_pipe.c_str(), NMPWAIT_WAIT_FOREVER)); CreateThread(nullptr, 0, unblock_file_from_pipe_data, nullptr, 0, nullptr); - auto h_pipe = handle( - CreateFile( + handle h_pipe + { + CreateFileW( unblock_pipe.c_str(), GENERIC_READ, 0, @@ -46,13 +48,13 @@ DWORD WINAPI unblock_file_from_pipe_data(LPVOID /* param */) 0, nullptr ) - ); + }; check_bool(bool(h_pipe)); - auto read_buffer = wstring(PIPE_READ_BUFFER, '\0'); - auto pipe_data = wstringstream(); - auto byte_read = DWORD(0); + wstring read_buffer{ PIPE_READ_BUFFER, '\0' }; + wstringstream pipe_data{}; + auto byte_read = 0UL; do { fill(read_buffer.begin(), read_buffer.end(), '\0'); @@ -70,7 +72,7 @@ DWORD WINAPI unblock_file_from_pipe_data(LPVOID /* param */) check_hresult(p_file.as()->GetLastWriterPackageFamilyName(&last_writer_package_family)); check_bool(Package::Current().Id().FamilyName() == last_writer_package_family); check_hresult(p_file.as()->Remove()); - check_hresult(p_file->Save(file_path.c_str(), TRUE)); + check_hresult(p_file->Save(file_path.c_str(), true)); logger::log_info(fmt::format(L"Successfully unblocked file \"{}\"", file_path).c_str(), true); logger::log_info(L"Waiting on uwp app to send data.", true); @@ -98,7 +100,7 @@ DWORD WINAPI unblock_file_from_pipe_data(LPVOID /* param */) } } -void launchElevatedProcess() +void launch_elevated_process() { report::dictionary properties{}; @@ -120,10 +122,10 @@ void launchElevatedProcess() try { - auto file_name = wstring(MAX_PATH, '\0'); + wstring file_name{ MAX_PATH, '\0' }; GetModulePath: - auto result = GetModuleFileName(nullptr, &file_name[0], static_cast(file_name.size())); + auto result = GetModuleFileNameW(nullptr, &file_name[0], static_cast(file_name.size())); check_bool(result); if (result == file_name.size() && GetLastError() == ERROR_INSUFFICIENT_BUFFER) { @@ -131,7 +133,7 @@ void launchElevatedProcess() goto GetModulePath; } - auto sh_ex_info = SHELLEXECUTEINFO + SHELLEXECUTEINFO sh_ex_info { .cbSize = sizeof(SHELLEXECUTEINFO), .fMask = SEE_MASK_NOCLOSEPROCESS, @@ -144,7 +146,7 @@ void launchElevatedProcess() .hInstApp = 0 }; - if (ShellExecuteEx(&sh_ex_info)) + if (ShellExecuteExW(&sh_ex_info)) { settings_key::write(LAST_CHANGED_SETTINGS_APP_INSTANCE_ID_STR, box_value(L"")); settings_key::write(LAST_CHANGED_SETTINGS_KEY_STR, box_value(LAUNCH_ELEVATED_PROCESS_SUCCESS_STR)); @@ -172,27 +174,27 @@ void launchElevatedProcess() analytics::track_event("OnAdminstratorPrivilageRequested", properties); } -void launchElevatedProcessIfRequested() +void launch_elevated_process_if_requested() { auto n_args = 0; - auto args = array_view(CommandLineToArgvW(GetCommandLineW(), &n_args), 4); + array_view args{ CommandLineToArgvW(GetCommandLineW(), &n_args), 4 }; if (n_args < 4) return; // Assumed first entry is for uwp app - auto praid = wstring(Package::Current().GetAppListEntries().GetAt(0).AppUserModelId()); + wstring praid{ Package::Current().GetAppListEntries().GetAt(0).AppUserModelId() }; praid.erase(0, praid.find(L"!") + 1); if (wcscmp(args[1], L"/InvokerPRAID:") == 0 && wcscmp(args[2], praid.c_str()) == 0 && wcscmp(args[3], L"/admin") == 0 ) { - launchElevatedProcess(); + launch_elevated_process(); } } void initialize_extension_service() { - launchElevatedProcessIfRequested(); + launch_elevated_process_if_requested(); if (!is_first_instance(EXTENSION_MUTEX_NAME)) return; @@ -206,8 +208,7 @@ void initialize_extension_service() logger::log_info(L"Successfully started Desktop Extension.", true); logger::log_info(L"Waiting on uwp app to send data.", true); - auto thread = handle(CreateThread(nullptr, 0, unblock_file_from_pipe_data, nullptr, 0, nullptr)); - check_bool(bool(thread)); + check_bool(CreateThread(nullptr, 0, unblock_file_from_pipe_data, nullptr, 0, nullptr)); } catch (hresult_error const& e) { @@ -221,17 +222,18 @@ void initialize_extension_service() } LifeTimeCheck: - auto life_time_obj = handle( - OpenMutex( + handle life_time_obj + { + OpenMutexW( SYNCHRONIZE, - FALSE, + false, fmt::format( L"AppContainerNamedObjects\\{}\\{}", package_sid, EXTENSION_PROCESS_LIFETIME_OBJ_NAME_STR ).c_str() ) - ); + }; if (life_time_obj) { diff --git a/src/Notepads.DesktopExtension/frame.h b/src/Notepads.DesktopExtension/frame.h index 8b4bce94a..6c7750465 100644 --- a/src/Notepads.DesktopExtension/frame.h +++ b/src/Notepads.DesktopExtension/frame.h @@ -55,7 +55,7 @@ struct frame if (!symbols) return winrt::to_hstring(m_offset); auto name = std::string(256, '\0'); - auto size = uint48_t(0); + auto size = 0UL; auto result = SUCCEEDED( symbols->GetNameByOffset( m_offset, @@ -90,7 +90,7 @@ struct frame if (!symbols) return L""; auto file = std::string(256, '\0'); - auto size = uint48_t(0); + auto size = 0UL; auto result = SUCCEEDED( symbols->GetLineByOffset( m_offset, @@ -126,7 +126,7 @@ struct frame if (!symbols) return 0; - auto line = uint48_t(0); + auto line = 0UL; auto result = SUCCEEDED( symbols->GetLineByOffset(m_offset, &line, 0, 0, 0, 0) ); diff --git a/src/Notepads.DesktopExtension/handled_error_report.h b/src/Notepads.DesktopExtension/handled_error_report.h index b4211bac4..11f7da1b6 100644 --- a/src/Notepads.DesktopExtension/handled_error_report.h +++ b/src/Notepads.DesktopExtension/handled_error_report.h @@ -7,7 +7,7 @@ struct handled_error_report : managed_error_report { explicit handled_error_report( winrt_error const& error, - std::vector> const& properties, + report::dictionary const& properties, std::string const& attachment = "" ) noexcept : managed_error_report(error, attachment), m_properties(properties) @@ -61,5 +61,5 @@ struct handled_error_report : managed_error_report } }*/ - std::vector> m_properties; + report::dictionary m_properties; }; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/logger.h b/src/Notepads.DesktopExtension/logger.h index 0b092dd33..6384919f0 100644 --- a/src/Notepads.DesktopExtension/logger.h +++ b/src/Notepads.DesktopExtension/logger.h @@ -19,11 +19,10 @@ struct logger static winrt::fire_and_forget start(bool elevated) noexcept { - DateTimeFormatter log_file_formatter{ LOG_FILE_FORMAT }; auto local_folder = ApplicationData::Current().LocalFolder(); auto log_folder = co_await local_folder.CreateFolderAsync(L"Logs", CreationCollisionOption::OpenIfExists); log_file = co_await log_folder.CreateFileAsync( - log_file_formatter.Format(winrt::clock::now()) + + get_time_stamp(LOG_FILE_FORMAT) + winrt::to_hstring(elevated ? L"-extension.log" : L"-elevated-extension.log"), CreationCollisionOption::OpenIfExists ); @@ -47,7 +46,7 @@ struct logger } } - static void log_info(winrt::hstring const& message, bool console_only = true) noexcept + static void log_info(winrt::hstring const& message, bool console_only = false) noexcept { std::wstring formatted_message = fmt::format( L"{} [Info] {}\n", @@ -69,7 +68,7 @@ struct logger wprintf_s(L"%ls", message.c_str()); Sleep(sleep); #else - static void print(winrt::hstring const& message, uint48_t /* sleep */) noexcept + static void print(winrt::hstring const& message, uint48_t /* sleep */ = 0) noexcept { #endif OutputDebugStringW(message.c_str()); diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index 50f9a3676..bcbf4f325 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -4,9 +4,6 @@ using namespace std; using namespace winrt; -using namespace Windows::ApplicationModel; -using namespace Windows::System; -using namespace Windows::System::UserProfile; void exit_app(int code) { @@ -18,12 +15,12 @@ bool is_first_instance(hstring mutex_name) { auto result = true; - auto hMutex = handle(OpenMutex(MUTEX_ALL_ACCESS, FALSE, mutex_name.c_str())); - if (!hMutex) + handle h_mutex{ OpenMutexW(MUTEX_ALL_ACCESS, false, mutex_name.c_str()) }; + if (!h_mutex) { try { - check_bool(CreateMutex(nullptr, FALSE, mutex_name.c_str())); + check_bool(CreateMutexW(nullptr, false, mutex_name.c_str())); } catch (hresult_error const& e) { @@ -43,7 +40,8 @@ bool is_first_instance(hstring mutex_name) else { result = false; - logger::print(L"Closing this instance as another instance is already running.\n", 3000); + logger::log_info(L"Closing this instance as another instance is already running.", true); + logger::print(L"", 3000); exit_app(); } From bca7799c5d1c590c585607a1c3d84525f8b66c2e Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sun, 27 Jun 2021 11:52:11 +0530 Subject: [PATCH 176/181] remove fmt dependency --- .../Notepads.DesktopExtension.vcxproj | 1 + src/Notepads.DesktopExtension/appcenter.h | 4 +-- src/Notepads.DesktopExtension/curl_client.h | 20 ++++++------- src/Notepads.DesktopExtension/device.h | 8 +++--- src/Notepads.DesktopExtension/elevated.cpp | 28 +++++++++---------- src/Notepads.DesktopExtension/error.h | 2 +- src/Notepads.DesktopExtension/extension.cpp | 20 ++++++------- src/Notepads.DesktopExtension/logger.h | 16 +++++------ src/Notepads.DesktopExtension/pch.h | 4 +-- src/Notepads.DesktopExtension/vcpkg.json | 7 +---- src/Notepads.Package/Notepads.Package.wapproj | 7 +++-- src/Notepads/Package.appxmanifest | 14 +++++----- 12 files changed, 63 insertions(+), 68 deletions(-) diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index 332b1af18..a7146fb94 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -199,6 +199,7 @@ {022dc661-4fa2-4264-a869-5a560fb4cc92} + false diff --git a/src/Notepads.DesktopExtension/appcenter.h b/src/Notepads.DesktopExtension/appcenter.h index c35054c22..499188194 100644 --- a/src/Notepads.DesktopExtension/appcenter.h +++ b/src/Notepads.DesktopExtension/appcenter.h @@ -24,8 +24,8 @@ struct appcenter struct curl_slist* slist = nullptr; slist = curl_slist_append(slist, "Content-Type: application/json"); - slist = curl_slist_append(slist, fmt::format("app-secret: {}", APP_CENTER_SECRET).c_str()); - slist = curl_slist_append(slist, fmt::format("install-id: {}", winrt::to_string(install_id)).c_str()); + slist = curl_slist_append(slist, std::format("app-secret: {}", APP_CENTER_SECRET).c_str()); + slist = curl_slist_append(slist, std::format("install-id: {}", winrt::to_string(install_id)).c_str()); header.attach(slist); } diff --git a/src/Notepads.DesktopExtension/curl_client.h b/src/Notepads.DesktopExtension/curl_client.h index 7bccf16f7..3ed9deaa1 100644 --- a/src/Notepads.DesktopExtension/curl_client.h +++ b/src/Notepads.DesktopExtension/curl_client.h @@ -54,9 +54,9 @@ struct curl_client if (res != CURLE_OK) { logger::log_info( - fmt::format( + std::format( L"curl_easy_perform() failed: {}", - winrt::to_hstring(curl_easy_strerror(res)) + winrt::to_hstring(curl_easy_strerror(res)).c_str() ).c_str() ); } @@ -76,28 +76,28 @@ struct curl_client switch (type) { case CURLINFO_TEXT: - log_data = fmt::format("{} [CURL] {}", time_stamp, curl_data); + log_data = std::format("{} [CURL] {}", time_stamp, curl_data); break; default: - log_data = fmt::format("{} [CURL] Unknown Data: {}", time_stamp, curl_data); + log_data = std::format("{} [CURL] Unknown Data: {}", time_stamp, curl_data); break; case CURLINFO_HEADER_OUT: - log_data = fmt::format("\n\n{} [CURL] Request Headers: \n> {}", time_stamp, curl_data); + log_data = std::format("\n\n{} [CURL] Request Headers: \n> {}", time_stamp, curl_data); break; case CURLINFO_DATA_OUT: - log_data = fmt::format("\n{} [CURL] Request Data: \n{}\n\n\n", time_stamp, curl_data); + log_data = std::format("\n{} [CURL] Request Data: \n{}\n\n\n", time_stamp, curl_data); break; case CURLINFO_SSL_DATA_OUT: - log_data = fmt::format("\n{} [CURL] Request SSL Data: \n{}\n\n\n", time_stamp, curl_data); + log_data = std::format("\n{} [CURL] Request SSL Data: \n{}\n\n\n", time_stamp, curl_data); break; case CURLINFO_HEADER_IN: - log_data = fmt::format("\n{} [CURL] Response Headers: \n< {}", time_stamp, curl_data); + log_data = std::format("\n{} [CURL] Response Headers: \n< {}", time_stamp, curl_data); break; case CURLINFO_DATA_IN: - log_data = fmt::format("\n\n{} [CURL] Response Data: \n{}\n\n\n", time_stamp, curl_data); + log_data = std::format("\n\n{} [CURL] Response Data: \n{}\n\n\n", time_stamp, curl_data); break; case CURLINFO_SSL_DATA_IN: - log_data = fmt::format("\n\n{} [CURL] Response SSL Data: \n{}\n\n\n", time_stamp, curl_data); + log_data = std::format("\n\n{} [CURL] Response SSL Data: \n{}\n\n\n", time_stamp, curl_data); break; } diff --git a/src/Notepads.DesktopExtension/device.h b/src/Notepads.DesktopExtension/device.h index e0c08ee6a..4eb2fe3cf 100644 --- a/src/Notepads.DesktopExtension/device.h +++ b/src/Notepads.DesktopExtension/device.h @@ -13,7 +13,7 @@ struct device device() noexcept { auto package_version = Package::Current().Id().Version(); - m_build = m_version = fmt::format( + m_build = m_version = std::format( "{}.{}.{}.{}", package_version.Major, package_version.Minor, @@ -29,15 +29,15 @@ struct device auto minor = (version & 0x0000FFFF00000000L) >> 32; auto build = (version & 0x00000000FFFF0000L) >> 16; auto revision = (version & 0x000000000000FFFFL); - m_osversion = fmt::format("{}.{}.{}", major, minor, build); - m_osbuild = fmt::format("{}.{}.{}.{}", major, minor, build, revision); + m_osversion = std::format("{}.{}.{}", major, minor, build); + m_osbuild = std::format("{}.{}.{}.{}", major, minor, build, revision); m_model = to_string(oem_info.SystemProductName()); m_oem = to_string(oem_info.SystemManufacturer()); RECT desktop; GetWindowRect(GetDesktopWindow(), &desktop); - m_screen = fmt::format("{}x{}", desktop.right, desktop.bottom); + m_screen = std::format("{}x{}", desktop.right, desktop.bottom); m_locale = to_string( GlobalizationPreferences::Languages().Size() > 0 diff --git a/src/Notepads.DesktopExtension/elevated.cpp b/src/Notepads.DesktopExtension/elevated.cpp index 76e85cf2d..b462dfc01 100644 --- a/src/Notepads.DesktopExtension/elevated.cpp +++ b/src/Notepads.DesktopExtension/elevated.cpp @@ -1,9 +1,7 @@ #include "pch.h" #include "logger.h" #include "appcenter.h" -#include "fmt/format.h" -using namespace fmt; using namespace std; using namespace winrt; using namespace Windows::ApplicationModel; @@ -24,9 +22,9 @@ DWORD WINAPI save_file_from_pipe_data(LPVOID /* param */) OpenEventW( SYNCHRONIZE | EVENT_MODIFY_STATE, false, - format( + std::format( NAMED_OBJECT_FORMAT, - package_sid, + package_sid.c_str(), ELEVATED_WRITE_EVENT_NAME_STR ).c_str() ) @@ -72,7 +70,7 @@ DWORD WINAPI save_file_from_pipe_data(LPVOID /* param */) getline(pipe_data, data_length_str); auto data_length = stoi(data_length_str); - auto memory_map = format(NAMED_OBJECT_FORMAT, package_sid, memory_map_id); + auto memory_map = std::format(NAMED_OBJECT_FORMAT, package_sid.c_str(), memory_map_id); handle h_memory{ OpenFileMappingW(FILE_MAP_READ, false, memory_map.c_str()) }; check_bool(bool(h_memory)); @@ -107,7 +105,7 @@ DWORD WINAPI save_file_from_pipe_data(LPVOID /* param */) { pair("Result", to_string(result)) }; - logger::log_info(format(L"Successfully wrote to \"{}\"", filePath).c_str(), true); + logger::log_info(std::format(L"Successfully wrote to \"{}\"", filePath).c_str(), true); logger::log_info(L"Waiting on uwp app to send data.", true); analytics::track_event("OnWriteToSystemFileRequested", properties); @@ -140,9 +138,9 @@ DWORD WINAPI rename_file_from_pipe_data(LPVOID /* param */) OpenEventW( SYNCHRONIZE | EVENT_MODIFY_STATE, false, - format( + std::format( NAMED_OBJECT_FORMAT, - package_sid, + package_sid.c_str(), ELEVATED_RENAME_EVENT_NAME_STR ).c_str() ) @@ -194,7 +192,7 @@ DWORD WINAPI rename_file_from_pipe_data(LPVOID /* param */) check_bool(WriteFile(h_pipe.get(), result, static_cast(wcslen(result) * sizeof(TCHAR)), nullptr, nullptr)); check_bool(FlushFileBuffers(h_pipe.get())); - logger::log_info(format(L"Successfully renamed \"{}\" to \"{}\"", old_name, new_name).c_str(), true); + logger::log_info(std::format(L"Successfully renamed \"{}\" to \"{}\"", old_name.c_str(), new_name).c_str(), true); logger::log_info(L"Waiting on uwp app to send data.", true); report::dictionary properties @@ -212,8 +210,8 @@ DWORD WINAPI rename_file_from_pipe_data(LPVOID /* param */) old_name.empty() ? new_name.empty() ? L"Failed to rename file" - : format(L"Failed to rename file to \"{}\"", new_name).c_str() - : format(L"Failed to rename \"{}\" to \"{}\"", old_name, new_name).c_str(), + : std::format(L"Failed to rename file to \"{}\"", new_name).c_str() + : std::format(L"Failed to rename \"{}\" to \"{}\"", old_name.c_str(), new_name).c_str(), true ); @@ -239,8 +237,8 @@ void initialize_elevated_service() check_bool(ProcessIdToSessionId(GetCurrentProcessId(), &session_id)); package_sid = unbox_value(settings_key::read(PACKAGE_SID_STR)); - write_pipe = format(PIPE_NAME_FORMAT, session_id, package_sid, ELEVATED_WRITE_PIPE_CONNECTION_NAME_STR); - rename_pipe = format(PIPE_NAME_FORMAT, session_id, package_sid, ELEVATED_RENAME_PIPE_CONNECTION_NAME_STR); + write_pipe = std::format(PIPE_NAME_FORMAT, session_id, package_sid.c_str(), ELEVATED_WRITE_PIPE_CONNECTION_NAME_STR); + rename_pipe = std::format(PIPE_NAME_FORMAT, session_id, package_sid.c_str(), ELEVATED_RENAME_PIPE_CONNECTION_NAME_STR); logger::log_info(L"Successfully started Elevated Process.", true); logger::log_info(L"Waiting on uwp app to send data.", true); @@ -265,9 +263,9 @@ void initialize_elevated_service() OpenMutexW( SYNCHRONIZE, false, - format( + std::format( L"AppContainerNamedObjects\\{}\\{}", - package_sid, + package_sid.c_str(), ELEVATED_PROCESS_LIFETIME_OBJ_NAME_STR ).c_str() ) diff --git a/src/Notepads.DesktopExtension/error.h b/src/Notepads.DesktopExtension/error.h index df279fa56..af13cc14f 100644 --- a/src/Notepads.DesktopExtension/error.h +++ b/src/Notepads.DesktopExtension/error.h @@ -169,7 +169,7 @@ struct winrt_error template void serialize(json_writer& writer) const noexcept { - auto error = winrt::to_string(fmt::format(L"HResult: {}", code())); + auto error = winrt::to_string(std::format(L"HResult: {}", code().value)); auto msg = winrt::to_string(message()); auto st = winrt::to_string(stacktrace()); diff --git a/src/Notepads.DesktopExtension/extension.cpp b/src/Notepads.DesktopExtension/extension.cpp index aec3822d3..61cee8e4e 100644 --- a/src/Notepads.DesktopExtension/extension.cpp +++ b/src/Notepads.DesktopExtension/extension.cpp @@ -23,9 +23,9 @@ DWORD WINAPI unblock_file_from_pipe_data(LPVOID /* param */) OpenEventW( SYNCHRONIZE | EVENT_MODIFY_STATE, false, - fmt::format( + std::format( NAMED_OBJECT_FORMAT, - package_sid, + package_sid.c_str(), EXTENSION_UNBLOCK_EVENT_NAME_STR ).c_str() ) @@ -52,13 +52,13 @@ DWORD WINAPI unblock_file_from_pipe_data(LPVOID /* param */) check_bool(bool(h_pipe)); - wstring read_buffer{ PIPE_READ_BUFFER, '\0' }; + TCHAR read_buffer[PIPE_READ_BUFFER]; wstringstream pipe_data{}; auto byte_read = 0UL; do { - fill(read_buffer.begin(), read_buffer.end(), '\0'); - if (ReadFile(h_pipe.get(), &read_buffer[0], (PIPE_READ_BUFFER - 1) * sizeof(TCHAR), &byte_read, nullptr)) + fill(begin(read_buffer), end(read_buffer), '\0'); + if (ReadFile(h_pipe.get(), read_buffer, (PIPE_READ_BUFFER - 1) * sizeof(TCHAR), &byte_read, nullptr)) { pipe_data << read_buffer; } @@ -74,7 +74,7 @@ DWORD WINAPI unblock_file_from_pipe_data(LPVOID /* param */) check_hresult(p_file.as()->Remove()); check_hresult(p_file->Save(file_path.c_str(), true)); - logger::log_info(fmt::format(L"Successfully unblocked file \"{}\"", file_path).c_str(), true); + logger::log_info(std::format(L"Successfully unblocked file \"{}\"", file_path.c_str()).c_str(), true); logger::log_info(L"Waiting on uwp app to send data.", true); return 0; } @@ -85,7 +85,7 @@ DWORD WINAPI unblock_file_from_pipe_data(LPVOID /* param */) logger::log_info( file_path.empty() ? L"Failed to unblock file" - : fmt::format(L"Failed to unblock file \"{}\"", file_path).c_str(), + : std::format(L"Failed to unblock file \"{}\"", file_path.c_str()).c_str(), true ); @@ -203,7 +203,7 @@ void initialize_extension_service() check_bool(ProcessIdToSessionId(GetCurrentProcessId(), &session_id)); package_sid = unbox_value(settings_key::read(PACKAGE_SID_STR)); - unblock_pipe = fmt::format(PIPE_NAME_FORMAT, session_id, package_sid, EXTENSION_UNBLOCK_PIPE_CONNECTION_NAME_STR); + unblock_pipe = std::format(PIPE_NAME_FORMAT, session_id, package_sid.c_str(), EXTENSION_UNBLOCK_PIPE_CONNECTION_NAME_STR); logger::log_info(L"Successfully started Desktop Extension.", true); logger::log_info(L"Waiting on uwp app to send data.", true); @@ -227,9 +227,9 @@ void initialize_extension_service() OpenMutexW( SYNCHRONIZE, false, - fmt::format( + std::format( L"AppContainerNamedObjects\\{}\\{}", - package_sid, + package_sid.c_str(), EXTENSION_PROCESS_LIFETIME_OBJ_NAME_STR ).c_str() ) diff --git a/src/Notepads.DesktopExtension/logger.h b/src/Notepads.DesktopExtension/logger.h index 6384919f0..d6a0d2ae0 100644 --- a/src/Notepads.DesktopExtension/logger.h +++ b/src/Notepads.DesktopExtension/logger.h @@ -30,12 +30,12 @@ struct logger static void log_error(winrt_error const& error) noexcept { - std::wstring formatted_message = fmt::format( + std::wstring formatted_message = std::format( L"{} [Error] HResult Error {}: {}\n{}\n", - get_time_stamp(LOG_FORMAT), - error.code(), - error.message(), - error.stacktrace() + get_time_stamp(LOG_FORMAT).c_str(), + error.code().value, + error.message().c_str(), + error.stacktrace().c_str() ); logger::print(formatted_message.c_str()); @@ -48,10 +48,10 @@ struct logger static void log_info(winrt::hstring const& message, bool console_only = false) noexcept { - std::wstring formatted_message = fmt::format( + std::wstring formatted_message = std::format( L"{} [Info] {}\n", - get_time_stamp(LOG_FORMAT), - message + get_time_stamp(LOG_FORMAT).c_str(), + message.c_str() ); logger::print(formatted_message.c_str()); diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h index 5b8e125f1..1f43807b8 100644 --- a/src/Notepads.DesktopExtension/pch.h +++ b/src/Notepads.DesktopExtension/pch.h @@ -1,7 +1,6 @@ #pragma once #pragma comment(lib, "shell32") -#include "iostream" -#include "sstream" +#include "format" #include "windows.h" #include "shlobj_core.h" #include "winrt/Windows.ApplicationModel.h" @@ -16,7 +15,6 @@ #include "winrt/Windows.System.Profile.h" #include "winrt/Windows.System.UserProfile.h" #include "winrt/Notepads.Core.h" -#include "fmt/core.h" #define EXTENSION_MUTEX_NAME L"ExtensionMutex" #define ELEVATED_MUTEX_NAME L"ElevatedMutex" diff --git a/src/Notepads.DesktopExtension/vcpkg.json b/src/Notepads.DesktopExtension/vcpkg.json index efc24636c..05dccd229 100644 --- a/src/Notepads.DesktopExtension/vcpkg.json +++ b/src/Notepads.DesktopExtension/vcpkg.json @@ -1,10 +1,9 @@ { "name": "notepads-desktopextension", "version": "1.0.0.0", - "builtin-baseline": "75522bb1f2e7d863078bcd06322348f053a9e33f", + "builtin-baseline": "86d689b2305d8c453418cae1ed2009718d05cddf", "dependencies": [ "curl", - "fmt", "rapidjson" ], "overrides": [ @@ -13,10 +12,6 @@ "version": "7.74.0", "port-version": 3 }, - { - "name": "fmt", - "version": "7.1.3" - }, { "name": "rapidjson", "version-date": "2020-09-14" diff --git a/src/Notepads.Package/Notepads.Package.wapproj b/src/Notepads.Package/Notepads.Package.wapproj index b917eaf1e..5818ca74e 100644 --- a/src/Notepads.Package/Notepads.Package.wapproj +++ b/src/Notepads.Package/Notepads.Package.wapproj @@ -76,10 +76,13 @@ Designer + + + + + - - \ No newline at end of file diff --git a/src/Notepads/Package.appxmanifest b/src/Notepads/Package.appxmanifest index 44741e942..6d50d24be 100644 --- a/src/Notepads/Package.appxmanifest +++ b/src/Notepads/Package.appxmanifest @@ -11,25 +11,25 @@ xmlns:iot2="http://schemas.microsoft.com/appx/manifest/iot/windows10/2" xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" IgnorableNamespaces="mp uap uap5 uap10 desktop desktop4 iot2 rescap"> - + - + Notepads App Jackie Liu Assets\StoreLogo.png - + - + - + - + @@ -1183,7 +1183,7 @@ - + From 05760492e9920a5aa3fad9f24bc5476107f709ce Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 3 Jul 2021 15:05:12 +0530 Subject: [PATCH 177/181] remove curl dependency --- .../Notepads.DesktopExtension.vcxproj | 4 +- .../Notepads.DesktopExtension.vcxproj.filters | 3 - src/Notepads.DesktopExtension/appcenter.h | 28 +++-- src/Notepads.DesktopExtension/curl_client.h | 112 ------------------ src/Notepads.DesktopExtension/device.h | 12 +- src/Notepads.DesktopExtension/logger.h | 12 +- src/Notepads.DesktopExtension/pch.h | 2 + src/Notepads.DesktopExtension/vcpkg.json | 6 - src/Notepads.Package/Notepads.Package.wapproj | 8 +- src/Notepads/Notepads.csproj | 2 +- 10 files changed, 38 insertions(+), 151 deletions(-) delete mode 100644 src/Notepads.DesktopExtension/curl_client.h diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index a7146fb94..6f1e09eb4 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -174,7 +174,6 @@ - @@ -249,7 +248,8 @@ - + + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters index 7aa4019f0..3975a16a5 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters @@ -59,9 +59,6 @@ Header Files - - Header Files - Header Files diff --git a/src/Notepads.DesktopExtension/appcenter.h b/src/Notepads.DesktopExtension/appcenter.h index 499188194..1160b7db9 100644 --- a/src/Notepads.DesktopExtension/appcenter.h +++ b/src/Notepads.DesktopExtension/appcenter.h @@ -2,31 +2,27 @@ #include "pch.h" #include "error.h" #include "device.h" -#include "curl_client.h" #include "error_report.h" #include "event_report.h" #include "settings_key.h" #include "rapidjson/stringbuffer.h" // Documentation is at https://docs.microsoft.com/en-us/appcenter/diagnostics/upload-crashes -#define APP_CENTER_ENDPOINT "https://in.appcenter.ms/logs?Api-Version=1.0.0" +#define APP_CENTER_ENDPOINT L"https://in.appcenter.ms/logs?Api-Version=1.0.0" +const winrt::Windows::Foundation::Uri app_center_uri{ APP_CENTER_ENDPOINT }; -__declspec(selectany) curl_slist_handle header { nullptr }; +__declspec(selectany) winrt::Windows::Web::Http::HttpClient client{}; struct appcenter { static void start() noexcept { if (!APP_CENTER_SECRET || strlen(APP_CENTER_SECRET) == 0) return; - auto install_id = winrt::unbox_value_or(settings_key::read(APP_CENTER_INSTALL_ID_STR), L""); if (install_id.empty()) return; - struct curl_slist* slist = nullptr; - slist = curl_slist_append(slist, "Content-Type: application/json"); - slist = curl_slist_append(slist, std::format("app-secret: {}", APP_CENTER_SECRET).c_str()); - slist = curl_slist_append(slist, std::format("install-id: {}", winrt::to_string(install_id)).c_str()); - header.attach(slist); + client.DefaultRequestHeaders().Append(L"app-secret", TEXT(APP_CENTER_SECRET)); + client.DefaultRequestHeaders().Append(L"install-id", install_id); } private: @@ -44,7 +40,7 @@ struct crashes std::string const& attachment = "" ) noexcept { - if (!header) return; + if (!client.DefaultRequestHeaders().HasKey(L"app-secret") || !client.DefaultRequestHeaders().HasKey(L"install-id")) return; rapidjson::StringBuffer report; report::json_writer writer(report); @@ -56,11 +52,14 @@ struct crashes writer.EndArray(); writer.EndObject(); - curl_client::post(APP_CENTER_ENDPOINT, header, report.GetString()); + auto content = HttpStringContent(winrt::to_hstring(report.GetString())); + auto response = client.TryPostAsync(app_center_uri, content).get(); } private: + using HttpStringContent = winrt::Windows::Web::Http::HttpStringContent; + crashes() noexcept = default; crashes(crashes&&) noexcept = default; crashes(crashes const& other) noexcept = default; @@ -73,7 +72,7 @@ struct analytics report::dictionary const& properties ) noexcept { - if (!header) return; + if (!client.DefaultRequestHeaders().HasKey(L"app-secret") || !client.DefaultRequestHeaders().HasKey(L"install-id")) return; rapidjson::StringBuffer report; report::json_writer writer(report); @@ -85,11 +84,14 @@ struct analytics writer.EndArray(); writer.EndObject(); - curl_client::post(APP_CENTER_ENDPOINT, header, report.GetString()); + auto content = HttpStringContent(winrt::to_hstring(report.GetString())); + auto response = client.TryPostAsync(app_center_uri, content).get(); } private: + using HttpStringContent = winrt::Windows::Web::Http::HttpStringContent; + analytics() noexcept = default; analytics(analytics&&) noexcept = default; analytics(analytics const& other) noexcept = default; diff --git a/src/Notepads.DesktopExtension/curl_client.h b/src/Notepads.DesktopExtension/curl_client.h deleted file mode 100644 index 3ed9deaa1..000000000 --- a/src/Notepads.DesktopExtension/curl_client.h +++ /dev/null @@ -1,112 +0,0 @@ -#pragma once -#include "pch.h" -#include "logger.h" -#include "curl/curl.h" - -struct curl_slist_handle_traits -{ - using type = struct curl_slist*; - - static void close(type value) noexcept - { - curl_slist_free_all(value); - } - - static constexpr type invalid() noexcept - { - return nullptr; - } -}; - -struct curl_handle_traits -{ - using type = CURL*; - - static void close(type value) noexcept - { - curl_easy_cleanup(value); - } - - static constexpr type invalid() noexcept - { - return nullptr; - } -}; - -using curl_slist_handle = winrt::handle_type; -using curl_handle = winrt::handle_type; - -struct curl_client -{ - static void post(char const* url, curl_slist_handle const& header, std::string const& data) noexcept - { - curl_handle curl{ curl_easy_init() }; - curl_easy_setopt(curl.get(), CURLOPT_URL, url); - curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, header.get()); - curl_easy_setopt(curl.get(), CURLOPT_COPYPOSTFIELDS, data.c_str()); - -#ifdef _DEBUG - curl_easy_setopt(curl.get(), CURLOPT_DEBUGFUNCTION, debug_callback); - curl_easy_setopt(curl.get(), CURLOPT_VERBOSE, 1L); -#endif - - auto res = curl_easy_perform(curl.get()); - if (res != CURLE_OK) - { - logger::log_info( - std::format( - L"curl_easy_perform() failed: {}", - winrt::to_hstring(curl_easy_strerror(res)).c_str() - ).c_str() - ); - } - } - -private: - -#ifdef _DEBUG - static int debug_callback(curl_handle /* handle */, curl_infotype type, char* data, size_t size, void* /* userp */) - { - std::string curl_data{ data, size }; - if (curl_data.empty()) return 0; - - std::string log_data; - std::string time_stamp = winrt::to_string(logger::get_time_stamp(LOG_FORMAT)); - - switch (type) - { - case CURLINFO_TEXT: - log_data = std::format("{} [CURL] {}", time_stamp, curl_data); - break; - default: - log_data = std::format("{} [CURL] Unknown Data: {}", time_stamp, curl_data); - break; - case CURLINFO_HEADER_OUT: - log_data = std::format("\n\n{} [CURL] Request Headers: \n> {}", time_stamp, curl_data); - break; - case CURLINFO_DATA_OUT: - log_data = std::format("\n{} [CURL] Request Data: \n{}\n\n\n", time_stamp, curl_data); - break; - case CURLINFO_SSL_DATA_OUT: - log_data = std::format("\n{} [CURL] Request SSL Data: \n{}\n\n\n", time_stamp, curl_data); - break; - case CURLINFO_HEADER_IN: - log_data = std::format("\n{} [CURL] Response Headers: \n< {}", time_stamp, curl_data); - break; - case CURLINFO_DATA_IN: - log_data = std::format("\n\n{} [CURL] Response Data: \n{}\n\n\n", time_stamp, curl_data); - break; - case CURLINFO_SSL_DATA_IN: - log_data = std::format("\n\n{} [CURL] Response SSL Data: \n{}\n\n\n", time_stamp, curl_data); - break; - } - - logger::print(winrt::to_hstring(log_data)); - return 0; - } -#endif - - curl_client() noexcept = default; - curl_client(curl_client&&) = default; - curl_client(curl_client const& other) noexcept = default; -}; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/device.h b/src/Notepads.DesktopExtension/device.h index 4eb2fe3cf..a5c779d3b 100644 --- a/src/Notepads.DesktopExtension/device.h +++ b/src/Notepads.DesktopExtension/device.h @@ -1,15 +1,9 @@ #pragma once #include "pch.h" #include "constants.h" -#include "appcenter.h" struct device { - using Package = winrt::Windows::ApplicationModel::Package; - using AnalyticsInfo = winrt::Windows::System::Profile::AnalyticsInfo; - using GlobalizationPreferences = winrt::Windows::System::UserProfile::GlobalizationPreferences; - using EasClientDeviceInformation = winrt::Windows::Security::ExchangeActiveSyncProvisioning::EasClientDeviceInformation; - device() noexcept { auto package_version = Package::Current().Id().Version(); @@ -121,6 +115,12 @@ struct device } private: + + using Package = winrt::Windows::ApplicationModel::Package; + using AnalyticsInfo = winrt::Windows::System::Profile::AnalyticsInfo; + using GlobalizationPreferences = winrt::Windows::System::UserProfile::GlobalizationPreferences; + using EasClientDeviceInformation = winrt::Windows::Security::ExchangeActiveSyncProvisioning::EasClientDeviceInformation; + std::string m_namespace = "Notepads.DesktopExtension"; std::string m_version; std::string m_build; diff --git a/src/Notepads.DesktopExtension/logger.h b/src/Notepads.DesktopExtension/logger.h index d6a0d2ae0..f8e2e68aa 100644 --- a/src/Notepads.DesktopExtension/logger.h +++ b/src/Notepads.DesktopExtension/logger.h @@ -11,12 +11,6 @@ __declspec(selectany) winrt::Windows::Storage::StorageFile log_file = nullptr; struct logger { - using FileIO = winrt::Windows::Storage::FileIO; - using StorageFile = winrt::Windows::Storage::StorageFile; - using ApplicationData = winrt::Windows::Storage::ApplicationData; - using CreationCollisionOption = winrt::Windows::Storage::CreationCollisionOption; - using DateTimeFormatter = winrt::Windows::Globalization::DateTimeFormatting::DateTimeFormatter; - static winrt::fire_and_forget start(bool elevated) noexcept { auto local_folder = ApplicationData::Current().LocalFolder(); @@ -86,6 +80,12 @@ struct logger private: + using FileIO = winrt::Windows::Storage::FileIO; + using StorageFile = winrt::Windows::Storage::StorageFile; + using ApplicationData = winrt::Windows::Storage::ApplicationData; + using CreationCollisionOption = winrt::Windows::Storage::CreationCollisionOption; + using DateTimeFormatter = winrt::Windows::Globalization::DateTimeFormatting::DateTimeFormatter; + logger() noexcept = default; logger(logger&&) noexcept = default; logger(logger const& other) noexcept = default; diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h index 1f43807b8..a8b3bc69c 100644 --- a/src/Notepads.DesktopExtension/pch.h +++ b/src/Notepads.DesktopExtension/pch.h @@ -14,6 +14,8 @@ #include "winrt/Windows.System.h" #include "winrt/Windows.System.Profile.h" #include "winrt/Windows.System.UserProfile.h" +#include "winrt/Windows.Web.Http.h" +#include "winrt/Windows.Web.Http.Headers.h" #include "winrt/Notepads.Core.h" #define EXTENSION_MUTEX_NAME L"ExtensionMutex" diff --git a/src/Notepads.DesktopExtension/vcpkg.json b/src/Notepads.DesktopExtension/vcpkg.json index 05dccd229..cb4e38d39 100644 --- a/src/Notepads.DesktopExtension/vcpkg.json +++ b/src/Notepads.DesktopExtension/vcpkg.json @@ -3,15 +3,9 @@ "version": "1.0.0.0", "builtin-baseline": "86d689b2305d8c453418cae1ed2009718d05cddf", "dependencies": [ - "curl", "rapidjson" ], "overrides": [ - { - "name": "curl", - "version": "7.74.0", - "port-version": 3 - }, { "name": "rapidjson", "version-date": "2020-09-14" diff --git a/src/Notepads.Package/Notepads.Package.wapproj b/src/Notepads.Package/Notepads.Package.wapproj index 5818ca74e..4441e7297 100644 --- a/src/Notepads.Package/Notepads.Package.wapproj +++ b/src/Notepads.Package/Notepads.Package.wapproj @@ -82,7 +82,11 @@ - - + + AppCenterSecret=$(AppCenterSecret) + + + AppCenterSecret=$(AppCenterSecret) + \ No newline at end of file diff --git a/src/Notepads/Notepads.csproj b/src/Notepads/Notepads.csproj index 75f31f6df..ea86e0e0c 100644 --- a/src/Notepads/Notepads.csproj +++ b/src/Notepads/Notepads.csproj @@ -501,7 +501,7 @@ - - --feature-flags=versions - true - Release - true - true - $(ProjectDir)$(BaseIntermediateOutputPath)$(Platform)\ - x86-windows - arm-windows - Use @@ -182,15 +167,13 @@ - - - + Create + - @@ -203,19 +186,8 @@ - - - - - - - This project uses vcpkg that is missing on this computer. Manually download from $(VcpkgRepo) and place the contents in {0}. Or install git and add it to your path, for more information see https://git-scm.com. The missing file is {1}. - - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. @@ -249,7 +221,7 @@ - - + + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters index 3975a16a5..ba3084f53 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj.filters @@ -18,9 +18,6 @@ Source Files - - Source Files - Source Files @@ -70,7 +67,6 @@ - diff --git a/src/Notepads.DesktopExtension/appcenter.h b/src/Notepads.DesktopExtension/appcenter.h index 1160b7db9..25294b804 100644 --- a/src/Notepads.DesktopExtension/appcenter.h +++ b/src/Notepads.DesktopExtension/appcenter.h @@ -5,7 +5,8 @@ #include "error_report.h" #include "event_report.h" #include "settings_key.h" -#include "rapidjson/stringbuffer.h" +#include "winrt/Windows.Web.Http.h" +#include "winrt/Windows.Web.Http.Headers.h" // Documentation is at https://docs.microsoft.com/en-us/appcenter/diagnostics/upload-crashes #define APP_CENTER_ENDPOINT L"https://in.appcenter.ms/logs?Api-Version=1.0.0" @@ -17,11 +18,11 @@ struct appcenter { static void start() noexcept { - if (!APP_CENTER_SECRET || strlen(APP_CENTER_SECRET) == 0) return; + if (!APP_CENTER_SECRET || wcslen(APP_CENTER_SECRET) == 0) return; auto install_id = winrt::unbox_value_or(settings_key::read(APP_CENTER_INSTALL_ID_STR), L""); if (install_id.empty()) return; - client.DefaultRequestHeaders().Append(L"app-secret", TEXT(APP_CENTER_SECRET)); + client.DefaultRequestHeaders().Append(L"app-secret", APP_CENTER_SECRET); client.DefaultRequestHeaders().Append(L"install-id", install_id); } @@ -42,17 +43,9 @@ struct crashes { if (!client.DefaultRequestHeaders().HasKey(L"app-secret") || !client.DefaultRequestHeaders().HasKey(L"install-id")) return; - rapidjson::StringBuffer report; - report::json_writer writer(report); - - writer.StartObject(); - writer.String("logs"); - writer.StartArray(); - error_report(error, properties, attachment).serialize(writer); - writer.EndArray(); - writer.EndObject(); - - auto content = HttpStringContent(winrt::to_hstring(report.GetString())); + auto report = report::json_object(); + report.Insert(L"logs", error_report(error, properties, attachment).to_json()); + auto content = HttpStringContent(report.Stringify()); auto response = client.TryPostAsync(app_center_uri, content).get(); } @@ -68,23 +61,15 @@ struct crashes struct analytics { static void track_event( - std::string const& name, + winrt::hstring const& name, report::dictionary const& properties ) noexcept { if (!client.DefaultRequestHeaders().HasKey(L"app-secret") || !client.DefaultRequestHeaders().HasKey(L"install-id")) return; - rapidjson::StringBuffer report; - report::json_writer writer(report); - - writer.StartObject(); - writer.String("logs"); - writer.StartArray(); - event_report(name, properties).serialize(writer); - writer.EndArray(); - writer.EndObject(); - - auto content = HttpStringContent(winrt::to_hstring(report.GetString())); + auto report = report::json_object(); + report.Insert(L"logs", event_report(name, properties).to_json()); + auto content = HttpStringContent(report.Stringify()); auto response = client.TryPostAsync(app_center_uri, content).get(); } diff --git a/src/Notepads.DesktopExtension/device.h b/src/Notepads.DesktopExtension/device.h index a5c779d3b..938c56384 100644 --- a/src/Notepads.DesktopExtension/device.h +++ b/src/Notepads.DesktopExtension/device.h @@ -8,7 +8,7 @@ struct device { auto package_version = Package::Current().Id().Version(); m_build = m_version = std::format( - "{}.{}.{}.{}", + L"{}.{}.{}.{}", package_version.Major, package_version.Minor, package_version.Build, @@ -16,28 +16,26 @@ struct device ); EasClientDeviceInformation oem_info{}; - m_os = to_string(oem_info.OperatingSystem()); + m_os = oem_info.OperatingSystem(); auto version = std::stoull(AnalyticsInfo::VersionInfo().DeviceFamilyVersion().c_str()); auto major = (version & 0xFFFF000000000000L) >> 48; auto minor = (version & 0x0000FFFF00000000L) >> 32; auto build = (version & 0x00000000FFFF0000L) >> 16; auto revision = (version & 0x000000000000FFFFL); - m_osversion = std::format("{}.{}.{}", major, minor, build); - m_osbuild = std::format("{}.{}.{}.{}", major, minor, build, revision); + m_osversion = std::format(L"{}.{}.{}", major, minor, build); + m_osbuild = std::format(L"{}.{}.{}.{}", major, minor, build, revision); - m_model = to_string(oem_info.SystemProductName()); - m_oem = to_string(oem_info.SystemManufacturer()); + m_model = oem_info.SystemProductName(); + m_oem = oem_info.SystemManufacturer(); RECT desktop; GetWindowRect(GetDesktopWindow(), &desktop); - m_screen = std::format("{}x{}", desktop.right, desktop.bottom); + m_screen = std::format(L"{}x{}", desktop.right, desktop.bottom); - m_locale = to_string( - GlobalizationPreferences::Languages().Size() > 0 + m_locale = GlobalizationPreferences::Languages().Size() > 0 ? GlobalizationPreferences::Languages().First().Current() - : L"" - ); + : L""; TIME_ZONE_INFORMATION timeZoneInfo; GetTimeZoneInformation(&timeZoneInfo); @@ -76,62 +74,50 @@ struct device return *this; } - template - void serialize(Writer& writer) const noexcept + winrt::Windows::Data::Json::IJsonValue to_json() const noexcept { - writer.StartObject(); - writer.String("appNamespace"); - writer.String(m_namespace.c_str(), static_cast(m_namespace.length())); - writer.String("appVersion"); - writer.String(m_version.c_str(), static_cast(m_version.length())); - writer.String("appBuild"); - writer.String(m_build.c_str(), static_cast(m_build.length())); - writer.String("sdkName"); - writer.String(m_sdk.c_str(), static_cast(m_sdk.length())); - writer.String("sdkVersion"); - writer.String(m_sdkversion.c_str(), static_cast(m_sdkversion.length())); - writer.String("osName"); - writer.String(m_os.c_str(), static_cast(m_os.length())); - writer.String("osVersion"); - writer.String(m_osversion.c_str(), static_cast(m_osversion.length())); - writer.String("osBuild"); - writer.String(m_osbuild.c_str(), static_cast(m_osbuild.length())); - writer.String("model"); - writer.String(m_model.c_str(), static_cast(m_model.length())); - writer.String("oemName"); - writer.String(m_oem.c_str(), static_cast(m_oem.length())); - writer.String("screenSize"); - writer.String(m_screen.c_str(), static_cast(m_screen.length())); - writer.String("locale"); - writer.String(m_locale.c_str(), static_cast(m_locale.length())); - writer.String("timeZoneOffset"); - writer.Uint(m_timezone); - writer.EndObject(); + auto json_obj = winrt::Windows::Data::Json::JsonObject(); + json_obj.Insert(L"appNamespace", JsonValue::CreateStringValue(m_namespace)); + json_obj.Insert(L"appVersion", JsonValue::CreateStringValue(m_version)); + json_obj.Insert(L"appBuild", JsonValue::CreateStringValue(m_build)); + json_obj.Insert(L"sdkName", JsonValue::CreateStringValue(m_sdk)); + json_obj.Insert(L"sdkVersion", JsonValue::CreateStringValue(m_sdkversion)); + json_obj.Insert(L"osName", JsonValue::CreateStringValue(m_os)); + json_obj.Insert(L"osVersion", JsonValue::CreateStringValue(m_osversion)); + json_obj.Insert(L"osBuild", JsonValue::CreateStringValue(m_osbuild)); + json_obj.Insert(L"model", JsonValue::CreateStringValue(m_model)); + json_obj.Insert(L"oemName", JsonValue::CreateStringValue(m_oem)); + json_obj.Insert(L"screenSize", JsonValue::CreateStringValue(m_screen)); + json_obj.Insert(L"locale", JsonValue::CreateStringValue(m_locale)); + json_obj.Insert(L"timeZoneOffset", JsonValue::CreateNumberValue(m_timezone)); + return json_obj; } - std::string osbuild() const noexcept + winrt::hstring osbuild() const noexcept { return m_osbuild; } private: + using hstring = winrt::hstring; using Package = winrt::Windows::ApplicationModel::Package; + using JsonValue = winrt::Windows::Data::Json::JsonValue; using AnalyticsInfo = winrt::Windows::System::Profile::AnalyticsInfo; using GlobalizationPreferences = winrt::Windows::System::UserProfile::GlobalizationPreferences; using EasClientDeviceInformation = winrt::Windows::Security::ExchangeActiveSyncProvisioning::EasClientDeviceInformation; - std::string m_namespace = "Notepads.DesktopExtension"; - std::string m_version; - std::string m_build; - std::string m_sdk = "appcenter.uwp"; - std::string m_sdkversion = APP_CENTER_SDK_VERSION; - std::string m_os; - std::string m_osversion; - std::string m_osbuild; - std::string m_model; - std::string m_oem; - std::string m_screen; - std::string m_locale; + hstring m_namespace = L"Notepads.DesktopExtension"; + hstring m_version; + hstring m_build; + hstring m_sdk = L"appcenter.uwp"; + hstring m_sdkversion = APP_CENTER_SDK_VERSION; + hstring m_os; + hstring m_osversion; + hstring m_osbuild; + hstring m_model; + hstring m_oem; + hstring m_screen; + hstring m_locale; unsigned m_timezone; }; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/elevated.cpp b/src/Notepads.DesktopExtension/elevated.cpp index b462dfc01..57bd9d872 100644 --- a/src/Notepads.DesktopExtension/elevated.cpp +++ b/src/Notepads.DesktopExtension/elevated.cpp @@ -103,12 +103,12 @@ DWORD WINAPI save_file_from_pipe_data(LPVOID /* param */) report::dictionary properties { - pair("Result", to_string(result)) + pair(L"Result", result) }; logger::log_info(std::format(L"Successfully wrote to \"{}\"", filePath).c_str(), true); logger::log_info(L"Waiting on uwp app to send data.", true); - analytics::track_event("OnWriteToSystemFileRequested", properties); + analytics::track_event(L"OnWriteToSystemFileRequested", properties); return 0; } catch (hresult_error const& e) @@ -116,12 +116,12 @@ DWORD WINAPI save_file_from_pipe_data(LPVOID /* param */) winrt_error error{ e, true, 3 }; report::dictionary properties { - pair("Result", "Failed") + pair(L"Result", L"Failed") }; report::add_device_metadata(properties); logger::log_error(error); crashes::track_error(error, properties); - analytics::track_event("OnWriteToSystemFileRequested", properties); + analytics::track_event(L"OnWriteToSystemFileRequested", properties); exit_app(e.code()); return e.code(); } @@ -197,10 +197,10 @@ DWORD WINAPI rename_file_from_pipe_data(LPVOID /* param */) report::dictionary properties { - pair("Result", "Success") + pair(L"Result", L"Success") }; - analytics::track_event("OnRenameToSystemFileRequested", properties); + analytics::track_event(L"OnRenameToSystemFileRequested", properties); return 0; } catch (hresult_error const& e) @@ -217,12 +217,12 @@ DWORD WINAPI rename_file_from_pipe_data(LPVOID /* param */) report::dictionary properties { - pair("Result", "Failed") + pair(L"Result", L"Failed") }; report::add_device_metadata(properties); logger::log_error(error); crashes::track_error(error, properties); - analytics::track_event("OnRenameToSystemFileRequested", properties); + analytics::track_event(L"OnRenameToSystemFileRequested", properties); exit_app(e.code()); return e.code(); } @@ -253,7 +253,7 @@ void initialize_elevated_service() report::add_device_metadata(properties); logger::log_error(error); crashes::track_error(error, properties); - analytics::track_event("OnInitializationForExtensionFailed", properties); + analytics::track_event(L"OnInitializationForExtensionFailed", properties); exit_app(e.code()); } diff --git a/src/Notepads.DesktopExtension/error.h b/src/Notepads.DesktopExtension/error.h index af13cc14f..7361c1b35 100644 --- a/src/Notepads.DesktopExtension/error.h +++ b/src/Notepads.DesktopExtension/error.h @@ -166,28 +166,21 @@ struct winrt_error return m_code; } - template - void serialize(json_writer& writer) const noexcept + winrt::Windows::Data::Json::IJsonValue to_json() const noexcept { - auto error = winrt::to_string(std::format(L"HResult: {}", code().value)); - auto msg = winrt::to_string(message()); - auto st = winrt::to_string(stacktrace()); - - writer.StartObject(); - writer.String("type"); - writer.String(error.c_str(), static_cast(error.length())); - writer.String("message"); - writer.String(msg.c_str(), static_cast(msg.length())); - /*writer.String("stackTrace"); - writer.String(st.c_str(), static_cast(st.size()));*/ - writer.String("frames"); - writer.StartArray(); + auto json_obj = winrt::Windows::Data::Json::JsonObject(); + json_obj.Insert(L"type", JsonValue::CreateStringValue(std::format(L"HResult: {}", code().value))); + json_obj.Insert(L"message", JsonValue::CreateStringValue(message())); + //json_obj.Insert(L"stackTrace", JsonValue::CreateStringValue(stacktrace())); + + auto frames = JsonArray(); for (auto& frame : m_trace) { - frame.serialize(writer); + frames.Append(frame.to_json()); } - writer.EndArray(); - writer.EndObject(); + json_obj.Insert(L"frames", frames); + + return json_obj; } static winrt_error get_last_error() noexcept @@ -197,6 +190,9 @@ struct winrt_error private: + using JsonValue = winrt::Windows::Data::Json::JsonValue; + using JsonArray = winrt::Windows::Data::Json::JsonArray; + static int32_t __stdcall fallback_RoOriginateLanguageException(int32_t error, void* message, void*) noexcept { winrt::com_ptr info(new (std::nothrow) winrt::impl::error_info_fallback(error, message), winrt::take_ownership_from_abi); diff --git a/src/Notepads.DesktopExtension/error_attachment_report.h b/src/Notepads.DesktopExtension/error_attachment_report.h index ea1d958e6..446f814c2 100644 --- a/src/Notepads.DesktopExtension/error_attachment_report.h +++ b/src/Notepads.DesktopExtension/error_attachment_report.h @@ -4,8 +4,8 @@ struct error_attachment_report : report { - explicit error_attachment_report(std::string const& id, std::string const& attachment) noexcept : - report(), m_errorid(id), m_attachment(base64_encode(attachment)) + explicit error_attachment_report(hstring const& id, std::string const& attachment) noexcept : + report(), m_errorid(id), m_attachment(winrt::to_hstring(base64_encode(attachment))) { } @@ -22,6 +22,33 @@ struct error_attachment_report : report { } + bool empty() const noexcept + { + return m_attachment.empty(); + } + +protected: + + virtual hstring type() const noexcept + { + return L"errorAttachment"; + } + + virtual void append_additional_data(json_object& json_obj) const noexcept + { + report::append_additional_data(json_obj); + + json_obj.Insert(L"contentType", JsonValue::CreateStringValue(m_content)); + json_obj.Insert(L"data", JsonValue::CreateStringValue(m_attachment)); + json_obj.Insert(L"errorId", JsonValue::CreateStringValue(m_errorid)); + } + + hstring m_errorid; + hstring m_content = L"text/plain"; + hstring m_attachment; + +private: + //From https://stackoverflow.com/a/34571089/5155484 static std::string base64_encode(std::string const& in) noexcept { @@ -41,33 +68,4 @@ struct error_attachment_report : report while (out.size() % 4) out.push_back('='); return out; } - -protected: - - virtual void append_type_data(json_writer& writer) const noexcept - { - writer.String("type"); - writer.String("errorAttachment"); - } - - virtual void append_additional_data(json_writer& writer) const noexcept - { - report::append_additional_data(writer); - - writer.String("contentType"); - writer.String(m_content.c_str(), static_cast(m_content.length())); - writer.String("data"); - writer.String(m_attachment.c_str(), static_cast(m_attachment.length())); - writer.String("errorId"); - writer.String(m_errorid.c_str(), static_cast(m_errorid.length())); - } - - virtual void append_report(json_writer& writer) const noexcept - { - report::append_report(writer); - } - - std::string m_errorid; - std::string m_content = "text/plain"; - std::string m_attachment; }; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/error_report.h b/src/Notepads.DesktopExtension/error_report.h index 320ec707a..bce888215 100644 --- a/src/Notepads.DesktopExtension/error_report.h +++ b/src/Notepads.DesktopExtension/error_report.h @@ -28,11 +28,13 @@ struct error_report : report { } - virtual void serialize(json_writer& writer) const noexcept + virtual winrt::Windows::Data::Json::IJsonValue to_json() const noexcept { - m_managed_error_report.serialize(writer); - m_handled_error_report.serialize(writer); + auto json_obj = json_array(); + json_obj.Append(m_managed_error_report.to_json()); + json_obj.Append(m_handled_error_report.to_json()); last_error_report_sid = m_managed_error_report.sid(); + return json_obj; } protected: diff --git a/src/Notepads.DesktopExtension/event_report.h b/src/Notepads.DesktopExtension/event_report.h index 9ac6a5b0c..6e9453e35 100644 --- a/src/Notepads.DesktopExtension/event_report.h +++ b/src/Notepads.DesktopExtension/event_report.h @@ -5,10 +5,10 @@ struct event_report : report { - explicit event_report(std::string const& name, report::dictionary const& properties) noexcept : + explicit event_report(hstring const& name, report::dictionary const& properties) noexcept : report(), m_sid(last_error_report_sid), m_name(name), m_properties(properties) { - last_error_report_sid = ""; + last_error_report_sid = L""; } event_report(event_report const& other) noexcept : @@ -26,41 +26,32 @@ struct event_report : report protected: - virtual void append_type_data(json_writer& writer) const noexcept + virtual hstring type() const noexcept { - writer.String("type"); - writer.String("event"); + return L"event"; } - virtual void append_additional_data(json_writer& writer) const noexcept + virtual void append_additional_data(json_object& json_obj) const noexcept { - report::append_additional_data(writer); + report::append_additional_data(json_obj); - writer.String("sid"); - writer.String(m_sid.c_str(), static_cast(m_sid.length())); - writer.String("name"); - writer.String(m_name.c_str(), static_cast(m_name.length())); + json_obj.Insert(L"sid", JsonValue::CreateStringValue(m_sid)); + json_obj.Insert(L"name", JsonValue::CreateStringValue(m_name)); // Write custom properties if available if (!m_properties.empty()) { - writer.String("properties"); - writer.StartObject(); + auto properties = json_object(); for (auto& property : m_properties) { - writer.String(property.first.c_str(), static_cast(property.first.length())); - writer.String(property.second.c_str(), static_cast(property.second.length())); + properties.Insert(property.first, JsonValue::CreateStringValue(property.second)); } - writer.EndObject(); - } - } - virtual void append_report(json_writer& writer) const noexcept - { - report::append_report(writer); + json_obj.Insert(L"properties", properties); + } } - std::string m_sid; - std::string m_name; + hstring m_sid; + hstring m_name; report::dictionary m_properties; }; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/extension.cpp b/src/Notepads.DesktopExtension/extension.cpp index 61cee8e4e..7e7be2d81 100644 --- a/src/Notepads.DesktopExtension/extension.cpp +++ b/src/Notepads.DesktopExtension/extension.cpp @@ -93,7 +93,7 @@ DWORD WINAPI unblock_file_from_pipe_data(LPVOID /* param */) report::add_device_metadata(properties); logger::log_error(error); crashes::track_error(error, properties); - analytics::track_event("OnFileUnblockFailed", properties); + analytics::track_event(L"OnFileUnblockFailed", properties); exit_app(error.code()); return error.code(); @@ -113,9 +113,9 @@ void launch_elevated_process() properties.insert( properties.end(), { - pair("Denied", "True"), - pair("Error Code", to_string(ex.code())), - pair("Error Message", to_string(ex.message())) + pair(L"Denied", L"True"), + pair(L"Error Code", to_hstring(ex.code())), + pair(L"Error Message", ex.message()) } ); }; @@ -152,7 +152,7 @@ void launch_elevated_process() settings_key::write(LAST_CHANGED_SETTINGS_KEY_STR, box_value(LAUNCH_ELEVATED_PROCESS_SUCCESS_STR)); logger::log_info(L"Elevated Process has been launched.", true); - properties.push_back(pair("Accepted", "True")); + properties.push_back(pair(L"Accepted", L"True")); } else { @@ -171,7 +171,7 @@ void launch_elevated_process() crashes::track_error(error, properties); } - analytics::track_event("OnAdminstratorPrivilageRequested", properties); + analytics::track_event(L"OnAdminstratorPrivilageRequested", properties); } void launch_elevated_process_if_requested() @@ -217,7 +217,7 @@ void initialize_extension_service() report::add_device_metadata(properties); logger::log_error(error); crashes::track_error(error, properties); - analytics::track_event("OnInitializationForExtensionFailed", properties); + analytics::track_event(L"OnInitializationForExtensionFailed", properties); exit_app(e.code()); } diff --git a/src/Notepads.DesktopExtension/frame.h b/src/Notepads.DesktopExtension/frame.h index 6c7750465..7853d40b5 100644 --- a/src/Notepads.DesktopExtension/frame.h +++ b/src/Notepads.DesktopExtension/frame.h @@ -3,12 +3,6 @@ #include "pch.h" #include "dbgeng.h" -#ifdef _DEBUG -#include "rapidjson/prettywriter.h" -#else -#include "rapidjson/writer.h" -#endif - __declspec(selectany) winrt::com_ptr symbols; struct frame @@ -134,33 +128,25 @@ struct frame return (result ? line : 0); } - template - void serialize(json_writer& writer) const noexcept + winrt::Windows::Data::Json::IJsonValue to_json() const noexcept { - if (m_offset <= 0) return; - - auto full_name = winrt::to_string(name()); - auto file_name = winrt::to_string(file()); - auto line_number = line(); - + std::wstring full_name = name().c_str(); auto delimiter = full_name.find_first_of('!'); - auto class_name = delimiter == std::string::npos ? full_name : full_name.substr(0, delimiter); - auto method_name = delimiter == std::string::npos ? "" : full_name.substr(delimiter + 1, full_name.length()); - - writer.StartObject(); - writer.String("className"); - writer.String(class_name.c_str(), static_cast(class_name.length())); - writer.String("methodName"); - writer.String(method_name.c_str(), static_cast(method_name.length())); - writer.String("fileName"); - writer.String(file_name.c_str(), static_cast(file_name.length())); - writer.String("lineNumber"); - writer.Uint(line_number); - writer.EndObject(); + auto class_name = delimiter == std::wstring::npos ? full_name : full_name.substr(0, delimiter); + auto method_name = delimiter == std::wstring::npos ? L"" : full_name.substr(delimiter + 1, full_name.length()); + + auto json_obj = winrt::Windows::Data::Json::JsonObject(); + json_obj.Insert(L"className", JsonValue::CreateStringValue(class_name)); + json_obj.Insert(L"methodName", JsonValue::CreateStringValue(method_name)); + json_obj.Insert(L"fileName", JsonValue::CreateStringValue(file())); + json_obj.Insert(L"lineNumber", JsonValue::CreateNumberValue(line())); + return json_obj; } private: + using JsonValue = winrt::Windows::Data::Json::JsonValue; + static void originate() noexcept { if (!symbols) diff --git a/src/Notepads.DesktopExtension/handled_error_report.h b/src/Notepads.DesktopExtension/handled_error_report.h index 11f7da1b6..529027982 100644 --- a/src/Notepads.DesktopExtension/handled_error_report.h +++ b/src/Notepads.DesktopExtension/handled_error_report.h @@ -27,39 +27,27 @@ struct handled_error_report : managed_error_report protected: - virtual void append_type_data(json_writer& writer) const noexcept + virtual hstring type() const noexcept { - writer.String("type"); - writer.String("handledError"); + return L"handledError"; } - virtual void append_additional_data(json_writer& writer) const noexcept + virtual void append_additional_data(json_object& json_obj) const noexcept { - managed_error_report::append_additional_data(writer); + managed_error_report::append_additional_data(json_obj); // Write custom properties if available if (!m_properties.empty()) { - writer.String("properties"); - writer.StartObject(); + auto properties = json_object(); for (auto& property : m_properties) { - writer.String(property.first.c_str(), static_cast(property.first.length())); - writer.String(property.second.c_str(), static_cast(property.second.length())); + properties.Insert(property.first, JsonValue::CreateStringValue(property.second)); } - writer.EndObject(); - } - } - - /*virtual void append_report(json_writer& writer) const noexcept - { - report::append_report(writer); - if (!m_attachment.empty()) - { - error_attachment_report(m_id, m_attachment).serialize(writer); + json_obj.Insert(L"properties", properties); } - }*/ + } report::dictionary m_properties; }; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/main.cpp b/src/Notepads.DesktopExtension/main.cpp index bcbf4f325..0b8134721 100644 --- a/src/Notepads.DesktopExtension/main.cpp +++ b/src/Notepads.DesktopExtension/main.cpp @@ -29,7 +29,7 @@ bool is_first_instance(hstring mutex_name) report::add_device_metadata(properties); logger::log_error(error); crashes::track_error(error, properties); - analytics::track_event("OnExtensionInstanceDetectionFailed", properties); + analytics::track_event(L"OnExtensionInstanceDetectionFailed", properties); exit_app(e.code()); } @@ -65,7 +65,7 @@ bool is_elevated_process() report::dictionary properties{}; report::add_device_metadata(properties); crashes::track_error(error, properties); - analytics::track_event("OnPrivilageDetectionFailed", properties); + analytics::track_event(L"OnPrivilageDetectionFailed", properties); return false; } } diff --git a/src/Notepads.DesktopExtension/managed_error_report.h b/src/Notepads.DesktopExtension/managed_error_report.h index 3fe5db90d..b85d97dae 100644 --- a/src/Notepads.DesktopExtension/managed_error_report.h +++ b/src/Notepads.DesktopExtension/managed_error_report.h @@ -6,10 +6,11 @@ struct managed_error_report : report { explicit managed_error_report(winrt_error const& error, std::string const& attachment = "") noexcept : - report(), m_error(error), m_attachment(attachment) + report(), m_error(error), m_attachment(m_id, attachment) { - m_sid = winrt::to_string(winrt::to_hstring(winrt::Windows::Foundation::GuidHelper::CreateNewGuid())); - m_sid.erase(0, m_sid.find_first_not_of('{')).erase(m_sid.find_last_not_of('}') + 1); + std::wstring sid = winrt::to_hstring(winrt::Windows::Foundation::GuidHelper::CreateNewGuid()).c_str(); + sid.erase(0, sid.find_first_not_of('{')).erase(sid.find_last_not_of('}') + 1); + m_sid = sid; } managed_error_report(managed_error_report const& other) noexcept : @@ -30,53 +31,48 @@ struct managed_error_report : report { } - std::string sid() const noexcept + hstring sid() const noexcept { return m_sid; } -protected: - - virtual void append_type_data(json_writer& writer) const noexcept + virtual winrt::Windows::Data::Json::IJsonValue to_json() const noexcept { - writer.String("type"); - writer.String("managedError"); - } + auto json_obj = json_array(); - virtual void append_additional_data(json_writer& writer) const noexcept - { - report::append_additional_data(writer); + json_obj.Append(report::to_json()); - writer.String("sid"); - writer.String(m_sid.c_str(), static_cast(m_sid.length())); - writer.String("processId"); - writer.Uint(m_pid); - writer.String("fatal"); - writer.Bool(m_error.fatal()); - writer.String("processName"); - writer.String(m_process.c_str(), static_cast(m_process.length())); - writer.String("errorThreadId"); - writer.Uint(m_thread); + if (!m_attachment.empty()) + { + json_obj.Append(m_attachment.to_json()); + } - // Write exception data - writer.String("exception"); - m_error.serialize(writer); + return json_obj; } - virtual void append_report(json_writer& writer) const noexcept +protected: + + virtual hstring type() const noexcept { - report::append_report(writer); + return L"managedError"; + } - if (!m_attachment.empty()) - { - error_attachment_report(m_id, m_attachment).serialize(writer); - } + virtual void append_additional_data(json_object& json_obj) const noexcept + { + report::append_additional_data(json_obj); + + json_obj.Insert(L"sid", JsonValue::CreateStringValue(m_sid)); + json_obj.Insert(L"processId", JsonValue::CreateNumberValue(m_pid)); + json_obj.Insert(L"fatal", JsonValue::CreateBooleanValue(m_error.fatal())); + json_obj.Insert(L"processName", JsonValue::CreateStringValue(m_process)); + json_obj.Insert(L"errorThreadId", JsonValue::CreateNumberValue(m_thread)); + json_obj.Insert(L"exception", m_error.to_json()); } unsigned m_pid = GetCurrentProcessId(); unsigned m_thread = GetCurrentThreadId(); - std::string m_sid; - std::string m_process = "Notepads32.exe"; - std::string m_attachment; + hstring m_sid; + hstring m_process = L"Notepads32.exe"; + error_attachment_report m_attachment; winrt_error m_error; }; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/pch.cpp b/src/Notepads.DesktopExtension/pch.cpp deleted file mode 100644 index 331e647d7..000000000 --- a/src/Notepads.DesktopExtension/pch.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "pch.h" \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/pch.h b/src/Notepads.DesktopExtension/pch.h index a8b3bc69c..af10e8df0 100644 --- a/src/Notepads.DesktopExtension/pch.h +++ b/src/Notepads.DesktopExtension/pch.h @@ -5,6 +5,7 @@ #include "shlobj_core.h" #include "winrt/Windows.ApplicationModel.h" #include "winrt/Windows.ApplicationModel.Core.h" +#include "winrt/Windows.Data.Json.h" #include "winrt/Windows.Foundation.h" #include "winrt/Windows.Foundation.Collections.h" #include "winrt/Windows.Globalization.DateTimeFormatting.h" @@ -14,8 +15,6 @@ #include "winrt/Windows.System.h" #include "winrt/Windows.System.Profile.h" #include "winrt/Windows.System.UserProfile.h" -#include "winrt/Windows.Web.Http.h" -#include "winrt/Windows.Web.Http.Headers.h" #include "winrt/Notepads.Core.h" #define EXTENSION_MUTEX_NAME L"ExtensionMutex" diff --git a/src/Notepads.DesktopExtension/report.h b/src/Notepads.DesktopExtension/report.h index d86c274e6..012a0f13a 100644 --- a/src/Notepads.DesktopExtension/report.h +++ b/src/Notepads.DesktopExtension/report.h @@ -5,73 +5,31 @@ #define APP_CENTER_FORMAT L"{year.full}-{month.integer(2)}-{day.integer(2)}" \ "T{hour.integer(2)}:{minute.integer(2)}:{second.integer(2)}Z" -const std::string launch_time_stamp = winrt::to_string( - logger::get_utc_time_stamp(APP_CENTER_FORMAT) -); +const winrt::hstring launch_time_stamp = logger::get_utc_time_stamp(APP_CENTER_FORMAT); -__declspec(selectany) std::string last_error_report_sid = ""; +__declspec(selectany) winrt::hstring last_error_report_sid = L""; __declspec(selectany) device device_info {}; struct report { -#ifdef _DEBUG - using json_writer = rapidjson::PrettyWriter; -#else - using json_writer = rapidjson::Writer; -#endif - using Package = winrt::Windows::ApplicationModel::Package; - using MemoryManager = winrt::Windows::System::MemoryManager; - using dictionary = std::vector>; - using ProcessorArchitecture = winrt::Windows::System::ProcessorArchitecture; + using json_object = winrt::Windows::Data::Json::JsonObject; + using dictionary = std::vector>; - virtual void serialize(json_writer& writer) const noexcept + virtual winrt::Windows::Data::Json::IJsonValue to_json() const noexcept { - writer.StartObject(); - - // Write report type data - append_type_data(writer); - - writer.String("id"); - writer.String(m_id.c_str(), static_cast(m_id.length())); - writer.String("timestamp"); - writer.String(m_timestamp.c_str(), static_cast(m_timestamp.length())); - writer.String("appLaunchTimestamp"); - writer.String(launch_time_stamp.c_str(), static_cast(launch_time_stamp.length())); - writer.String("architecture"); - writer.String(m_arch.c_str(), static_cast(m_arch.length())); + auto json_obj = json_object(); + json_obj.Insert(L"type", JsonValue::CreateStringValue(type())); + json_obj.Insert(L"id", JsonValue::CreateStringValue(m_id)); + json_obj.Insert(L"timestamp", JsonValue::CreateStringValue(m_timestamp)); + json_obj.Insert(L"appLaunchTimestamp", JsonValue::CreateStringValue(launch_time_stamp)); + json_obj.Insert(L"architecture", JsonValue::CreateStringValue(m_arch)); // Write report specific data - append_additional_data(writer); + append_additional_data(json_obj); - // Write device specific data - writer.String("device"); - device_info.serialize(writer); + json_obj.Insert(L"device", device_info.to_json()); - writer.EndObject(); - - // Write additional report data - append_report(writer); - } - - static std::string to_string(ProcessorArchitecture arch) noexcept - { - switch (arch) - { - case ProcessorArchitecture::Arm: - return "Arm"; - case ProcessorArchitecture::Arm64: - return "Arm64"; - case ProcessorArchitecture::X86OnArm64: - return "X86OnArm64"; - case ProcessorArchitecture::X86: - return "X86"; - case ProcessorArchitecture::X64: - return "X64"; - case ProcessorArchitecture::Neutral: - return "Neutral"; - default: - return "Unknown"; - } + return json_obj; } static void add_device_metadata(dictionary& properties) noexcept @@ -79,21 +37,25 @@ struct report properties.insert( properties.end(), { - std::pair("AvailableMemory", std::to_string((float)MemoryManager::AppMemoryUsageLimit() / 1024 / 1024)), - std::pair("OSArchitecture", to_string(Package::Current().Id().Architecture())), - std::pair("OSVersion",device_info.osbuild()), - std::pair("IsDesktopExtension", "True"), - std::pair("IsElevated", is_elevated_process() ? "True" : "False") + std::pair(L"AvailableMemory", winrt::to_hstring((float)MemoryManager::AppMemoryUsageLimit() / 1024 / 1024)), + std::pair(L"OSArchitecture", to_hstring(Package::Current().Id().Architecture())), + std::pair(L"OSVersion", device_info.osbuild()), + std::pair(L"IsDesktopExtension", L"True"), + std::pair(L"IsElevated", is_elevated_process() ? L"True" : L"False") } ); } protected: + using hstring = winrt::hstring; + using json_array = winrt::Windows::Data::Json::JsonArray; + report() noexcept { - m_id = winrt::to_string(winrt::to_hstring(winrt::Windows::Foundation::GuidHelper::CreateNewGuid())); - m_id.erase(0, m_id.find_first_not_of('{')).erase(m_id.find_last_not_of('}') + 1); + std::wstring id = winrt::to_hstring(winrt::Windows::Foundation::GuidHelper::CreateNewGuid()).c_str(); + id.erase(0, id.find_first_not_of('{')).erase(id.find_last_not_of('}') + 1); + m_id = id; } report(report const& other) noexcept : @@ -106,23 +68,46 @@ struct report report(report&&) noexcept = default; - virtual void append_type_data(json_writer& /* writer */) const noexcept + virtual hstring type() const noexcept { - // override in child classes + return L""; } - virtual void append_additional_data(json_writer& /* writer */) const noexcept + virtual void append_additional_data(json_object& /* writer */) const noexcept { // override in child classes } - virtual void append_report(json_writer& /* writer */) const noexcept + hstring m_id; + hstring m_process = L"Notepads32.exe"; + hstring m_arch = to_hstring(Package::Current().Id().Architecture()); + hstring m_timestamp = logger::get_utc_time_stamp(APP_CENTER_FORMAT); + +private: + + using Package = winrt::Windows::ApplicationModel::Package; + using JsonValue = winrt::Windows::Data::Json::JsonValue; + using MemoryManager = winrt::Windows::System::MemoryManager; + using ProcessorArchitecture = winrt::Windows::System::ProcessorArchitecture; + + static winrt::hstring to_hstring(ProcessorArchitecture arch) noexcept { - // override in child classes + switch (arch) + { + case ProcessorArchitecture::Arm: + return L"Arm"; + case ProcessorArchitecture::Arm64: + return L"Arm64"; + case ProcessorArchitecture::X86OnArm64: + return L"X86OnArm64"; + case ProcessorArchitecture::X86: + return L"X86"; + case ProcessorArchitecture::X64: + return L"X64"; + case ProcessorArchitecture::Neutral: + return L"Neutral"; + default: + return L"Unknown"; + } } - - std::string m_id; - std::string m_process = "Notepads32.exe"; - std::string m_arch = to_string(Package::Current().Id().Architecture()); - std::string m_timestamp = winrt::to_string(logger::get_utc_time_stamp(APP_CENTER_FORMAT)); }; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/vcpkg.json b/src/Notepads.DesktopExtension/vcpkg.json deleted file mode 100644 index cb4e38d39..000000000 --- a/src/Notepads.DesktopExtension/vcpkg.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "notepads-desktopextension", - "version": "1.0.0.0", - "builtin-baseline": "86d689b2305d8c453418cae1ed2009718d05cddf", - "dependencies": [ - "rapidjson" - ], - "overrides": [ - { - "name": "rapidjson", - "version-date": "2020-09-14" - } - ] -} \ No newline at end of file From 6cb9ddf18659318861e4d9d693175f0bef76b308 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Sat, 3 Jul 2021 19:42:54 +0530 Subject: [PATCH 179/181] remove vcpkg dependency --- .github/workflows/Build.yml | 19 +------------------ 1 file changed, 1 insertion(+), 18 deletions(-) diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index 9f3243f2d..8b5e32ecd 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -12,7 +12,6 @@ jobs: env: Solution_Name: src\Notepads.sln Project_Path: src\Notepads.Package\Notepads.Package.wapproj - Vcpkg_Nuget_Package: ${{ github.repository_owner }}-${{ github.event.repository.name }} runs-on: windows-latest steps: @@ -35,20 +34,6 @@ jobs: msbuild $env:Solution_Name /t:Restore nuget restore $env:Solution_Name - - name: 'Setup Vcpkg Binary Caching' - shell: 'pwsh' - run: | - & $(& $env:Vcpkg_Path fetch nuget | select -last 1) sources add ` - -source "https://nuget.pkg.github.com/$env:Owner/index.json" ` - -storepasswordincleartext ` - -name "$env:Vcpkg_Nuget_Package" ` - -username "$env:Owner" ` - -password "$env:Key" - env: - Owner: ${{ github.repository_owner }} - Key: ${{ secrets.GITHUB_TOKEN }} - Vcpkg_Path: src\packages\vcpkg\vcpkg - - name: Build shell: 'pwsh' run: | @@ -62,6 +47,4 @@ jobs: Appx_Bundle: Always Appx_Bundle_Platforms: x86|x64 Appx_Package_Build_Mode: StoreUpload - Configuration: ${{ matrix.configuration }} - VCPKG_BINARY_SOURCES: 'clear;nuget,${{ env.Vcpkg_Nuget_Package }},readwrite;interactive' - VCPKG_USE_NUGET_CACHE: 'true' \ No newline at end of file + Configuration: ${{ matrix.configuration }} \ No newline at end of file From fe9b754a4f7d92db35bc0c3c1c986cf5c5c558c5 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 23 Jul 2021 22:25:00 +0530 Subject: [PATCH 180/181] chore: refactor project targets --- src/Notepads.Core/Notepads.Core.vcxproj | 1 - .../Notepads.DesktopExtension.vcxproj | 17 ++++++++++++----- src/Notepads.DesktopExtension/appcenter.h | 3 --- src/Notepads.DesktopExtension/device.h | 1 - src/Notepads.DesktopExtension/error.h | 1 - .../error_attachment_report.h | 1 - src/Notepads.DesktopExtension/error_report.h | 1 - src/Notepads.DesktopExtension/event_report.h | 1 - src/Notepads.DesktopExtension/frame.h | 1 - .../handled_error_report.h | 1 - src/Notepads.DesktopExtension/logger.h | 1 - .../managed_error_report.h | 1 - src/Notepads.DesktopExtension/report.h | 1 - src/Notepads.DesktopExtension/settings_key.h | 1 - 14 files changed, 12 insertions(+), 20 deletions(-) diff --git a/src/Notepads.Core/Notepads.Core.vcxproj b/src/Notepads.Core/Notepads.Core.vcxproj index c5d10b8be..9fe25b5ef 100644 --- a/src/Notepads.Core/Notepads.Core.vcxproj +++ b/src/Notepads.Core/Notepads.Core.vcxproj @@ -12,7 +12,6 @@ true true true - false true $(BaseIntermediateOutputPath)Generated Files\ true diff --git a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj index 75b2f581e..e777aca1c 100644 --- a/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj +++ b/src/Notepads.DesktopExtension/Notepads.DesktopExtension.vcxproj @@ -205,7 +205,8 @@ - + + ]]> + - - - + + +#pragma once +#define APP_CENTER_SDK_VERSION L"$(AppCenterSdkVersion)" +#define APP_CENTER_SECRET L"$(AppCenterSecret)" + + + \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/appcenter.h b/src/Notepads.DesktopExtension/appcenter.h index 25294b804..c7803c21c 100644 --- a/src/Notepads.DesktopExtension/appcenter.h +++ b/src/Notepads.DesktopExtension/appcenter.h @@ -27,7 +27,6 @@ struct appcenter } private: - appcenter() noexcept = default; appcenter(appcenter&&) noexcept = default; appcenter(appcenter const& other) noexcept = default; @@ -50,7 +49,6 @@ struct crashes } private: - using HttpStringContent = winrt::Windows::Web::Http::HttpStringContent; crashes() noexcept = default; @@ -74,7 +72,6 @@ struct analytics } private: - using HttpStringContent = winrt::Windows::Web::Http::HttpStringContent; analytics() noexcept = default; diff --git a/src/Notepads.DesktopExtension/device.h b/src/Notepads.DesktopExtension/device.h index 938c56384..e91103471 100644 --- a/src/Notepads.DesktopExtension/device.h +++ b/src/Notepads.DesktopExtension/device.h @@ -99,7 +99,6 @@ struct device } private: - using hstring = winrt::hstring; using Package = winrt::Windows::ApplicationModel::Package; using JsonValue = winrt::Windows::Data::Json::JsonValue; diff --git a/src/Notepads.DesktopExtension/error.h b/src/Notepads.DesktopExtension/error.h index 7361c1b35..af045c96f 100644 --- a/src/Notepads.DesktopExtension/error.h +++ b/src/Notepads.DesktopExtension/error.h @@ -189,7 +189,6 @@ struct winrt_error } private: - using JsonValue = winrt::Windows::Data::Json::JsonValue; using JsonArray = winrt::Windows::Data::Json::JsonArray; diff --git a/src/Notepads.DesktopExtension/error_attachment_report.h b/src/Notepads.DesktopExtension/error_attachment_report.h index 446f814c2..e9e0050b3 100644 --- a/src/Notepads.DesktopExtension/error_attachment_report.h +++ b/src/Notepads.DesktopExtension/error_attachment_report.h @@ -48,7 +48,6 @@ struct error_attachment_report : report hstring m_attachment; private: - //From https://stackoverflow.com/a/34571089/5155484 static std::string base64_encode(std::string const& in) noexcept { diff --git a/src/Notepads.DesktopExtension/error_report.h b/src/Notepads.DesktopExtension/error_report.h index bce888215..bd57421b8 100644 --- a/src/Notepads.DesktopExtension/error_report.h +++ b/src/Notepads.DesktopExtension/error_report.h @@ -38,7 +38,6 @@ struct error_report : report } protected: - managed_error_report m_managed_error_report; handled_error_report m_handled_error_report; }; \ No newline at end of file diff --git a/src/Notepads.DesktopExtension/event_report.h b/src/Notepads.DesktopExtension/event_report.h index 6e9453e35..802c00fcb 100644 --- a/src/Notepads.DesktopExtension/event_report.h +++ b/src/Notepads.DesktopExtension/event_report.h @@ -25,7 +25,6 @@ struct event_report : report } protected: - virtual hstring type() const noexcept { return L"event"; diff --git a/src/Notepads.DesktopExtension/frame.h b/src/Notepads.DesktopExtension/frame.h index 7853d40b5..65e1958dd 100644 --- a/src/Notepads.DesktopExtension/frame.h +++ b/src/Notepads.DesktopExtension/frame.h @@ -144,7 +144,6 @@ struct frame } private: - using JsonValue = winrt::Windows::Data::Json::JsonValue; static void originate() noexcept diff --git a/src/Notepads.DesktopExtension/handled_error_report.h b/src/Notepads.DesktopExtension/handled_error_report.h index 529027982..c3ce03755 100644 --- a/src/Notepads.DesktopExtension/handled_error_report.h +++ b/src/Notepads.DesktopExtension/handled_error_report.h @@ -26,7 +26,6 @@ struct handled_error_report : managed_error_report } protected: - virtual hstring type() const noexcept { return L"handledError"; diff --git a/src/Notepads.DesktopExtension/logger.h b/src/Notepads.DesktopExtension/logger.h index f8e2e68aa..7001fb49b 100644 --- a/src/Notepads.DesktopExtension/logger.h +++ b/src/Notepads.DesktopExtension/logger.h @@ -79,7 +79,6 @@ struct logger } private: - using FileIO = winrt::Windows::Storage::FileIO; using StorageFile = winrt::Windows::Storage::StorageFile; using ApplicationData = winrt::Windows::Storage::ApplicationData; diff --git a/src/Notepads.DesktopExtension/managed_error_report.h b/src/Notepads.DesktopExtension/managed_error_report.h index b85d97dae..93be9567a 100644 --- a/src/Notepads.DesktopExtension/managed_error_report.h +++ b/src/Notepads.DesktopExtension/managed_error_report.h @@ -51,7 +51,6 @@ struct managed_error_report : report } protected: - virtual hstring type() const noexcept { return L"managedError"; diff --git a/src/Notepads.DesktopExtension/report.h b/src/Notepads.DesktopExtension/report.h index 012a0f13a..a8748aad5 100644 --- a/src/Notepads.DesktopExtension/report.h +++ b/src/Notepads.DesktopExtension/report.h @@ -47,7 +47,6 @@ struct report } protected: - using hstring = winrt::hstring; using json_array = winrt::Windows::Data::Json::JsonArray; diff --git a/src/Notepads.DesktopExtension/settings_key.h b/src/Notepads.DesktopExtension/settings_key.h index 857fefa2d..e669ed41a 100644 --- a/src/Notepads.DesktopExtension/settings_key.h +++ b/src/Notepads.DesktopExtension/settings_key.h @@ -22,7 +22,6 @@ struct settings_key } private: - settings_key() noexcept = default; settings_key(settings_key&&) noexcept = default; settings_key(settings_key const& other) noexcept = default; From 7892c00f4bfd5c0e34cba68eb6b9b8d9c1151dd3 Mon Sep 17 00:00:00 2001 From: Soumya Ranjan Mahunt Date: Fri, 23 Jul 2021 22:29:50 +0530 Subject: [PATCH 181/181] chore: resolve codefactor errors --- src/Notepads.DesktopExtension/error_attachment_report.h | 1 - src/Notepads.DesktopExtension/report.h | 1 - 2 files changed, 2 deletions(-) diff --git a/src/Notepads.DesktopExtension/error_attachment_report.h b/src/Notepads.DesktopExtension/error_attachment_report.h index e9e0050b3..cc5ef70e3 100644 --- a/src/Notepads.DesktopExtension/error_attachment_report.h +++ b/src/Notepads.DesktopExtension/error_attachment_report.h @@ -28,7 +28,6 @@ struct error_attachment_report : report } protected: - virtual hstring type() const noexcept { return L"errorAttachment"; diff --git a/src/Notepads.DesktopExtension/report.h b/src/Notepads.DesktopExtension/report.h index a8748aad5..f4a3c3704 100644 --- a/src/Notepads.DesktopExtension/report.h +++ b/src/Notepads.DesktopExtension/report.h @@ -83,7 +83,6 @@ struct report hstring m_timestamp = logger::get_utc_time_stamp(APP_CENTER_FORMAT); private: - using Package = winrt::Windows::ApplicationModel::Package; using JsonValue = winrt::Windows::Data::Json::JsonValue; using MemoryManager = winrt::Windows::System::MemoryManager;