From 71ced8db5697362490342ec240e50dc7c874f107 Mon Sep 17 00:00:00 2001 From: Denny09310 Date: Sun, 9 Nov 2025 12:05:07 +0100 Subject: [PATCH 1/8] refactor: Migrated from Newtonsoft.Json to System.Text.Json, missing one test passing --- src/ElectronNET.API/API/ApiBase.cs | 22 +++- src/ElectronNET.API/API/App.cs | 89 +++++++------- src/ElectronNET.API/API/AutoUpdater.cs | 111 +++++++++--------- src/ElectronNET.API/API/BrowserView.cs | 33 ++---- src/ElectronNET.API/API/BrowserWindow.cs | 69 +++++------ src/ElectronNET.API/API/Clipboard.cs | 48 ++++---- src/ElectronNET.API/API/CommandLine.cs | 11 +- src/ElectronNET.API/API/Cookies.cs | 27 ++--- src/ElectronNET.API/API/Dialog.cs | 57 +++++---- src/ElectronNET.API/API/Dock.cs | 38 +++--- .../API/Entities/BlockMapDataHolder.cs | 6 +- .../API/Entities/BrowserWindowOptions.cs | 14 ++- src/ElectronNET.API/API/Entities/CPUUsage.cs | 2 +- .../API/Entities/ChromeExtensionInfo.cs | 6 +- .../API/Entities/CookieChangedCause.cs | 12 +- .../API/Entities/CookieFilter.cs | 6 +- src/ElectronNET.API/API/Entities/Display.cs | 2 +- src/ElectronNET.API/API/Entities/Extension.cs | 8 +- .../API/Entities/GPUFeatureStatus.cs | 23 ++-- .../API/Entities/InputEvent.cs | 7 +- .../API/Entities/JsonPropertyAttribute.cs | 8 ++ .../API/Entities/JumpListCategory.cs | 9 +- .../API/Entities/JumpListItem.cs | 8 +- src/ElectronNET.API/API/Entities/MenuItem.cs | 10 +- .../API/Entities/MessageBoxOptions.cs | 8 +- .../API/Entities/NativeImage.cs | 4 +- .../API/Entities/NativeImageJsonConverter.cs | 27 +++-- .../API/Entities/NotificationOptions.cs | 2 +- .../API/Entities/OpenDevToolsOptions.cs | 9 +- .../API/Entities/OpenDialogOptions.cs | 9 +- .../API/Entities/OpenExternalOptions.cs | 3 +- .../API/Entities/PrintToPDFOptions.cs | 4 +- .../API/Entities/ProgressBarOptions.cs | 9 +- .../API/Entities/ProgressInfo.cs | 6 +- .../API/Entities/RemovePassword.cs | 8 +- .../API/Entities/ThumbarButton.cs | 8 +- .../API/Entities/TitleBarStyle.cs | 5 +- src/ElectronNET.API/API/GlobalShortcut.cs | 11 +- src/ElectronNET.API/API/HostHook.cs | 44 ++----- src/ElectronNET.API/API/IpcMain.cs | 92 ++------------- src/ElectronNET.API/API/Menu.cs | 37 +++--- src/ElectronNET.API/API/NativeTheme.cs | 23 ++-- src/ElectronNET.API/API/Notification.cs | 39 +++--- src/ElectronNET.API/API/PowerMonitor.cs | 5 +- src/ElectronNET.API/API/Process.cs | 52 ++++---- src/ElectronNET.API/API/Screen.cs | 50 ++++---- src/ElectronNET.API/API/Session.cs | 53 ++++----- src/ElectronNET.API/API/Shell.cs | 42 +++---- src/ElectronNET.API/API/Tray.cs | 19 +-- src/ElectronNET.API/API/WebContents.cs | 60 +++++----- src/ElectronNET.API/API/WebRequest.cs | 12 +- src/ElectronNET.API/API/WindowManager.cs | 39 ++---- src/ElectronNET.API/Bridge/SocketIOFacade.cs | 24 ++-- src/ElectronNET.API/Common/ApiEventManager.cs | 28 +++-- src/ElectronNET.API/Common/Extensions.cs | 2 +- src/ElectronNET.API/Common/ProcessRunner.cs | 2 +- src/ElectronNET.API/Common/RunnerParams.cs | 2 +- .../Converter/ModifierTypeListConverter.cs | 51 ++++---- .../Converter/PageSizeConverter.cs | 28 +++-- .../Converter/TitleBarOverlayConverter.cs | 29 +++-- src/ElectronNET.API/ElectronNET.API.csproj | 4 +- src/ElectronNET.API/ElectronNetRuntime.cs | 6 +- .../Controllers/RuntimeControllerBase.cs | 2 +- .../RuntimeControllerDotNetFirst.cs | 4 +- .../RuntimeControllerElectronFirst.cs | 4 +- .../Runtime/IElectronNetRuntimeController.cs | 2 +- .../ElectronProcess/ElectronProcessActive.cs | 4 +- .../ElectronProcess/ElectronProcessPassive.cs | 2 +- .../Runtime/Services/LifetimeServiceBase.cs | 2 +- .../SocketBridge/SocketBridgeService.cs | 4 +- src/ElectronNET.API/Runtime/StartupManager.cs | 6 +- .../Serialization/ElectronJson.cs | 35 ++++++ .../Tests/BrowserWindowTests.cs | 4 +- .../Tests/CookiesTests.cs | 2 +- .../Tests/IpcMainTests.cs | 14 +-- .../Tests/MenuTests.cs | 4 +- .../Tests/ProcessTests.cs | 2 +- .../Tests/WebContentsTests.cs | 2 +- .../Controllers/ClipboardController.cs | 8 +- .../Views/Clipboard/Index.cshtml | 5 +- 80 files changed, 715 insertions(+), 873 deletions(-) create mode 100644 src/ElectronNET.API/API/Entities/JsonPropertyAttribute.cs create mode 100644 src/ElectronNET.API/Serialization/ElectronJson.cs diff --git a/src/ElectronNET.API/API/ApiBase.cs b/src/ElectronNET.API/API/ApiBase.cs index 13285cac..b8be21b7 100644 --- a/src/ElectronNET.API/API/ApiBase.cs +++ b/src/ElectronNET.API/API/ApiBase.cs @@ -1,11 +1,12 @@ namespace ElectronNET.API { + using ElectronNET.Common; using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Runtime.CompilerServices; + using System.Text.Json; using System.Threading.Tasks; - using ElectronNET.Common; public abstract class ApiBase { @@ -150,14 +151,25 @@ public PropertyGetter(ApiBase apiBase, string callerName, int timeoutMs) var messageName = apiBase.propertyMessageNames.GetOrAdd(callerName, s => apiBase.objectName + s.StripAsync()); - BridgeConnector.Socket.On(eventName, (result) => + BridgeConnector.Socket.On(eventName, (result) => { BridgeConnector.Socket.Off(eventName); lock (this) { - this.tcs?.SetResult(result); - this.tcs = null; + try + { + var value = JsonSerializer.Deserialize(result, Serialization.ElectronJson.Options); + this.tcs?.SetResult(value); + } + catch (Exception ex) + { + this.tcs?.TrySetException(ex); + } + finally + { + this.tcs = null; + } } }); @@ -170,7 +182,7 @@ public PropertyGetter(ApiBase apiBase, string callerName, int timeoutMs) BridgeConnector.Socket.Emit(messageName); } - System.Threading.Tasks.Task.Delay(ApiBase.PropertyTimeout).ContinueWith(_ => + System.Threading.Tasks.Task.Delay(PropertyTimeout).ContinueWith(_ => { if (this.tcs != null) { diff --git a/src/ElectronNET.API/API/App.cs b/src/ElectronNET.API/API/App.cs index 4739d0a6..b0b60062 100644 --- a/src/ElectronNET.API/API/App.cs +++ b/src/ElectronNET.API/API/App.cs @@ -1,13 +1,11 @@ -using ElectronNET.API.Entities; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; +using ElectronNET.API.Entities; +using ElectronNET.API.Extensions; +using ElectronNET.Common; using System; using System.Runtime.InteropServices; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using ElectronNET.API.Extensions; -using ElectronNET.Common; // ReSharper disable InconsistentNaming @@ -271,7 +269,7 @@ public event Action WebContentsCreated /// when Chrome's accessibility support is enabled, otherwise. public event Action AccessibilitySupportChanged { - add => ApiEventManager.AddEvent("app-accessibility-support-changed", GetHashCode(), _accessibilitySupportChanged, value, (args) => (bool)args); + add => ApiEventManager.AddEvent("app-accessibility-support-changed", GetHashCode(), _accessibilitySupportChanged, value, (args) => args.GetBoolean()); remove => ApiEventManager.RemoveEvent("app-accessibility-support-changed", GetHashCode(), _accessibilitySupportChanged, value); } @@ -414,10 +412,7 @@ internal static App Instance private static App _app; private static object _syncRoot = new object(); - private readonly JsonSerializer _jsonSerializer = new JsonSerializer() - { - ContractResolver = new CamelCasePropertyNamesContractResolver() - }; + /// /// Try to close all windows. The event will be emitted first. If all windows are successfully @@ -475,7 +470,7 @@ public void Relaunch() /// Options for the relaunch. public void Relaunch(RelaunchOptions relaunchOptions) { - this.CallMethod1(JObject.FromObject(relaunchOptions, _jsonSerializer)); + this.CallMethod1(relaunchOptions); } /// @@ -495,7 +490,7 @@ public void Focus() /// public void Focus(FocusOptions focusOptions) { - this.CallMethod1(JObject.FromObject(focusOptions, _jsonSerializer)); + this.CallMethod1(focusOptions); } /// @@ -551,11 +546,11 @@ public async Task GetPathAsync(PathName pathName, CancellationToken canc var taskCompletionSource = new TaskCompletionSource(); using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled())) { - BridgeConnector.Socket.On("appGetPathCompleted", (path) => + BridgeConnector.Socket.On("appGetPathCompleted", (path) => { BridgeConnector.Socket.Off("appGetPathCompleted"); - taskCompletionSource.SetResult(path.ToString()); + taskCompletionSource.SetResult(path.GetString()); }); BridgeConnector.Socket.Emit("appGetPath", pathName.GetDescription()); @@ -720,10 +715,10 @@ public async Task SetAsDefaultProtocolClientAsync(string protocol, string var taskCompletionSource = new TaskCompletionSource(); using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled())) { - BridgeConnector.Socket.On("appSetAsDefaultProtocolClientCompleted", (success) => + BridgeConnector.Socket.On("appSetAsDefaultProtocolClientCompleted", (success) => { BridgeConnector.Socket.Off("appSetAsDefaultProtocolClientCompleted"); - taskCompletionSource.SetResult((bool)success); + taskCompletionSource.SetResult(success.GetBoolean()); }); BridgeConnector.Socket.Emit("appSetAsDefaultProtocolClient", protocol, path, args); @@ -774,10 +769,10 @@ public async Task RemoveAsDefaultProtocolClientAsync(string protocol, stri var taskCompletionSource = new TaskCompletionSource(); using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled())) { - BridgeConnector.Socket.On("appRemoveAsDefaultProtocolClientCompleted", (success) => + BridgeConnector.Socket.On("appRemoveAsDefaultProtocolClientCompleted", (success) => { BridgeConnector.Socket.Off("appRemoveAsDefaultProtocolClientCompleted"); - taskCompletionSource.SetResult((bool)success); + taskCompletionSource.SetResult(success.GetBoolean()); }); BridgeConnector.Socket.Emit("appRemoveAsDefaultProtocolClient", protocol, path, args); @@ -846,10 +841,10 @@ public async Task IsDefaultProtocolClientAsync(string protocol, string pat var taskCompletionSource = new TaskCompletionSource(); using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled())) { - BridgeConnector.Socket.On("appIsDefaultProtocolClientCompleted", (success) => + BridgeConnector.Socket.On("appIsDefaultProtocolClientCompleted", (success) => { BridgeConnector.Socket.Off("appIsDefaultProtocolClientCompleted"); - taskCompletionSource.SetResult((bool)success); + taskCompletionSource.SetResult(success.GetBoolean()); }); BridgeConnector.Socket.Emit("appIsDefaultProtocolClient", protocol, path, args); @@ -874,13 +869,13 @@ public async Task SetUserTasksAsync(UserTask[] userTasks, CancellationToke var taskCompletionSource = new TaskCompletionSource(); using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled())) { - BridgeConnector.Socket.On("appSetUserTasksCompleted", (success) => + BridgeConnector.Socket.On("appSetUserTasksCompleted", (success) => { BridgeConnector.Socket.Off("appSetUserTasksCompleted"); - taskCompletionSource.SetResult((bool)success); + taskCompletionSource.SetResult(success.GetBoolean()); }); - BridgeConnector.Socket.Emit("appSetUserTasks", JArray.FromObject(userTasks, _jsonSerializer)); + BridgeConnector.Socket.Emit("appSetUserTasks", userTasks); return await taskCompletionSource.Task .ConfigureAwait(false); @@ -916,7 +911,7 @@ public async Task GetJumpListSettingsAsync(CancellationToken c /// Array of objects. public void SetJumpList(JumpListCategory[] categories) { - this.CallMethod1(JArray.FromObject(categories, _jsonSerializer)); + this.CallMethod1(categories); } /// @@ -947,19 +942,21 @@ public async Task RequestSingleInstanceLockAsync(Action var taskCompletionSource = new TaskCompletionSource(); using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled())) { - BridgeConnector.Socket.On("appRequestSingleInstanceLockCompleted", (success) => + BridgeConnector.Socket.On("appRequestSingleInstanceLockCompleted", (success) => { BridgeConnector.Socket.Off("appRequestSingleInstanceLockCompleted"); - taskCompletionSource.SetResult((bool)success); + taskCompletionSource.SetResult(success.GetBoolean()); }); BridgeConnector.Socket.Off("secondInstance"); - BridgeConnector.Socket.On("secondInstance", (result) => + BridgeConnector.Socket.On("secondInstance", (result) => { - JArray results = (JArray)result; - string[] args = results.First.ToObject(); - string workingDirectory = results.Last.ToObject(); - + var arr = result.EnumerateArray(); + var e = arr.GetEnumerator(); + e.MoveNext(); + var args = e.Current.Deserialize(JsonSerializerOptions.Default); + e.MoveNext(); + var workingDirectory = e.Current.GetString(); newInstanceOpened(args, workingDirectory); }); @@ -1071,13 +1068,13 @@ public async Task ImportCertificateAsync(ImportCertificateOptions options, var taskCompletionSource = new TaskCompletionSource(); using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled())) { - BridgeConnector.Socket.On("appImportCertificateCompleted", (result) => + BridgeConnector.Socket.On("appImportCertificateCompleted", (result) => { BridgeConnector.Socket.Off("appImportCertificateCompleted"); - taskCompletionSource.SetResult((int)result); + taskCompletionSource.SetResult(result.GetInt32()); }); - BridgeConnector.Socket.Emit("appImportCertificate", JObject.FromObject(options, _jsonSerializer)); + BridgeConnector.Socket.Emit("appImportCertificate", options); return await taskCompletionSource.Task .ConfigureAwait(false); @@ -1127,10 +1124,10 @@ public async Task SetBadgeCountAsync(int count, CancellationToken cancella var taskCompletionSource = new TaskCompletionSource(); using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled())) { - BridgeConnector.Socket.On("appSetBadgeCountCompleted", (success) => + BridgeConnector.Socket.On("appSetBadgeCountCompleted", (success) => { BridgeConnector.Socket.Off("appSetBadgeCountCompleted"); - taskCompletionSource.SetResult((bool)success); + taskCompletionSource.SetResult(success.GetBoolean()); }); BridgeConnector.Socket.Emit("appSetBadgeCount", count); @@ -1187,11 +1184,11 @@ public async Task GetLoginItemSettingsAsync(LoginItemSettings var taskCompletionSource = new TaskCompletionSource(); using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled())) { - BridgeConnector.Socket.On("appGetLoginItemSettingsCompleted", (loginItemSettings) => + BridgeConnector.Socket.On("appGetLoginItemSettingsCompleted", (loginItemSettings) => { BridgeConnector.Socket.Off("appGetLoginItemSettingsCompleted"); - var result = ((JObject)loginItemSettings).ToObject(); + var result = JsonSerializer.Deserialize(loginItemSettings, Serialization.ElectronJson.Options); taskCompletionSource.SetResult(result); }); @@ -1202,7 +1199,7 @@ public async Task GetLoginItemSettingsAsync(LoginItemSettings } else { - BridgeConnector.Socket.Emit("appGetLoginItemSettings", JObject.FromObject(options, _jsonSerializer)); + BridgeConnector.Socket.Emit("appGetLoginItemSettings", options); } return await taskCompletionSource.Task @@ -1218,7 +1215,7 @@ public async Task GetLoginItemSettingsAsync(LoginItemSettings /// public void SetLoginItemSettings(LoginSettings loginSettings) { - this.CallMethod1(JObject.FromObject(loginSettings, _jsonSerializer)); + this.CallMethod1(loginSettings); } /// @@ -1270,7 +1267,7 @@ public void ShowAboutPanel() /// About panel options. public void SetAboutPanelOptions(AboutPanelOptions options) { - this.CallMethod1(JObject.FromObject(options, _jsonSerializer)); + this.CallMethod1(options); } /// @@ -1306,14 +1303,14 @@ public Task UserAgentFallbackAsync { get { - return Task.Run(() => + return Task.Run(() => { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("appGetUserAgentFallbackCompleted", (result) => + BridgeConnector.Socket.On("appGetUserAgentFallbackCompleted", (result) => { BridgeConnector.Socket.Off("appGetUserAgentFallbackCompleted"); - taskCompletionSource.SetResult((string)result); + taskCompletionSource.SetResult(result.GetString()); }); BridgeConnector.Socket.Emit("appGetUserAgentFallback"); @@ -1364,4 +1361,4 @@ public void Once(string eventName, Action action) public async Task Once(string eventName, Action action) => await Events.Instance.Once(ModuleName, eventName, action).ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/ElectronNET.API/API/AutoUpdater.cs b/src/ElectronNET.API/API/AutoUpdater.cs index ed7e9e6a..e7c2b028 100644 --- a/src/ElectronNET.API/API/AutoUpdater.cs +++ b/src/ElectronNET.API/API/AutoUpdater.cs @@ -1,11 +1,10 @@ -using ElectronNET.API.Entities; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; +using ElectronNET.API.Entities; +using ElectronNET.API.Serialization; +using ElectronNET.Common; using System; using System.Collections.Generic; +using System.Text.Json; using System.Threading.Tasks; -using ElectronNET.Common; // ReSharper disable InconsistentNaming @@ -23,14 +22,14 @@ public bool AutoDownload { get { - return Task.Run(() => + return Task.Run(() => { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("autoUpdater-autoDownload-get-reply", (result) => + BridgeConnector.Socket.On("autoUpdater-autoDownload-get-reply", (result) => { BridgeConnector.Socket.Off("autoUpdater-autoDownload-get-reply"); - taskCompletionSource.SetResult((bool)result); + taskCompletionSource.SetResult(result.GetBoolean()); }); BridgeConnector.Socket.Emit("autoUpdater-autoDownload-get"); @@ -53,14 +52,14 @@ public bool AutoInstallOnAppQuit { get { - return Task.Run(() => + return Task.Run(() => { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("autoUpdater-autoInstallOnAppQuit-get-reply", (result) => + BridgeConnector.Socket.On("autoUpdater-autoInstallOnAppQuit-get-reply", (result) => { BridgeConnector.Socket.Off("autoUpdater-autoInstallOnAppQuit-get-reply"); - taskCompletionSource.SetResult((bool)result); + taskCompletionSource.SetResult(result.GetBoolean()); }); BridgeConnector.Socket.Emit("autoUpdater-autoInstallOnAppQuit-get"); @@ -84,14 +83,14 @@ public bool AllowPrerelease { get { - return Task.Run(() => + return Task.Run(() => { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("autoUpdater-allowPrerelease-get-reply", (result) => + BridgeConnector.Socket.On("autoUpdater-allowPrerelease-get-reply", (result) => { BridgeConnector.Socket.Off("autoUpdater-allowPrerelease-get-reply"); - taskCompletionSource.SetResult((bool)result); + taskCompletionSource.SetResult(result.GetBoolean()); }); BridgeConnector.Socket.Emit("autoUpdater-allowPrerelease-get"); @@ -113,14 +112,14 @@ public bool FullChangelog { get { - return Task.Run(() => + return Task.Run(() => { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("autoUpdater-fullChangelog-get-reply", (result) => + BridgeConnector.Socket.On("autoUpdater-fullChangelog-get-reply", (result) => { BridgeConnector.Socket.Off("autoUpdater-fullChangelog-get-reply"); - taskCompletionSource.SetResult((bool)result); + taskCompletionSource.SetResult(result.GetBoolean()); }); BridgeConnector.Socket.Emit("autoUpdater-fullChangelog-get"); @@ -143,14 +142,14 @@ public bool AllowDowngrade { get { - return Task.Run(() => + return Task.Run(() => { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("autoUpdater-allowDowngrade-get-reply", (result) => + BridgeConnector.Socket.On("autoUpdater-allowDowngrade-get-reply", (result) => { BridgeConnector.Socket.Off("autoUpdater-allowDowngrade-get-reply"); - taskCompletionSource.SetResult((bool)result); + taskCompletionSource.SetResult(result.GetBoolean()); }); BridgeConnector.Socket.Emit("autoUpdater-allowDowngrade-get"); @@ -171,14 +170,14 @@ public string UpdateConfigPath { get { - return Task.Run(() => + return Task.Run(() => { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("autoUpdater-updateConfigPath-get-reply", (result) => + BridgeConnector.Socket.On("autoUpdater-updateConfigPath-get-reply", (result) => { BridgeConnector.Socket.Off("autoUpdater-updateConfigPath-get-reply"); - taskCompletionSource.SetResult(result.ToString()); + taskCompletionSource.SetResult(result.GetString()); }); BridgeConnector.Socket.Emit("autoUpdater-updateConfigPath-get"); @@ -195,14 +194,14 @@ public Task CurrentVersionAsync { get { - return Task.Run(() => + return Task.Run(() => { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("autoUpdater-currentVersion-get-reply", (result) => + BridgeConnector.Socket.On("autoUpdater-currentVersion-get-reply", (result) => { BridgeConnector.Socket.Off("autoUpdater-currentVersion-get-reply"); - SemVer version = ((JObject)result).ToObject(); + var version = result.Deserialize(ElectronJsonContext.Default.SemVer); taskCompletionSource.SetResult(version); }); BridgeConnector.Socket.Emit("autoUpdater-currentVersion-get"); @@ -233,14 +232,14 @@ public Task ChannelAsync { get { - return Task.Run(() => + return Task.Run(() => { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("autoUpdater-channel-get-reply", (result) => + BridgeConnector.Socket.On("autoUpdater-channel-get-reply", (result) => { BridgeConnector.Socket.Off("autoUpdater-channel-get-reply"); - taskCompletionSource.SetResult(result.ToString()); + taskCompletionSource.SetResult(result.GetString()); }); BridgeConnector.Socket.Emit("autoUpdater-channel-get"); @@ -260,10 +259,10 @@ public Task> RequestHeadersAsync return Task.Run(() => { var taskCompletionSource = new TaskCompletionSource>(); - BridgeConnector.Socket.On("autoUpdater-requestHeaders-get-reply", (headers) => + BridgeConnector.Socket.On("autoUpdater-requestHeaders-get-reply", (headers) => { BridgeConnector.Socket.Off("autoUpdater-requestHeaders-get-reply"); - Dictionary result = ((JObject)headers).ToObject>(); + var result = headers.Deserialize>(ElectronJson.Options); taskCompletionSource.SetResult(result); }); BridgeConnector.Socket.Emit("autoUpdater-requestHeaders-get"); @@ -279,7 +278,7 @@ public Dictionary RequestHeaders { set { - BridgeConnector.Socket.Emit("autoUpdater-requestHeaders-set", JObject.FromObject(value, _jsonSerializer)); + BridgeConnector.Socket.Emit("autoUpdater-requestHeaders-set", value); } } @@ -311,7 +310,7 @@ public event Action OnCheckingForUpdate /// public event Action OnUpdateAvailable { - add => ApiEventManager.AddEvent("autoUpdater-update-available", GetHashCode(), _updateAvailable, value, (args) => JObject.Parse(args.ToString()).ToObject()); + add => ApiEventManager.AddEvent("autoUpdater-update-available", GetHashCode(), _updateAvailable, value, (args) => JsonSerializer.Deserialize(args, ElectronJsonContext.Default.UpdateInfo)); remove => ApiEventManager.RemoveEvent("autoUpdater-update-available", GetHashCode(), _updateAvailable, value); } @@ -322,7 +321,7 @@ public event Action OnUpdateAvailable /// public event Action OnUpdateNotAvailable { - add => ApiEventManager.AddEvent("autoUpdater-update-not-available", GetHashCode(), _updateNotAvailable, value, (args) => JObject.Parse(args.ToString()).ToObject()); + add => ApiEventManager.AddEvent("autoUpdater-update-not-available", GetHashCode(), _updateNotAvailable, value, (args) => JsonSerializer.Deserialize(args, ElectronJsonContext.Default.UpdateInfo)); remove => ApiEventManager.RemoveEvent("autoUpdater-update-not-available", GetHashCode(), _updateNotAvailable, value); } @@ -333,7 +332,7 @@ public event Action OnUpdateNotAvailable /// public event Action OnDownloadProgress { - add => ApiEventManager.AddEvent("autoUpdater-download-progress", GetHashCode(), _downloadProgress, value, (args) => JObject.Parse(args.ToString()).ToObject()); + add => ApiEventManager.AddEvent("autoUpdater-download-progress", GetHashCode(), _downloadProgress, value, (args) => JsonSerializer.Deserialize(args, ElectronJsonContext.Default.ProgressInfo)); remove => ApiEventManager.RemoveEvent("autoUpdater-download-progress", GetHashCode(), _downloadProgress, value); } @@ -344,7 +343,7 @@ public event Action OnDownloadProgress /// public event Action OnUpdateDownloaded { - add => ApiEventManager.AddEvent("autoUpdater-update-downloaded", GetHashCode(), _updateDownloaded, value, (args) => JObject.Parse(args.ToString()).ToObject()); + add => ApiEventManager.AddEvent("autoUpdater-update-downloaded", GetHashCode(), _updateDownloaded, value, (args) => JsonSerializer.Deserialize(args, ElectronJsonContext.Default.UpdateInfo)); remove => ApiEventManager.RemoveEvent("autoUpdater-update-downloaded", GetHashCode(), _updateDownloaded, value); } @@ -385,26 +384,26 @@ public Task CheckForUpdatesAsync() var taskCompletionSource = new TaskCompletionSource(); string guid = Guid.NewGuid().ToString(); - BridgeConnector.Socket.On("autoUpdaterCheckForUpdatesComplete" + guid, (updateCheckResult) => + BridgeConnector.Socket.On("autoUpdaterCheckForUpdatesComplete" + guid, (updateCheckResult) => { try { BridgeConnector.Socket.Off("autoUpdaterCheckForUpdatesComplete" + guid); BridgeConnector.Socket.Off("autoUpdaterCheckForUpdatesError" + guid); - taskCompletionSource.SetResult(JObject.Parse(updateCheckResult.ToString()).ToObject()); + taskCompletionSource.SetResult(updateCheckResult.Deserialize(ElectronJsonContext.Default.UpdateCheckResult)); } catch (Exception ex) { taskCompletionSource.SetException(ex); } }); - BridgeConnector.Socket.On("autoUpdaterCheckForUpdatesError" + guid, (error) => + BridgeConnector.Socket.On("autoUpdaterCheckForUpdatesError" + guid, (result) => { BridgeConnector.Socket.Off("autoUpdaterCheckForUpdatesComplete" + guid); BridgeConnector.Socket.Off("autoUpdaterCheckForUpdatesError" + guid); string message = "An error occurred in CheckForUpdatesAsync"; - if (error != null && !string.IsNullOrEmpty(error.ToString())) - message = JsonConvert.SerializeObject(error); + var error = result.GetString(); + if (!string.IsNullOrEmpty(error)) message = error; taskCompletionSource.SetException(new Exception(message)); }); @@ -424,29 +423,26 @@ public Task CheckForUpdatesAndNotifyAsync() var taskCompletionSource = new TaskCompletionSource(); string guid = Guid.NewGuid().ToString(); - BridgeConnector.Socket.On("autoUpdaterCheckForUpdatesAndNotifyComplete" + guid, (updateCheckResult) => + BridgeConnector.Socket.On("autoUpdaterCheckForUpdatesAndNotifyComplete" + guid, (updateCheckResult) => { try { BridgeConnector.Socket.Off("autoUpdaterCheckForUpdatesAndNotifyComplete" + guid); BridgeConnector.Socket.Off("autoUpdaterCheckForUpdatesAndNotifyError" + guid); - if (updateCheckResult == null) - taskCompletionSource.SetResult(null); - else - taskCompletionSource.SetResult(JObject.Parse(updateCheckResult.ToString()).ToObject()); + taskCompletionSource.SetResult(updateCheckResult.Deserialize(ElectronJsonContext.Default.UpdateCheckResult)); } catch (Exception ex) { taskCompletionSource.SetException(ex); } }); - BridgeConnector.Socket.On("autoUpdaterCheckForUpdatesAndNotifyError" + guid, (error) => + BridgeConnector.Socket.On("autoUpdaterCheckForUpdatesAndNotifyError" + guid, (result) => { BridgeConnector.Socket.Off("autoUpdaterCheckForUpdatesAndNotifyComplete" + guid); BridgeConnector.Socket.Off("autoUpdaterCheckForUpdatesAndNotifyError" + guid); string message = "An error occurred in autoUpdaterCheckForUpdatesAndNotify"; - if (error != null) - message = JsonConvert.SerializeObject(error); + var error = result.GetString(); + if (!string.IsNullOrEmpty(error)) message = error; taskCompletionSource.SetException(new Exception(message)); }); @@ -478,10 +474,10 @@ public Task DownloadUpdateAsync() var taskCompletionSource = new TaskCompletionSource(); string guid = Guid.NewGuid().ToString(); - BridgeConnector.Socket.On("autoUpdaterDownloadUpdateComplete" + guid, (downloadedPath) => + BridgeConnector.Socket.On("autoUpdaterDownloadUpdateComplete" + guid, (downloadedPath) => { BridgeConnector.Socket.Off("autoUpdaterDownloadUpdateComplete" + guid); - taskCompletionSource.SetResult(downloadedPath.ToString()); + taskCompletionSource.SetResult(downloadedPath.GetString()); }); BridgeConnector.Socket.Emit("autoUpdaterDownloadUpdate", guid); @@ -498,10 +494,10 @@ public Task GetFeedURLAsync() var taskCompletionSource = new TaskCompletionSource(); string guid = Guid.NewGuid().ToString(); - BridgeConnector.Socket.On("autoUpdaterGetFeedURLComplete" + guid, (downloadedPath) => + BridgeConnector.Socket.On("autoUpdaterGetFeedURLComplete" + guid, (downloadedPath) => { BridgeConnector.Socket.Off("autoUpdaterGetFeedURLComplete" + guid); - taskCompletionSource.SetResult(downloadedPath.ToString()); + taskCompletionSource.SetResult(downloadedPath.GetString()); }); BridgeConnector.Socket.Emit("autoUpdaterGetFeedURL", guid); @@ -509,9 +505,8 @@ public Task GetFeedURLAsync() return taskCompletionSource.Task; } - private readonly JsonSerializer _jsonSerializer = new JsonSerializer() - { - ContractResolver = new CamelCasePropertyNamesContractResolver() - }; + } -} \ No newline at end of file +} + + diff --git a/src/ElectronNET.API/API/BrowserView.cs b/src/ElectronNET.API/API/BrowserView.cs index 50814f2c..02a761af 100644 --- a/src/ElectronNET.API/API/BrowserView.cs +++ b/src/ElectronNET.API/API/BrowserView.cs @@ -1,14 +1,13 @@ -using ElectronNET.API.Entities; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; +using ElectronNET.API.Entities; +using ElectronNET.API.Serialization; +using System.Text.Json; using System.Threading.Tasks; namespace ElectronNET.API { /// - /// A BrowserView can be used to embed additional web content into a BrowserWindow. - /// It is like a child window, except that it is positioned relative to its owning window. + /// A BrowserView can be used to embed additional web content into a BrowserWindow. + /// It is like a child window, except that it is positioned relative to its owning window. /// It is meant to be an alternative to the webview tag. /// public class BrowserView @@ -16,9 +15,6 @@ public class BrowserView /// /// Gets the identifier. /// - /// - /// The identifier. - /// public int Id { get; internal set; } /// @@ -28,7 +24,6 @@ public class BrowserView /// /// Resizes and moves the view to the supplied bounds relative to the window. - /// /// (experimental) /// public Rectangle Bounds @@ -39,10 +34,10 @@ public Rectangle Bounds Task.Run(() => { - BridgeConnector.Socket.On("browserView-getBounds-reply", (result) => + BridgeConnector.Socket.On("browserView-getBounds-reply", (result) => { BridgeConnector.Socket.Off("browserView-getBounds-reply"); - taskCompletionSource.SetResult(result); + taskCompletionSource.SetResult(result.Deserialize(ElectronJsonContext.Default.Rectangle)); }); BridgeConnector.Socket.Emit("browserView-getBounds", Id); @@ -52,7 +47,7 @@ public Rectangle Bounds } set { - BridgeConnector.Socket.Emit("browserView-setBounds", Id, JObject.FromObject(value, _jsonSerializer)); + BridgeConnector.Socket.Emit("browserView-setBounds", Id, value); } } @@ -74,12 +69,11 @@ internal BrowserView(int id) /// public void SetAutoResize(AutoResizeOptions options) { - BridgeConnector.Socket.Emit("browserView-setAutoResize", Id, JObject.FromObject(options, _jsonSerializer)); + BridgeConnector.Socket.Emit("browserView-setAutoResize", Id, options); } /// /// Color in #aarrggbb or #argb form. The alpha channel is optional. - /// /// (experimental) /// /// Color in #aarrggbb or #argb form. The alpha channel is optional. @@ -87,11 +81,6 @@ public void SetBackgroundColor(string color) { BridgeConnector.Socket.Emit("browserView-setBackgroundColor", Id, color); } - - private JsonSerializer _jsonSerializer = new JsonSerializer() - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - NullValueHandling = NullValueHandling.Ignore - }; } -} \ No newline at end of file +} + diff --git a/src/ElectronNET.API/API/BrowserWindow.cs b/src/ElectronNET.API/API/BrowserWindow.cs index 0c0e54a1..646523af 100644 --- a/src/ElectronNET.API/API/BrowserWindow.cs +++ b/src/ElectronNET.API/API/BrowserWindow.cs @@ -1,23 +1,17 @@ -using ElectronNET.API.Entities; +using ElectronNET.API.Entities; using ElectronNET.API.Extensions; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; -using ElectronNET.Common; // ReSharper disable InconsistentNaming namespace ElectronNET.API; -using System.Collections.Concurrent; -using System.Diagnostics; -using System.Runtime.CompilerServices; using ElectronNET.Common; +using System.Text.Json; /// /// Create and control browser windows. @@ -469,7 +463,7 @@ internal BrowserWindow(int id) /// The aspect ratio to maintain for some portion of the content view. /// The extra size not to be included while maintaining the aspect ratio. public void SetAspectRatio(double aspectRatio, Size extraSize) => - this.CallMethod2(aspectRatio, JObject.FromObject(extraSize, _jsonSerializer)); + this.CallMethod2(aspectRatio, extraSize); /// /// This will make a window maintain an aspect ratio. The extra size allows a developer to have space, @@ -486,7 +480,7 @@ public void SetAspectRatio(double aspectRatio, Size extraSize) => /// The aspect ratio to maintain for some portion of the content view. /// The extra size not to be included while maintaining the aspect ratio. public void SetAspectRatio(int aspectRatio, Size extraSize) => - this.CallMethod2(aspectRatio, JObject.FromObject(extraSize, _jsonSerializer)); + this.CallMethod2(aspectRatio, extraSize); /// /// Uses Quick Look to preview a file at a given path. @@ -515,14 +509,14 @@ public void SetAspectRatio(int aspectRatio, Size extraSize) => /// Resizes and moves the window to the supplied bounds /// /// - public void SetBounds(Rectangle bounds) => this.CallMethod1(JObject.FromObject(bounds, _jsonSerializer)); + public void SetBounds(Rectangle bounds) => this.CallMethod1(bounds); /// /// Resizes and moves the window to the supplied bounds /// /// /// - public void SetBounds(Rectangle bounds, bool animate) => this.CallMethod2(JObject.FromObject(bounds, _jsonSerializer), animate); + public void SetBounds(Rectangle bounds, bool animate) => this.CallMethod2(bounds, animate); /// /// Gets the bounds asynchronous. @@ -534,14 +528,14 @@ public void SetAspectRatio(int aspectRatio, Size extraSize) => /// Resizes and moves the window’s client area (e.g. the web page) to the supplied bounds. /// /// - public void SetContentBounds(Rectangle bounds) => this.CallMethod1(JObject.FromObject(bounds, _jsonSerializer)); + public void SetContentBounds(Rectangle bounds) => this.CallMethod1(bounds); /// /// Resizes and moves the window’s client area (e.g. the web page) to the supplied bounds. /// /// /// - public void SetContentBounds(Rectangle bounds, bool animate) => this.CallMethod2(JObject.FromObject(bounds, _jsonSerializer), animate); + public void SetContentBounds(Rectangle bounds, bool animate) => this.CallMethod2(bounds, animate); /// /// Gets the content bounds asynchronous. @@ -749,10 +743,10 @@ public void SetPosition(int x, int y) { // Workaround Windows 10 / Electron Bug // https://github.com/electron/electron/issues/4045 - ////if (isWindows10()) - ////{ - //// x = x - 7; - ////} + //if (isWindows10()) + //{ + // x = x - 7; + //} this.CallMethod2(x, y); } @@ -766,10 +760,11 @@ public void SetPosition(int x, int y, bool animate) { // Workaround Windows 10 / Electron Bug // https://github.com/electron/electron/issues/4045 - ////if (isWindows10()) - ////{ - //// x = x - 7; - ////} + //if (isWindows10()) + //{ + // x = x - 7; + //} + this.CallMethod3(x, y, animate); } @@ -894,7 +889,7 @@ private bool isWindows10() /// /// /// - public void LoadURL(string url, LoadURLOptions options) => this.CallMethod2(url, JObject.FromObject(options, _jsonSerializer)); + public void LoadURL(string url, LoadURLOptions options) => this.CallMethod2(url, options); /// /// Same as webContents.reload. @@ -925,13 +920,13 @@ public IReadOnlyCollection MenuItems public void SetMenu(MenuItem[] menuItems) { menuItems.AddMenuItemsId(); - this.CallMethod1(JArray.FromObject(menuItems, _jsonSerializer)); + this.CallMethod1(menuItems); _items.AddRange(menuItems); BridgeConnector.Socket.Off("windowMenuItemClicked"); - BridgeConnector.Socket.On("windowMenuItemClicked", (id) => + BridgeConnector.Socket.On("windowMenuItemClicked", (id) => { - MenuItem menuItem = _items.GetMenuItem(id.ToString()); + MenuItem menuItem = _items.GetMenuItem(id.GetString()); menuItem?.Click(); }); } @@ -967,7 +962,7 @@ public void SetMenu(MenuItem[] menuItems) /// /// public void SetProgressBar(double progress, ProgressBarOptions progressBarOptions) => - this.CallMethod2(progress, JObject.FromObject(progressBarOptions, _jsonSerializer)); + this.CallMethod2(progress, progressBarOptions); /// /// Sets whether the window should have a shadow. On Windows and Linux does nothing. @@ -1015,22 +1010,22 @@ public Task SetThumbarButtonsAsync(ThumbarButton[] thumbarButtons) { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("browserWindowSetThumbarButtons-completed", (success) => + BridgeConnector.Socket.On("browserWindowSetThumbarButtons-completed", (success) => { BridgeConnector.Socket.Off("browserWindowSetThumbarButtons-completed"); - taskCompletionSource.SetResult((bool)success); + taskCompletionSource.SetResult(success.GetBoolean()); }); thumbarButtons.AddThumbarButtonsId(); - BridgeConnector.Socket.Emit("browserWindowSetThumbarButtons", Id, JArray.FromObject(thumbarButtons, _jsonSerializer)); + BridgeConnector.Socket.Emit("browserWindowSetThumbarButtons", Id, thumbarButtons); _thumbarButtons.Clear(); _thumbarButtons.AddRange(thumbarButtons); BridgeConnector.Socket.Off("thumbarButtonClicked"); - BridgeConnector.Socket.On("thumbarButtonClicked", (id) => + BridgeConnector.Socket.On("thumbarButtonClicked", (id) => { - ThumbarButton thumbarButton = _thumbarButtons.GetThumbarButton(id.ToString()); + ThumbarButton thumbarButton = _thumbarButtons.GetThumbarButton(id.GetString()); thumbarButton?.Click(); }); @@ -1058,7 +1053,7 @@ public Task SetThumbarButtonsAsync(ThumbarButton[] thumbarButtons) /// If one of those properties is not set, then neither will be used. /// /// - public void SetAppDetails(AppDetailsOptions options) => this.CallMethod1(JObject.FromObject(options, _jsonSerializer)); + public void SetAppDetails(AppDetailsOptions options) => this.CallMethod1(options); /// /// Same as webContents.showDefinitionForSelection(). @@ -1146,7 +1141,7 @@ public void SetParentWindow(BrowserWindow parent) } else { - BridgeConnector.Socket.Emit("browserWindowSetParentWindow", Id, JObject.FromObject(parent, _jsonSerializer)); + BridgeConnector.Socket.Emit("browserWindowSetParentWindow", Id, parent); } } @@ -1210,10 +1205,4 @@ public void SetBrowserView(BrowserView browserView) // This message name does not match the default ApiBase naming convention. BridgeConnector.Socket.Emit("browserWindow-setBrowserView", Id, browserView.Id); } - - private readonly JsonSerializer _jsonSerializer = new() - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - NullValueHandling = NullValueHandling.Ignore - }; } \ No newline at end of file diff --git a/src/ElectronNET.API/API/Clipboard.cs b/src/ElectronNET.API/API/Clipboard.cs index 4a808475..fada11f6 100644 --- a/src/ElectronNET.API/API/Clipboard.cs +++ b/src/ElectronNET.API/API/Clipboard.cs @@ -1,7 +1,6 @@ -using ElectronNET.API.Entities; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; +using ElectronNET.API.Entities; +using ElectronNET.API.Serialization; +using System.Text.Json; using System.Threading.Tasks; namespace ElectronNET.API @@ -46,11 +45,11 @@ public Task ReadTextAsync(string type = "") { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("clipboard-readText-Completed", (text) => + BridgeConnector.Socket.On("clipboard-readText-Completed", (text) => { BridgeConnector.Socket.Off("clipboard-readText-Completed"); - taskCompletionSource.SetResult(text.ToString()); + taskCompletionSource.SetResult(text.GetString()); }); BridgeConnector.Socket.Emit("clipboard-readText", type); @@ -77,11 +76,11 @@ public Task ReadHTMLAsync(string type = "") { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("clipboard-readHTML-Completed", (text) => + BridgeConnector.Socket.On("clipboard-readHTML-Completed", (text) => { BridgeConnector.Socket.Off("clipboard-readHTML-Completed"); - taskCompletionSource.SetResult(text.ToString()); + taskCompletionSource.SetResult(text.GetString()); }); BridgeConnector.Socket.Emit("clipboard-readHTML", type); @@ -108,11 +107,11 @@ public Task ReadRTFAsync(string type = "") { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("clipboard-readRTF-Completed", (text) => + BridgeConnector.Socket.On("clipboard-readRTF-Completed", (text) => { BridgeConnector.Socket.Off("clipboard-readRTF-Completed"); - taskCompletionSource.SetResult(text.ToString()); + taskCompletionSource.SetResult(text.GetString()); }); BridgeConnector.Socket.Emit("clipboard-readRTF", type); @@ -140,11 +139,11 @@ public Task ReadBookmarkAsync() { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("clipboard-readBookmark-Completed", (bookmark) => + BridgeConnector.Socket.On("clipboard-readBookmark-Completed", (bookmark) => { BridgeConnector.Socket.Off("clipboard-readBookmark-Completed"); - taskCompletionSource.SetResult(((JObject)bookmark).ToObject()); + taskCompletionSource.SetResult(JsonSerializer.Deserialize(bookmark, ElectronJson.Options)); }); BridgeConnector.Socket.Emit("clipboard-readBookmark"); @@ -177,11 +176,11 @@ public Task ReadFindTextAsync() { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("clipboard-readFindText-Completed", (text) => + BridgeConnector.Socket.On("clipboard-readFindText-Completed", (text) => { BridgeConnector.Socket.Off("clipboard-readFindText-Completed"); - taskCompletionSource.SetResult(text.ToString()); + taskCompletionSource.SetResult(text.GetString()); }); BridgeConnector.Socket.Emit("clipboard-readFindText"); @@ -217,11 +216,11 @@ public Task AvailableFormatsAsync(string type = "") { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("clipboard-availableFormats-Completed", (formats) => + BridgeConnector.Socket.On("clipboard-availableFormats-Completed", (formats) => { BridgeConnector.Socket.Off("clipboard-availableFormats-Completed"); - taskCompletionSource.SetResult(((JArray)formats).ToObject()); + taskCompletionSource.SetResult(JsonSerializer.Deserialize(formats, ElectronJson.Options)); }); BridgeConnector.Socket.Emit("clipboard-availableFormats", type); @@ -236,7 +235,7 @@ public Task AvailableFormatsAsync(string type = "") /// public void Write(Data data, string type = "") { - BridgeConnector.Socket.Emit("clipboard-write", JObject.FromObject(data, _jsonSerializer), type); + BridgeConnector.Socket.Emit("clipboard-write", data, type); } /// @@ -248,11 +247,11 @@ public Task ReadImageAsync(string type = "") { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("clipboard-readImage-Completed", (image) => + BridgeConnector.Socket.On("clipboard-readImage-Completed", (image) => { BridgeConnector.Socket.Off("clipboard-readImage-Completed"); - var nativeImage = ((JObject)image).ToObject(); + var nativeImage = image.Deserialize(ElectronJson.Options); taskCompletionSource.SetResult(nativeImage); }); @@ -269,14 +268,7 @@ public Task ReadImageAsync(string type = "") /// public void WriteImage(NativeImage image, string type = "") { - BridgeConnector.Socket.Emit("clipboard-writeImage", JsonConvert.SerializeObject(image), type); + BridgeConnector.Socket.Emit("clipboard-writeImage", JsonSerializer.Serialize(image, ElectronJson.Options), type); } - - private JsonSerializer _jsonSerializer = new JsonSerializer() - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - NullValueHandling = NullValueHandling.Ignore, - DefaultValueHandling = DefaultValueHandling.Ignore - }; } -} \ No newline at end of file +} diff --git a/src/ElectronNET.API/API/CommandLine.cs b/src/ElectronNET.API/API/CommandLine.cs index 184a3453..370df147 100644 --- a/src/ElectronNET.API/API/CommandLine.cs +++ b/src/ElectronNET.API/API/CommandLine.cs @@ -1,4 +1,5 @@ -using System.Threading; +using System.Text.Json; +using System.Threading; using System.Threading.Tasks; namespace ElectronNET.API @@ -75,10 +76,10 @@ public void AppendArgument(string value) var taskCompletionSource = new TaskCompletionSource(); using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled())) { - BridgeConnector.Socket.On("appCommandLineHasSwitchCompleted", (result) => + BridgeConnector.Socket.On("appCommandLineHasSwitchCompleted", (result) => { BridgeConnector.Socket.Off("appCommandLineHasSwitchCompleted"); - taskCompletionSource.SetResult((bool)result); + taskCompletionSource.SetResult(result.GetBoolean()); }); BridgeConnector.Socket.Emit("appCommandLineHasSwitch", switchName); @@ -103,10 +104,10 @@ public void AppendArgument(string value) var taskCompletionSource = new TaskCompletionSource(); using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled())) { - BridgeConnector.Socket.On("appCommandLineGetSwitchValueCompleted", (result) => + BridgeConnector.Socket.On("appCommandLineGetSwitchValueCompleted", (result) => { BridgeConnector.Socket.Off("appCommandLineGetSwitchValueCompleted"); - taskCompletionSource.SetResult((string)result); + taskCompletionSource.SetResult(result.GetString()); }); BridgeConnector.Socket.Emit("appCommandLineGetSwitchValue", switchName); diff --git a/src/ElectronNET.API/API/Cookies.cs b/src/ElectronNET.API/API/Cookies.cs index 9e35c0f2..6e9b3556 100644 --- a/src/ElectronNET.API/API/Cookies.cs +++ b/src/ElectronNET.API/API/Cookies.cs @@ -1,9 +1,5 @@ -using System; -using System.Threading.Tasks; using ElectronNET.API.Entities; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; +using System; namespace ElectronNET.API { @@ -34,11 +30,15 @@ public event Action OnChanged { if (_changed == null) { - BridgeConnector.Socket.On("webContents-session-cookies-changed" + Id, (args) => + BridgeConnector.Socket.On("webContents-session-cookies-changed" + Id, (args) => { - Cookie cookie = ((JArray)args)[0].ToObject(); - CookieChangedCause cause = ((JArray)args)[1].ToObject(); - bool removed = ((JArray)args)[2].ToObject(); + var e = args.EnumerateArray().GetEnumerator(); + e.MoveNext(); + var cookie = System.Text.Json.JsonSerializer.Deserialize(e.Current, Serialization.ElectronJson.Options); + e.MoveNext(); + var cause = System.Text.Json.JsonSerializer.Deserialize(e.Current, Serialization.ElectronJson.Options); + e.MoveNext(); + var removed = e.Current.GetBoolean(); _changed(cookie, cause, removed); }); @@ -58,11 +58,6 @@ public event Action OnChanged private event Action _changed; - private JsonSerializer _jsonSerializer = new JsonSerializer() - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - NullValueHandling = NullValueHandling.Ignore, - DefaultValueHandling = DefaultValueHandling.Ignore - }; + } -} \ No newline at end of file +} diff --git a/src/ElectronNET.API/API/Dialog.cs b/src/ElectronNET.API/API/Dialog.cs index a8085e0f..3296ded2 100644 --- a/src/ElectronNET.API/API/Dialog.cs +++ b/src/ElectronNET.API/API/Dialog.cs @@ -1,9 +1,6 @@ -using ElectronNET.API.Entities; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; +using ElectronNET.API.Entities; using System; -using System.Collections.Generic; +using System.Text.Json; using System.Threading.Tasks; namespace ElectronNET.API @@ -52,18 +49,17 @@ public Task ShowOpenDialogAsync(BrowserWindow browserWindow, OpenDialo var taskCompletionSource = new TaskCompletionSource(); var guid = Guid.NewGuid().ToString(); - BridgeConnector.Socket.On("showOpenDialogComplete" + guid, (filePaths) => + BridgeConnector.Socket.On("showOpenDialogComplete" + guid, (filePaths) => { BridgeConnector.Socket.Off("showOpenDialogComplete" + guid); - - var result = ((JArray)filePaths).ToObject(); + var result = JsonSerializer.Deserialize(filePaths, Serialization.ElectronJson.Options); taskCompletionSource.SetResult(result); }); BridgeConnector.Socket.Emit("showOpenDialog", - JObject.FromObject(browserWindow, _jsonSerializer), - JObject.FromObject(options, _jsonSerializer), guid); + browserWindow, + options, guid); return taskCompletionSource.Task; } @@ -79,16 +75,16 @@ public Task ShowSaveDialogAsync(BrowserWindow browserWindow, SaveDialogO var taskCompletionSource = new TaskCompletionSource(); var guid = Guid.NewGuid().ToString(); - BridgeConnector.Socket.On("showSaveDialogComplete" + guid, (filename) => + BridgeConnector.Socket.On("showSaveDialogComplete" + guid, (filename) => { BridgeConnector.Socket.Off("showSaveDialogComplete" + guid); - taskCompletionSource.SetResult(filename.ToString()); + taskCompletionSource.SetResult(filename.GetString()); }); BridgeConnector.Socket.Emit("showSaveDialog", - JObject.FromObject(browserWindow, _jsonSerializer), - JObject.FromObject(options, _jsonSerializer), + browserWindow, + options, guid); return taskCompletionSource.Task; @@ -148,28 +144,34 @@ public Task ShowMessageBoxAsync(BrowserWindow browserWindow, M var taskCompletionSource = new TaskCompletionSource(); var guid = Guid.NewGuid().ToString(); - BridgeConnector.Socket.On("showMessageBoxComplete" + guid, (args) => + BridgeConnector.Socket.On("showMessageBoxComplete" + guid, (args) => { BridgeConnector.Socket.Off("showMessageBoxComplete" + guid); - var result = ((JArray)args); + // args is [response:int, checkboxChecked:boolean] + var arr = args.EnumerateArray(); + var e = arr.GetEnumerator(); + e.MoveNext(); + var response = e.Current.GetInt32(); + e.MoveNext(); + var checkbox = e.Current.GetBoolean(); taskCompletionSource.SetResult(new MessageBoxResult { - Response = (int)result.First, - CheckboxChecked = (bool)result.Last + Response = response, + CheckboxChecked = checkbox }); }); if (browserWindow == null) { - BridgeConnector.Socket.Emit("showMessageBox", JObject.FromObject(messageBoxOptions, _jsonSerializer), guid); + BridgeConnector.Socket.Emit("showMessageBox", messageBoxOptions, guid); } else { BridgeConnector.Socket.Emit("showMessageBox", - JObject.FromObject(browserWindow, _jsonSerializer), - JObject.FromObject(messageBoxOptions, _jsonSerializer), + browserWindow, + messageBoxOptions, guid); } @@ -223,18 +225,13 @@ public Task ShowCertificateTrustDialogAsync(BrowserWindow browserWindow, Certifi }); BridgeConnector.Socket.Emit("showCertificateTrustDialog", - JObject.FromObject(browserWindow, _jsonSerializer), - JObject.FromObject(options, _jsonSerializer), + browserWindow, + options, guid); return taskCompletionSource.Task; } - private JsonSerializer _jsonSerializer = new JsonSerializer() - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - NullValueHandling = NullValueHandling.Ignore, - DefaultValueHandling = DefaultValueHandling.Ignore - }; + } -} \ No newline at end of file +} diff --git a/src/ElectronNET.API/API/Dock.cs b/src/ElectronNET.API/API/Dock.cs index caf018ec..c9816c3b 100644 --- a/src/ElectronNET.API/API/Dock.cs +++ b/src/ElectronNET.API/API/Dock.cs @@ -1,11 +1,9 @@ +using ElectronNET.API.Entities; +using ElectronNET.API.Extensions; using System.Collections.Generic; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; -using ElectronNET.API.Entities; -using ElectronNET.API.Extensions; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; namespace ElectronNET.API { @@ -57,10 +55,10 @@ public async Task BounceAsync(DockBounceType type, CancellationToken cancel var taskCompletionSource = new TaskCompletionSource(); using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled())) { - BridgeConnector.Socket.On("dock-bounce-completed", (id) => + BridgeConnector.Socket.On("dock-bounce-completed", (id) => { BridgeConnector.Socket.Off("dock-bounce-completed"); - taskCompletionSource.SetResult((int)id); + taskCompletionSource.SetResult(id.GetInt32()); }); BridgeConnector.Socket.Emit("dock-bounce", type.GetDescription()); @@ -109,10 +107,10 @@ public async Task GetBadgeAsync(CancellationToken cancellationToken = de var taskCompletionSource = new TaskCompletionSource(); using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled())) { - BridgeConnector.Socket.On("dock-getBadge-completed", (text) => + BridgeConnector.Socket.On("dock-getBadge-completed", (text) => { BridgeConnector.Socket.Off("dock-getBadge-completed"); - taskCompletionSource.SetResult((string)text); + taskCompletionSource.SetResult(text.GetString()); }); BridgeConnector.Socket.Emit("dock-getBadge"); @@ -151,10 +149,10 @@ public async Task IsVisibleAsync(CancellationToken cancellationToken = def var taskCompletionSource = new TaskCompletionSource(); using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled())) { - BridgeConnector.Socket.On("dock-isVisible-completed", (isVisible) => + BridgeConnector.Socket.On("dock-isVisible-completed", (isVisible) => { BridgeConnector.Socket.Off("dock-isVisible-completed"); - taskCompletionSource.SetResult((bool)isVisible); + taskCompletionSource.SetResult(isVisible.GetBoolean()); }); BridgeConnector.Socket.Emit("dock-isVisible"); @@ -186,13 +184,13 @@ public IReadOnlyCollection MenuItems public void SetMenu(MenuItem[] menuItems) { menuItems.AddMenuItemsId(); - BridgeConnector.Socket.Emit("dock-setMenu", JArray.FromObject(menuItems, _jsonSerializer)); + BridgeConnector.Socket.Emit("dock-setMenu", menuItems); _items.AddRange(menuItems); BridgeConnector.Socket.Off("dockMenuItemClicked"); - BridgeConnector.Socket.On("dockMenuItemClicked", (id) => + BridgeConnector.Socket.On("dockMenuItemClicked", (id) => { - MenuItem menuItem = _items.GetMenuItem(id.ToString()); + MenuItem menuItem = _items.GetMenuItem(id.GetString()); menuItem?.Click(); }); } @@ -208,10 +206,10 @@ public async Task GetMenu(CancellationToken cancellationToken = default) var taskCompletionSource = new TaskCompletionSource(); using (cancellationToken.Register(() => taskCompletionSource.TrySetCanceled())) { - BridgeConnector.Socket.On("dock-getMenu-completed", (menu) => + BridgeConnector.Socket.On("dock-getMenu-completed", (menu) => { BridgeConnector.Socket.Off("dock-getMenu-completed"); - taskCompletionSource.SetResult(((JObject)menu).ToObject()); + taskCompletionSource.SetResult(JsonSerializer.Deserialize(menu, Serialization.ElectronJson.Options)); }); BridgeConnector.Socket.Emit("dock-getMenu"); @@ -230,10 +228,6 @@ public void SetIcon(string image) BridgeConnector.Socket.Emit("dock-setIcon", image); } - private JsonSerializer _jsonSerializer = new JsonSerializer() - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - NullValueHandling = NullValueHandling.Ignore - }; + } -} \ No newline at end of file +} diff --git a/src/ElectronNET.API/API/Entities/BlockMapDataHolder.cs b/src/ElectronNET.API/API/Entities/BlockMapDataHolder.cs index 9294ac0a..24b45f60 100644 --- a/src/ElectronNET.API/API/Entities/BlockMapDataHolder.cs +++ b/src/ElectronNET.API/API/Entities/BlockMapDataHolder.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace ElectronNET.API.Entities +namespace ElectronNET.API.Entities { /// /// diff --git a/src/ElectronNET.API/API/Entities/BrowserWindowOptions.cs b/src/ElectronNET.API/API/Entities/BrowserWindowOptions.cs index 2b7427bd..140e9e7f 100644 --- a/src/ElectronNET.API/API/Entities/BrowserWindowOptions.cs +++ b/src/ElectronNET.API/API/Entities/BrowserWindowOptions.cs @@ -1,7 +1,7 @@ -using ElectronNET.Converter; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; +using ElectronNET.Converter; + using System.ComponentModel; +using System.Text.Json.Serialization; namespace ElectronNET.API.Entities { @@ -213,7 +213,7 @@ public class BrowserWindowOptions /// The style of window title bar. Default is default. Possible values are: /// 'default' | 'hidden' | 'hiddenInset' | 'customButtonsOnHover' /// - [JsonConverter(typeof(StringEnumConverter))] + [JsonConverter(typeof(JsonStringEnumConverter))] public TitleBarStyle TitleBarStyle { get; set; } /// @@ -256,7 +256,7 @@ public class BrowserWindowOptions /// appearance-based, light, dark, titlebar, selection, menu, popover, sidebar, /// medium-light or ultra-dark. /// - [JsonConverter(typeof(StringEnumConverter))] + [JsonConverter(typeof(JsonStringEnumConverter))] public Vibrancy Vibrancy { get; set; } /// @@ -294,3 +294,7 @@ public class BrowserWindowOptions public string ProxyCredentials { get; set; } } } + + + + diff --git a/src/ElectronNET.API/API/Entities/CPUUsage.cs b/src/ElectronNET.API/API/Entities/CPUUsage.cs index 7225cae0..f9b73261 100644 --- a/src/ElectronNET.API/API/Entities/CPUUsage.cs +++ b/src/ElectronNET.API/API/Entities/CPUUsage.cs @@ -8,7 +8,7 @@ public class CPUUsage /// /// Percentage of CPU used since the last call to getCPUUsage. First call returns 0. /// - public int PercentCPUUsage { get; set; } + public double PercentCPUUsage { get; set; } /// /// The number of average idle cpu wakeups per second since the last call to diff --git a/src/ElectronNET.API/API/Entities/ChromeExtensionInfo.cs b/src/ElectronNET.API/API/Entities/ChromeExtensionInfo.cs index 8ceb9868..52bc2dc4 100644 --- a/src/ElectronNET.API/API/Entities/ChromeExtensionInfo.cs +++ b/src/ElectronNET.API/API/Entities/ChromeExtensionInfo.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace ElectronNET.API.Entities +namespace ElectronNET.API.Entities { /// /// Provide metadata about the current loaded Chrome extension diff --git a/src/ElectronNET.API/API/Entities/CookieChangedCause.cs b/src/ElectronNET.API/API/Entities/CookieChangedCause.cs index 32b81271..472e9386 100644 --- a/src/ElectronNET.API/API/Entities/CookieChangedCause.cs +++ b/src/ElectronNET.API/API/Entities/CookieChangedCause.cs @@ -1,18 +1,18 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; + +using System.Text.Json.Serialization; namespace ElectronNET.API.Entities { /// /// The cause of the change /// - [JsonConverter(typeof(StringEnumConverter))] + [JsonConverter(typeof(JsonStringEnumConverter))] public enum CookieChangedCause { /// ///The cookie was changed directly by a consumer's action. /// - [JsonProperty("explicit")] + [JsonPropertyName("explicit")] @explicit, /// @@ -33,7 +33,7 @@ public enum CookieChangedCause /// /// The cookie was overwritten with an already-expired expiration date. /// - [JsonProperty("expired_overwrite")] + [JsonPropertyName("expired_overwrite")] expiredOverwrite } -} \ No newline at end of file +} diff --git a/src/ElectronNET.API/API/Entities/CookieFilter.cs b/src/ElectronNET.API/API/Entities/CookieFilter.cs index 67e8acb2..ee5a51e4 100644 --- a/src/ElectronNET.API/API/Entities/CookieFilter.cs +++ b/src/ElectronNET.API/API/Entities/CookieFilter.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace ElectronNET.API.Entities +namespace ElectronNET.API.Entities { /// /// diff --git a/src/ElectronNET.API/API/Entities/Display.cs b/src/ElectronNET.API/API/Entities/Display.cs index 7b35a95f..d574099c 100644 --- a/src/ElectronNET.API/API/Entities/Display.cs +++ b/src/ElectronNET.API/API/Entities/Display.cs @@ -41,7 +41,7 @@ public class Display /// /// Unique identifier associated with the display. /// - public string Id { get; set; } + public long Id { get; set; } /// /// true for an internal display and false for an external display. diff --git a/src/ElectronNET.API/API/Entities/Extension.cs b/src/ElectronNET.API/API/Entities/Extension.cs index bc458766..6bd8cbe1 100644 --- a/src/ElectronNET.API/API/Entities/Extension.cs +++ b/src/ElectronNET.API/API/Entities/Extension.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ElectronNET.API.Entities +namespace ElectronNET.API.Entities { /// /// Docs: https://electronjs.org/docs/api/structures/extension diff --git a/src/ElectronNET.API/API/Entities/GPUFeatureStatus.cs b/src/ElectronNET.API/API/Entities/GPUFeatureStatus.cs index 1681c4a8..1a49de9b 100644 --- a/src/ElectronNET.API/API/Entities/GPUFeatureStatus.cs +++ b/src/ElectronNET.API/API/Entities/GPUFeatureStatus.cs @@ -1,4 +1,5 @@ -using Newtonsoft.Json; + +using System.Text.Json.Serialization; namespace ElectronNET.API.Entities { @@ -10,43 +11,43 @@ public class GPUFeatureStatus /// /// Canvas. /// - [JsonProperty("2d_canvas")] + [JsonPropertyName("2d_canvas")] public string Canvas { get; set; } /// /// Flash. /// - [JsonProperty("flash_3d")] + [JsonPropertyName("flash_3d")] public string Flash3D { get; set; } /// /// Flash Stage3D. /// - [JsonProperty("flash_stage3d")] + [JsonPropertyName("flash_stage3d")] public string FlashStage3D { get; set; } /// /// Flash Stage3D Baseline profile. /// - [JsonProperty("flash_stage3d_baseline")] + [JsonPropertyName("flash_stage3d_baseline")] public string FlashStage3dBaseline { get; set; } /// /// Compositing. /// - [JsonProperty("gpu_compositing")] + [JsonPropertyName("gpu_compositing")] public string GpuCompositing { get; set; } /// /// Multiple Raster Threads. /// - [JsonProperty("multiple_raster_threads")] + [JsonPropertyName("multiple_raster_threads")] public string MultipleRasterThreads { get; set; } /// /// Native GpuMemoryBuffers. /// - [JsonProperty("native_gpu_memory_buffers")] + [JsonPropertyName("native_gpu_memory_buffers")] public string NativeGpuMemoryBuffers { get; set; } /// @@ -57,19 +58,19 @@ public class GPUFeatureStatus /// /// Video Decode. /// - [JsonProperty("video_decode")] + [JsonPropertyName("video_decode")] public string VideoDecode { get; set; } /// /// Video Encode. /// - [JsonProperty("video_encode")] + [JsonPropertyName("video_encode")] public string VideoEncode { get; set; } /// /// VPx Video Decode. /// - [JsonProperty("vpx_decode")] + [JsonPropertyName("vpx_decode")] public string VpxDecode { get; set; } /// diff --git a/src/ElectronNET.API/API/Entities/InputEvent.cs b/src/ElectronNET.API/API/Entities/InputEvent.cs index aa385429..a3055afe 100644 --- a/src/ElectronNET.API/API/Entities/InputEvent.cs +++ b/src/ElectronNET.API/API/Entities/InputEvent.cs @@ -1,10 +1,9 @@ -using Newtonsoft.Json.Converters; using System.Collections.Generic; -using Newtonsoft.Json; namespace ElectronNET.API.Entities { using ElectronNET.Converter; + using System.Text.Json.Serialization; /// /// @@ -76,7 +75,9 @@ public class InputEvent /// `touchScrollStarted`, `pointerDown`, `pointerUp`, `pointerMove`, /// `pointerRawUpdate`, `pointerCancel` or `pointerCausedUaAction`. /// - [JsonConverter(typeof(StringEnumConverter))] + [JsonConverter(typeof(JsonStringEnumConverter))] public InputEventType Type { get; set; } } } + + diff --git a/src/ElectronNET.API/API/Entities/JsonPropertyAttribute.cs b/src/ElectronNET.API/API/Entities/JsonPropertyAttribute.cs new file mode 100644 index 00000000..62dfbec4 --- /dev/null +++ b/src/ElectronNET.API/API/Entities/JsonPropertyAttribute.cs @@ -0,0 +1,8 @@ +using System; + +namespace ElectronNET.API.Entities +{ + internal class JsonPropertyAttribute : Attribute + { + } +} \ No newline at end of file diff --git a/src/ElectronNET.API/API/Entities/JumpListCategory.cs b/src/ElectronNET.API/API/Entities/JumpListCategory.cs index 4c1bf92c..6a3ca4fd 100644 --- a/src/ElectronNET.API/API/Entities/JumpListCategory.cs +++ b/src/ElectronNET.API/API/Entities/JumpListCategory.cs @@ -1,5 +1,5 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; + +using System.Text.Json.Serialization; namespace ElectronNET.API.Entities { @@ -21,7 +21,8 @@ public class JumpListCategory /// /// One of the following: "tasks" | "frequent" | "recent" | "custom" /// - [JsonConverter(typeof(StringEnumConverter))] + [JsonConverter(typeof(JsonStringEnumConverter))] public JumpListCategoryType Type { get; set; } } -} \ No newline at end of file +} + diff --git a/src/ElectronNET.API/API/Entities/JumpListItem.cs b/src/ElectronNET.API/API/Entities/JumpListItem.cs index 0341c8a4..9efa03e1 100644 --- a/src/ElectronNET.API/API/Entities/JumpListItem.cs +++ b/src/ElectronNET.API/API/Entities/JumpListItem.cs @@ -1,5 +1,5 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; + +using System.Text.Json.Serialization; namespace ElectronNET.API.Entities { @@ -52,7 +52,9 @@ public class JumpListItem /// /// One of the following: "task" | "separator" | "file" /// - [JsonConverter(typeof(StringEnumConverter))] + [JsonConverter(typeof(JsonStringEnumConverter))] public JumpListItemType Type { get; set; } } } + + diff --git a/src/ElectronNET.API/API/Entities/MenuItem.cs b/src/ElectronNET.API/API/Entities/MenuItem.cs index 221bd05a..b7c8fd32 100644 --- a/src/ElectronNET.API/API/Entities/MenuItem.cs +++ b/src/ElectronNET.API/API/Entities/MenuItem.cs @@ -1,7 +1,5 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; using System; -using System.ComponentModel; +using System.Text.Json.Serialization; namespace ElectronNET.API.Entities { @@ -21,13 +19,13 @@ public class MenuItem /// Define the action of the menu item, when specified the click property will be /// ignored. /// - [JsonConverter(typeof(StringEnumConverter))] + [JsonConverter(typeof(JsonStringEnumConverter))] public MenuRole Role { get; set; } /// /// Can be normal, separator, submenu, checkbox or radio. /// - [JsonConverter(typeof(StringEnumConverter))] + [JsonConverter(typeof(JsonStringEnumConverter))] public MenuType Type { get; set; } @@ -101,3 +99,5 @@ public class MenuItem public string Position { get; set; } } } + + diff --git a/src/ElectronNET.API/API/Entities/MessageBoxOptions.cs b/src/ElectronNET.API/API/Entities/MessageBoxOptions.cs index 6e93bf65..970b144a 100644 --- a/src/ElectronNET.API/API/Entities/MessageBoxOptions.cs +++ b/src/ElectronNET.API/API/Entities/MessageBoxOptions.cs @@ -1,5 +1,5 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; + +using System.Text.Json.Serialization; namespace ElectronNET.API.Entities { @@ -13,7 +13,7 @@ public class MessageBoxOptions /// displays the same icon as "info", unless you set an icon using the "icon" /// option. On macOS, both "warning" and "error" display the same warning icon. /// - [JsonConverter(typeof(StringEnumConverter))] + [JsonConverter(typeof(JsonStringEnumConverter))] public MessageBoxType Type { get; set; } /// @@ -99,3 +99,5 @@ public MessageBoxOptions(string message) } } } + + diff --git a/src/ElectronNET.API/API/Entities/NativeImage.cs b/src/ElectronNET.API/API/Entities/NativeImage.cs index 7904d246..bf087919 100644 --- a/src/ElectronNET.API/API/Entities/NativeImage.cs +++ b/src/ElectronNET.API/API/Entities/NativeImage.cs @@ -1,12 +1,12 @@ -using System; +using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; +using System.Text.Json.Serialization; using System.Text.RegularExpressions; -using Newtonsoft.Json; namespace ElectronNET.API.Entities { diff --git a/src/ElectronNET.API/API/Entities/NativeImageJsonConverter.cs b/src/ElectronNET.API/API/Entities/NativeImageJsonConverter.cs index ac564a28..d77d1fab 100644 --- a/src/ElectronNET.API/API/Entities/NativeImageJsonConverter.cs +++ b/src/ElectronNET.API/API/Entities/NativeImageJsonConverter.cs @@ -1,25 +1,29 @@ -using System; +using System; using System.Collections.Generic; using System.Drawing; using System.IO; -using Newtonsoft.Json; +using System.Text.Json; +using System.Text.Json.Serialization; namespace ElectronNET.API.Entities { - internal class NativeImageJsonConverter : JsonConverter + internal class NativeImageJsonConverter : JsonConverter { - public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + public override void Write(Utf8JsonWriter writer, NativeImage value, JsonSerializerOptions options) { - if (value is NativeImage nativeImage) + if (value is null) { - var scaledImages = nativeImage.GetAllScaledImages(); - serializer.Serialize(writer, scaledImages); + writer.WriteNullValue(); + return; } + + var scaledImages = value.GetAllScaledImages(); + JsonSerializer.Serialize(writer, scaledImages, Serialization.ElectronJson.Options); } - public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + public override NativeImage Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - var dict = serializer.Deserialize>(reader); + var dict = JsonSerializer.Deserialize>(ref reader, Serialization.ElectronJson.Options); var newDictionary = new Dictionary(); foreach (var item in dict) { @@ -29,7 +33,6 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist return new NativeImage(newDictionary); } - - public override bool CanConvert(Type objectType) => objectType == typeof(NativeImage); } -} \ No newline at end of file +} + diff --git a/src/ElectronNET.API/API/Entities/NotificationOptions.cs b/src/ElectronNET.API/API/Entities/NotificationOptions.cs index d1913798..35c9c6c4 100644 --- a/src/ElectronNET.API/API/Entities/NotificationOptions.cs +++ b/src/ElectronNET.API/API/Entities/NotificationOptions.cs @@ -1,5 +1,5 @@ -using Newtonsoft.Json; using System; +using System.Text.Json.Serialization; namespace ElectronNET.API.Entities { diff --git a/src/ElectronNET.API/API/Entities/OpenDevToolsOptions.cs b/src/ElectronNET.API/API/Entities/OpenDevToolsOptions.cs index 23a9aa70..b40859af 100644 --- a/src/ElectronNET.API/API/Entities/OpenDevToolsOptions.cs +++ b/src/ElectronNET.API/API/Entities/OpenDevToolsOptions.cs @@ -1,5 +1,5 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; + +using System.Text.Json.Serialization; namespace ElectronNET.API.Entities { @@ -13,7 +13,8 @@ public class OpenDevToolsOptions /// detach.Defaults to last used dock state.In undocked mode it's possible to dock /// back.In detach mode it's not. /// - [JsonConverter(typeof(StringEnumConverter))] + [JsonConverter(typeof(JsonStringEnumConverter))] public DevToolsMode Mode { get; set; } } -} \ No newline at end of file +} + diff --git a/src/ElectronNET.API/API/Entities/OpenDialogOptions.cs b/src/ElectronNET.API/API/Entities/OpenDialogOptions.cs index 3f18dffd..d8fec8b0 100644 --- a/src/ElectronNET.API/API/Entities/OpenDialogOptions.cs +++ b/src/ElectronNET.API/API/Entities/OpenDialogOptions.cs @@ -1,5 +1,5 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; + +using System.Text.Json.Serialization; namespace ElectronNET.API.Entities { @@ -33,7 +33,7 @@ public class OpenDialogOptions /// Contains which features the dialog should use. The following values are supported: /// 'openFile' | 'openDirectory' | 'multiSelections' | 'showHiddenFiles' | 'createDirectory' | 'promptToCreate' | 'noResolveAliases' | 'treatPackageAsDirectory' /// - [JsonProperty("properties", ItemConverterType = typeof(StringEnumConverter))] + [JsonPropertyName("properties")] public OpenDialogProperty[] Properties { get; set; } /// @@ -58,4 +58,5 @@ public class OpenDialogOptions /// public FileFilter[] Filters { get; set; } } -} \ No newline at end of file +} + diff --git a/src/ElectronNET.API/API/Entities/OpenExternalOptions.cs b/src/ElectronNET.API/API/Entities/OpenExternalOptions.cs index dba51ca4..f648cd19 100644 --- a/src/ElectronNET.API/API/Entities/OpenExternalOptions.cs +++ b/src/ElectronNET.API/API/Entities/OpenExternalOptions.cs @@ -1,5 +1,4 @@ -using System; -using System.ComponentModel; +using System.ComponentModel; namespace ElectronNET.API.Entities { diff --git a/src/ElectronNET.API/API/Entities/PrintToPDFOptions.cs b/src/ElectronNET.API/API/Entities/PrintToPDFOptions.cs index 30b7b1d4..714bca0b 100644 --- a/src/ElectronNET.API/API/Entities/PrintToPDFOptions.cs +++ b/src/ElectronNET.API/API/Entities/PrintToPDFOptions.cs @@ -1,5 +1,5 @@ -using ElectronNET.Converter; -using Newtonsoft.Json; +using ElectronNET.Converter; +using System.Text.Json.Serialization; namespace ElectronNET.API.Entities; diff --git a/src/ElectronNET.API/API/Entities/ProgressBarOptions.cs b/src/ElectronNET.API/API/Entities/ProgressBarOptions.cs index 7177a2fc..ae233ca9 100644 --- a/src/ElectronNET.API/API/Entities/ProgressBarOptions.cs +++ b/src/ElectronNET.API/API/Entities/ProgressBarOptions.cs @@ -1,5 +1,5 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; + +using System.Text.Json.Serialization; namespace ElectronNET.API.Entities { @@ -11,7 +11,8 @@ public class ProgressBarOptions /// /// Mode for the progress bar. Can be 'none' | 'normal' | 'indeterminate' | 'error' | 'paused'. /// - [JsonConverter(typeof(StringEnumConverter))] + [JsonConverter(typeof(JsonStringEnumConverter))] public ProgressBarMode Mode { get; set; } } -} \ No newline at end of file +} + diff --git a/src/ElectronNET.API/API/Entities/ProgressInfo.cs b/src/ElectronNET.API/API/Entities/ProgressInfo.cs index fe6ea3d7..75c94970 100644 --- a/src/ElectronNET.API/API/Entities/ProgressInfo.cs +++ b/src/ElectronNET.API/API/Entities/ProgressInfo.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace ElectronNET.API.Entities +namespace ElectronNET.API.Entities { /// /// diff --git a/src/ElectronNET.API/API/Entities/RemovePassword.cs b/src/ElectronNET.API/API/Entities/RemovePassword.cs index f0118e4e..38e462ef 100644 --- a/src/ElectronNET.API/API/Entities/RemovePassword.cs +++ b/src/ElectronNET.API/API/Entities/RemovePassword.cs @@ -1,5 +1,5 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; + +using System.Text.Json.Serialization; namespace ElectronNET.API.Entities { @@ -28,7 +28,7 @@ public class RemovePassword /// Scheme of the authentication. Can be basic, digest, ntlm, negotiate. /// Must be provided if removing by origin. /// - [JsonConverter(typeof(StringEnumConverter))] + [JsonConverter(typeof(JsonStringEnumConverter))] public Scheme Scheme { get; set; } /// @@ -51,3 +51,5 @@ public RemovePassword(string type) } } } + + diff --git a/src/ElectronNET.API/API/Entities/ThumbarButton.cs b/src/ElectronNET.API/API/Entities/ThumbarButton.cs index 504c26f1..ec3e9a9e 100644 --- a/src/ElectronNET.API/API/Entities/ThumbarButton.cs +++ b/src/ElectronNET.API/API/Entities/ThumbarButton.cs @@ -1,6 +1,5 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; using System; +using System.Text.Json.Serialization; namespace ElectronNET.API.Entities { @@ -36,7 +35,7 @@ public class ThumbarButton /// hidden - The button is not shown to the user. /// noninteractive - The button is enabled but not interactive; no pressed button state is drawn.This value is intended for instances where the button is used in a notification. /// - [JsonProperty("flags", ItemConverterType = typeof(StringEnumConverter))] + [JsonPropertyName("flags")] public ThumbarButtonFlag[] Flags { get; set; } /// @@ -58,4 +57,5 @@ public ThumbarButton(string icon) Icon = icon; } } -} \ No newline at end of file +} + diff --git a/src/ElectronNET.API/API/Entities/TitleBarStyle.cs b/src/ElectronNET.API/API/Entities/TitleBarStyle.cs index 8fb108ec..f28ac954 100644 --- a/src/ElectronNET.API/API/Entities/TitleBarStyle.cs +++ b/src/ElectronNET.API/API/Entities/TitleBarStyle.cs @@ -1,4 +1,5 @@ -using Newtonsoft.Json; + +using System.Text.Json.Serialization; namespace ElectronNET.API.Entities { @@ -10,7 +11,7 @@ public enum TitleBarStyle /// /// The default style /// - [JsonProperty("default")] + [JsonPropertyName("default")] defaultStyle, /// diff --git a/src/ElectronNET.API/API/GlobalShortcut.cs b/src/ElectronNET.API/API/GlobalShortcut.cs index ec20d551..9697a609 100644 --- a/src/ElectronNET.API/API/GlobalShortcut.cs +++ b/src/ElectronNET.API/API/GlobalShortcut.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Text.Json; using System.Threading.Tasks; namespace ElectronNET.API @@ -52,11 +53,11 @@ public void Register(string accelerator, Action function) _shortcuts.Add(accelerator, function); BridgeConnector.Socket.Off("globalShortcut-pressed"); - BridgeConnector.Socket.On("globalShortcut-pressed", (shortcut) => + BridgeConnector.Socket.On("globalShortcut-pressed", (shortcut) => { - if (_shortcuts.ContainsKey(shortcut.ToString())) + if (_shortcuts.TryGetValue(shortcut.GetString(), out var action)) { - _shortcuts[shortcut.ToString()](); + action(); } }); @@ -74,11 +75,11 @@ public Task IsRegisteredAsync(string accelerator) { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("globalShortcut-isRegisteredCompleted", (isRegistered) => + BridgeConnector.Socket.On("globalShortcut-isRegisteredCompleted", (isRegistered) => { BridgeConnector.Socket.Off("globalShortcut-isRegisteredCompleted"); - taskCompletionSource.SetResult((bool)isRegistered); + taskCompletionSource.SetResult(isRegistered.GetBoolean()); }); BridgeConnector.Socket.Emit("globalShortcut-isRegistered", accelerator); diff --git a/src/ElectronNET.API/API/HostHook.cs b/src/ElectronNET.API/API/HostHook.cs index 7f0dd625..7a914e41 100644 --- a/src/ElectronNET.API/API/HostHook.cs +++ b/src/ElectronNET.API/API/HostHook.cs @@ -1,7 +1,5 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; using System; +using System.Text.Json; using System.Threading.Tasks; namespace ElectronNET.API @@ -49,10 +47,10 @@ internal static HostHook Instance /// Optional parameters. public void Call(string socketEventName, params dynamic[] arguments) { - BridgeConnector.Socket.On(socketEventName + "Error" + oneCallguid, (result) => + BridgeConnector.Socket.On(socketEventName + "Error" + oneCallguid, (result) => { BridgeConnector.Socket.Off(socketEventName + "Error" + oneCallguid); - Electron.Dialog.ShowErrorBox("Host Hook Exception", result.ToString()); + Electron.Dialog.ShowErrorBox("Host Hook Exception", result.GetString()); }); BridgeConnector.Socket.Emit(socketEventName, arguments, oneCallguid); @@ -70,14 +68,14 @@ public Task CallAsync(string socketEventName, params dynamic[] arguments) var taskCompletionSource = new TaskCompletionSource(); string guid = Guid.NewGuid().ToString(); - BridgeConnector.Socket.On(socketEventName + "Error" + guid, (result) => + BridgeConnector.Socket.On(socketEventName + "Error" + guid, (result) => { BridgeConnector.Socket.Off(socketEventName + "Error" + guid); - Electron.Dialog.ShowErrorBox("Host Hook Exception", result.ToString()); + Electron.Dialog.ShowErrorBox("Host Hook Exception", result.GetString()); taskCompletionSource.SetException(new Exception($"Host Hook Exception {result}")); }); - BridgeConnector.Socket.On(socketEventName + "Complete" + guid, (result) => + BridgeConnector.Socket.On(socketEventName + "Complete" + guid, (result) => { BridgeConnector.Socket.Off(socketEventName + "Error" + guid); BridgeConnector.Socket.Off(socketEventName + "Complete" + guid); @@ -85,26 +83,7 @@ public Task CallAsync(string socketEventName, params dynamic[] arguments) try { - if (result.GetType().IsValueType || result is string) - { - data = (T)result; - } - else - { - var token = JToken.Parse(result.ToString()); - if (token is JArray) - { - data = token.ToObject(); - } - else if (token is JObject) - { - data = token.ToObject(); - } - else - { - data = (T)result; - } - } + data = result.Deserialize(Serialization.ElectronJson.Options); } catch (Exception exception) { @@ -120,11 +99,6 @@ public Task CallAsync(string socketEventName, params dynamic[] arguments) return taskCompletionSource.Task; } - private JsonSerializer _jsonSerializer = new JsonSerializer() - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - NullValueHandling = NullValueHandling.Ignore, - DefaultValueHandling = DefaultValueHandling.Ignore - }; + } -} \ No newline at end of file +} diff --git a/src/ElectronNET.API/API/IpcMain.cs b/src/ElectronNET.API/API/IpcMain.cs index c4eed197..c3e8c890 100644 --- a/src/ElectronNET.API/API/IpcMain.cs +++ b/src/ElectronNET.API/API/IpcMain.cs @@ -1,8 +1,4 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; using System; -using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; @@ -50,7 +46,7 @@ public async Task On(string channel, Action listener) { await BridgeConnector.Socket.Emit("registerIpcMainChannel", channel).ConfigureAwait(false); BridgeConnector.Socket.Off(channel); - BridgeConnector.Socket.On(channel, (args) => + BridgeConnector.Socket.On(channel, (args) => { List objectArray = FormatArguments(args); @@ -65,19 +61,10 @@ public async Task On(string channel, Action listener) }); } - private List FormatArguments(object args) + private static List FormatArguments(System.Text.Json.JsonElement args) { - List objectArray = ((JArray)args).ToObject().ToList(); - - for (int index = 0; index < objectArray.Count; index++) - { - var item = objectArray[index]; - if (item == null) - { - objectArray.Remove(item); - } - } - + var objectArray = System.Text.Json.JsonSerializer.Deserialize(args, Serialization.ElectronJson.Options).ToList(); + objectArray.RemoveAll(item => item is null); return objectArray; } @@ -93,7 +80,7 @@ private List FormatArguments(object args) public void OnSync(string channel, Func listener) { BridgeConnector.Socket.Emit("registerSyncIpcMainChannel", channel); - BridgeConnector.Socket.On(channel, (args) => + BridgeConnector.Socket.On(channel, (args) => { List objectArray = FormatArguments(args); object parameter; @@ -120,7 +107,7 @@ public void OnSync(string channel, Func listener) public void Once(string channel, Action listener) { BridgeConnector.Socket.Emit("registerOnceIpcMainChannel", channel); - BridgeConnector.Socket.Once(channel, (args) => + BridgeConnector.Socket.Once(channel, (args) => { List objectArray = FormatArguments(args); @@ -155,34 +142,7 @@ public void RemoveAllListeners(string channel) /// Arguments data. public void Send(BrowserWindow browserWindow, string channel, params object[] data) { - List jobjects = new List(); - List jarrays = new List(); - List objects = new List(); - - foreach (var parameterObject in data) - { - if (parameterObject.GetType().IsArray || parameterObject.GetType().IsGenericType && parameterObject is IEnumerable) - { - jarrays.Add(JArray.FromObject(parameterObject, _jsonSerializer)); - } - else if (parameterObject.GetType().IsClass && !parameterObject.GetType().IsPrimitive && !(parameterObject is string)) - { - jobjects.Add(JObject.FromObject(parameterObject, _jsonSerializer)); - } - else if (parameterObject.GetType().IsPrimitive || (parameterObject is string)) - { - objects.Add(parameterObject); - } - } - - if (jobjects.Count > 0 || jarrays.Count > 0) - { - BridgeConnector.Socket.Emit("sendToIpcRenderer", JObject.FromObject(browserWindow, _jsonSerializer), channel, jarrays.ToArray(), jobjects.ToArray(), objects.ToArray()); - } - else - { - BridgeConnector.Socket.Emit("sendToIpcRenderer", JObject.FromObject(browserWindow, _jsonSerializer), channel, data); - } + BridgeConnector.Socket.Emit("sendToIpcRenderer", browserWindow, channel, data); } /// @@ -196,41 +156,9 @@ public void Send(BrowserWindow browserWindow, string channel, params object[] da /// Arguments data. public void Send(BrowserView browserView, string channel, params object[] data) { - List jobjects = new List(); - List jarrays = new List(); - List objects = new List(); - - foreach (var parameterObject in data) - { - if (parameterObject.GetType().IsArray || parameterObject.GetType().IsGenericType && parameterObject is IEnumerable) - { - jarrays.Add(JArray.FromObject(parameterObject, _jsonSerializer)); - } - else if (parameterObject.GetType().IsClass && !parameterObject.GetType().IsPrimitive && !(parameterObject is string)) - { - jobjects.Add(JObject.FromObject(parameterObject, _jsonSerializer)); - } - else if (parameterObject.GetType().IsPrimitive || (parameterObject is string)) - { - objects.Add(parameterObject); - } - } - - if (jobjects.Count > 0 || jarrays.Count > 0) - { - BridgeConnector.Socket.Emit("sendToIpcRendererBrowserView", browserView.Id, channel, jarrays.ToArray(), jobjects.ToArray(), objects.ToArray()); - } - else - { - BridgeConnector.Socket.Emit("sendToIpcRendererBrowserView", browserView.Id, channel, data); - } + BridgeConnector.Socket.Emit("sendToIpcRendererBrowserView", browserView.Id, channel, data); } - private JsonSerializer _jsonSerializer = new JsonSerializer() - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - NullValueHandling = NullValueHandling.Ignore, - DefaultValueHandling = DefaultValueHandling.Ignore - }; + } -} \ No newline at end of file +} diff --git a/src/ElectronNET.API/API/Menu.cs b/src/ElectronNET.API/API/Menu.cs index bb98d501..87b3753d 100644 --- a/src/ElectronNET.API/API/Menu.cs +++ b/src/ElectronNET.API/API/Menu.cs @@ -1,11 +1,10 @@ -using ElectronNET.API.Entities; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using System.Collections.Generic; +using ElectronNET.API.Entities; using ElectronNET.API.Extensions; -using System.Linq; +using ElectronNET.API.Serialization; +using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Linq; +using System.Text.Json; namespace ElectronNET.API { @@ -67,13 +66,13 @@ public void SetApplicationMenu(MenuItem[] menuItems) menuItems.AddMenuItemsId(); menuItems.AddSubmenuTypes(); - BridgeConnector.Socket.Emit("menu-setApplicationMenu", JArray.FromObject(menuItems, _jsonSerializer)); + BridgeConnector.Socket.Emit("menu-setApplicationMenu", JsonSerializer.SerializeToNode(menuItems, ElectronJson.Options)); _menuItems.AddRange(menuItems); BridgeConnector.Socket.Off("menuItemClicked"); - BridgeConnector.Socket.On("menuItemClicked", (id) => + BridgeConnector.Socket.On("menuItemClicked", (id) => { - MenuItem menuItem = _menuItems.GetMenuItem(id.ToString()); + MenuItem menuItem = _menuItems.GetMenuItem(id.GetString()); menuItem.Click?.Invoke(); }); } @@ -98,7 +97,7 @@ public void SetContextMenu(BrowserWindow browserWindow, MenuItem[] menuItems) menuItems.AddMenuItemsId(); menuItems.AddSubmenuTypes(); - BridgeConnector.Socket.Emit("menu-setContextMenu", browserWindow.Id, JArray.FromObject(menuItems, _jsonSerializer)); + BridgeConnector.Socket.Emit("menu-setContextMenu", browserWindow.Id, menuItems); if (!_contextMenuItems.ContainsKey(browserWindow.Id)) { @@ -108,10 +107,14 @@ public void SetContextMenu(BrowserWindow browserWindow, MenuItem[] menuItems) } BridgeConnector.Socket.Off("contextMenuItemClicked"); - BridgeConnector.Socket.On("contextMenuItemClicked", (results) => + BridgeConnector.Socket.On("contextMenuItemClicked", (results) => { - var id = ((JArray)results).First.ToString(); - var browserWindowId = (int)((JArray)results).Last; + var arr = results.EnumerateArray(); + var e = arr.GetEnumerator(); + e.MoveNext(); + var id = e.Current.GetString(); + e.MoveNext(); + var browserWindowId = e.Current.GetInt32(); MenuItem menuItem = _contextMenuItems[browserWindowId].GetMenuItem(id); menuItem.Click?.Invoke(); @@ -127,10 +130,6 @@ public void ContextMenuPopup(BrowserWindow browserWindow) BridgeConnector.Socket.Emit("menu-contextMenuPopup", browserWindow.Id); } - private JsonSerializer _jsonSerializer = new JsonSerializer() - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - NullValueHandling = NullValueHandling.Ignore - }; + } -} \ No newline at end of file +} diff --git a/src/ElectronNET.API/API/NativeTheme.cs b/src/ElectronNET.API/API/NativeTheme.cs index d38abc35..e8cf5011 100644 --- a/src/ElectronNET.API/API/NativeTheme.cs +++ b/src/ElectronNET.API/API/NativeTheme.cs @@ -1,8 +1,9 @@ -using System; -using System.Threading.Tasks; -using ElectronNET.API.Entities; +using ElectronNET.API.Entities; using ElectronNET.API.Extensions; using ElectronNET.Common; +using System; +using System.Text.Json; +using System.Threading.Tasks; namespace ElectronNET.API { @@ -108,11 +109,11 @@ public Task GetThemeSourceAsync() { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("nativeTheme-themeSource-getCompleted", (themeSource) => + BridgeConnector.Socket.On("nativeTheme-themeSource-getCompleted", (themeSource) => { BridgeConnector.Socket.Off("nativeTheme-themeSource-getCompleted"); - var themeSourceValue = (ThemeSourceMode)Enum.Parse(typeof(ThemeSourceMode), (string)themeSource, true); + var themeSourceValue = (ThemeSourceMode)Enum.Parse(typeof(ThemeSourceMode), themeSource.GetString(), true); taskCompletionSource.SetResult(themeSourceValue); }); @@ -131,11 +132,11 @@ public Task ShouldUseDarkColorsAsync() { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("nativeTheme-shouldUseDarkColors-completed", (shouldUseDarkColors) => + BridgeConnector.Socket.On("nativeTheme-shouldUseDarkColors-completed", (shouldUseDarkColors) => { BridgeConnector.Socket.Off("nativeTheme-shouldUseDarkColors-completed"); - taskCompletionSource.SetResult((bool)shouldUseDarkColors); + taskCompletionSource.SetResult(shouldUseDarkColors.GetBoolean()); }); BridgeConnector.Socket.Emit("nativeTheme-shouldUseDarkColors"); @@ -151,11 +152,11 @@ public Task ShouldUseHighContrastColorsAsync() { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("nativeTheme-shouldUseHighContrastColors-completed", (shouldUseHighContrastColors) => + BridgeConnector.Socket.On("nativeTheme-shouldUseHighContrastColors-completed", (shouldUseHighContrastColors) => { BridgeConnector.Socket.Off("nativeTheme-shouldUseHighContrastColors-completed"); - taskCompletionSource.SetResult((bool)shouldUseHighContrastColors); + taskCompletionSource.SetResult(shouldUseHighContrastColors.GetBoolean()); }); BridgeConnector.Socket.Emit("nativeTheme-shouldUseHighContrastColors"); @@ -171,11 +172,11 @@ public Task ShouldUseInvertedColorSchemeAsync() { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("nativeTheme-shouldUseInvertedColorScheme-completed", (shouldUseInvertedColorScheme) => + BridgeConnector.Socket.On("nativeTheme-shouldUseInvertedColorScheme-completed", (shouldUseInvertedColorScheme) => { BridgeConnector.Socket.Off("nativeTheme-shouldUseInvertedColorScheme-completed"); - taskCompletionSource.SetResult((bool)shouldUseInvertedColorScheme); + taskCompletionSource.SetResult(shouldUseInvertedColorScheme.GetBoolean()); }); BridgeConnector.Socket.Emit("nativeTheme-shouldUseInvertedColorScheme"); diff --git a/src/ElectronNET.API/API/Notification.cs b/src/ElectronNET.API/API/Notification.cs index 1913ee29..7d405081 100644 --- a/src/ElectronNET.API/API/Notification.cs +++ b/src/ElectronNET.API/API/Notification.cs @@ -1,10 +1,8 @@ -using ElectronNET.API.Entities; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; +using ElectronNET.API.Entities; using System; using System.Collections.Generic; using System.Linq; +using System.Text.Json; using System.Threading.Tasks; namespace ElectronNET.API @@ -50,7 +48,7 @@ public void Show(NotificationOptions notificationOptions) { GenerateIDsForDefinedActions(notificationOptions); - BridgeConnector.Socket.Emit("createNotification", JObject.FromObject(notificationOptions, _jsonSerializer)); + BridgeConnector.Socket.Emit("createNotification", notificationOptions); } private static void GenerateIDsForDefinedActions(NotificationOptions notificationOptions) @@ -63,7 +61,7 @@ private static void GenerateIDsForDefinedActions(NotificationOptions notificatio isActionDefined = true; BridgeConnector.Socket.Off("NotificationEventShow"); - BridgeConnector.Socket.On("NotificationEventShow", (id) => { _notificationOptions.Single(x => x.ShowID == id.ToString()).OnShow(); }); + BridgeConnector.Socket.On("NotificationEventShow", (id) => { _notificationOptions.Single(x => x.ShowID == id.GetString()).OnShow(); }); } if (notificationOptions.OnClick != null) @@ -72,7 +70,7 @@ private static void GenerateIDsForDefinedActions(NotificationOptions notificatio isActionDefined = true; BridgeConnector.Socket.Off("NotificationEventClick"); - BridgeConnector.Socket.On("NotificationEventClick", (id) => { _notificationOptions.Single(x => x.ClickID == id.ToString()).OnClick(); }); + BridgeConnector.Socket.On("NotificationEventClick", (id) => { _notificationOptions.Single(x => x.ClickID == id.GetString()).OnClick(); }); } if (notificationOptions.OnClose != null) @@ -81,7 +79,7 @@ private static void GenerateIDsForDefinedActions(NotificationOptions notificatio isActionDefined = true; BridgeConnector.Socket.Off("NotificationEventClose"); - BridgeConnector.Socket.On("NotificationEventClose", (id) => { _notificationOptions.Single(x => x.CloseID == id.ToString()).OnClose(); }); + BridgeConnector.Socket.On("NotificationEventClose", (id) => { _notificationOptions.Single(x => x.CloseID == id.GetString()).OnClose(); }); } if (notificationOptions.OnReply != null) @@ -90,10 +88,10 @@ private static void GenerateIDsForDefinedActions(NotificationOptions notificatio isActionDefined = true; BridgeConnector.Socket.Off("NotificationEventReply"); - BridgeConnector.Socket.On("NotificationEventReply", (args) => + BridgeConnector.Socket.On("NotificationEventReply", (args) => { - var arguments = ((JArray)args).ToObject(); - _notificationOptions.Single(x => x.ReplyID == arguments[0].ToString()).OnReply(arguments[1].ToString()); + var arguments = args.Deserialize(Serialization.ElectronJson.Options); + _notificationOptions.Single(x => x.ReplyID == arguments[0]).OnReply(arguments[1]); }); } @@ -103,10 +101,10 @@ private static void GenerateIDsForDefinedActions(NotificationOptions notificatio isActionDefined = true; BridgeConnector.Socket.Off("NotificationEventAction"); - BridgeConnector.Socket.On("NotificationEventAction", (args) => + BridgeConnector.Socket.On("NotificationEventAction", (args) => { - var arguments = ((JArray)args).ToObject(); - _notificationOptions.Single(x => x.ReplyID == arguments[0].ToString()).OnAction(arguments[1].ToString()); + var arguments = JsonSerializer.Deserialize(args, Serialization.ElectronJson.Options); + _notificationOptions.Single(x => x.ReplyID == arguments[0]).OnAction(arguments[1]); }); } @@ -124,10 +122,10 @@ public Task IsSupportedAsync() { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("notificationIsSupportedComplete", (isSupported) => + BridgeConnector.Socket.On("notificationIsSupportedComplete", (isSupported) => { BridgeConnector.Socket.Off("notificationIsSupportedComplete"); - taskCompletionSource.SetResult((bool)isSupported); + taskCompletionSource.SetResult(isSupported.GetBoolean()); }); BridgeConnector.Socket.Emit("notificationIsSupported"); @@ -135,11 +133,6 @@ public Task IsSupportedAsync() return taskCompletionSource.Task; } - private JsonSerializer _jsonSerializer = new JsonSerializer() - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - NullValueHandling = NullValueHandling.Ignore, - DefaultValueHandling = DefaultValueHandling.Ignore - }; + } -} \ No newline at end of file +} diff --git a/src/ElectronNET.API/API/PowerMonitor.cs b/src/ElectronNET.API/API/PowerMonitor.cs index 36556c58..aefefee6 100644 --- a/src/ElectronNET.API/API/PowerMonitor.cs +++ b/src/ElectronNET.API/API/PowerMonitor.cs @@ -1,6 +1,5 @@ -using System; -using System.Threading.Tasks; -using ElectronNET.Common; +using ElectronNET.Common; +using System; // ReSharper disable InconsistentNaming diff --git a/src/ElectronNET.API/API/Process.cs b/src/ElectronNET.API/API/Process.cs index 0be0181d..47828627 100644 --- a/src/ElectronNET.API/API/Process.cs +++ b/src/ElectronNET.API/API/Process.cs @@ -1,8 +1,6 @@ -using System.Threading; -using System.Threading.Tasks; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; using ElectronNET.API.Entities; +using System.Text.Json; +using System.Threading.Tasks; namespace ElectronNET.API { @@ -49,10 +47,10 @@ public Task ExecPathAsync { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("process-execPath-Completed", (result) => + BridgeConnector.Socket.On("process-execPath-Completed", (result) => { BridgeConnector.Socket.Off("process-execPath-Completed"); - taskCompletionSource.SetResult(result.ToString()); + taskCompletionSource.SetResult(result.GetString()); }); BridgeConnector.Socket.Emit("process-execPath"); @@ -73,10 +71,10 @@ public Task ArgvAsync { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("process-argv-Completed", (result) => + BridgeConnector.Socket.On("process-argv-Completed", (result) => { BridgeConnector.Socket.Off("process-argv-Completed"); - taskCompletionSource.SetResult(((JArray)result).ToObject()); + taskCompletionSource.SetResult(JsonSerializer.Deserialize(result, Serialization.ElectronJson.Options)); }); BridgeConnector.Socket.Emit("process-argv"); @@ -94,10 +92,10 @@ public Task TypeAsync { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("process-type-Completed", (result) => + BridgeConnector.Socket.On("process-type-Completed", (result) => { BridgeConnector.Socket.Off("process-type-Completed"); - taskCompletionSource.SetResult(result.ToString()); + taskCompletionSource.SetResult(result.GetString()); }); BridgeConnector.Socket.Emit("process-type"); @@ -116,10 +114,10 @@ public Task VersionsAsync { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("process-versions-Completed", (result) => + BridgeConnector.Socket.On("process-versions-Completed", (result) => { BridgeConnector.Socket.Off("process-versions-Completed"); - taskCompletionSource.SetResult(((JObject)result).ToObject()); + taskCompletionSource.SetResult(JsonSerializer.Deserialize(result, Serialization.ElectronJson.Options)); }); BridgeConnector.Socket.Emit("process-versions"); @@ -138,10 +136,10 @@ public Task DefaultAppAsync { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("process-defaultApp-Completed", (result) => + BridgeConnector.Socket.On("process-defaultApp-Completed", (result) => { BridgeConnector.Socket.Off("process-defaultApp-Completed"); - taskCompletionSource.SetResult(bool.Parse(result.ToString())); + taskCompletionSource.SetResult(result.GetBoolean()); }); BridgeConnector.Socket.Emit("process-defaultApp"); @@ -159,10 +157,10 @@ public Task IsMainFrameAsync { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("process-isMainFrame-Completed", (result) => + BridgeConnector.Socket.On("process-isMainFrame-Completed", (result) => { BridgeConnector.Socket.Off("process-isMainFrame-Completed"); - taskCompletionSource.SetResult(bool.Parse(result.ToString())); + taskCompletionSource.SetResult(result.GetBoolean()); }); BridgeConnector.Socket.Emit("process-isMainFrame"); @@ -179,10 +177,10 @@ public Task ResourcesPathAsync { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("process-resourcesPath-Completed", (result) => + BridgeConnector.Socket.On("process-resourcesPath-Completed", (result) => { BridgeConnector.Socket.Off("process-resourcesPath-Completed"); - taskCompletionSource.SetResult(result.ToString()); + taskCompletionSource.SetResult(result.GetString()); }); BridgeConnector.Socket.Emit("process-resourcesPath"); @@ -200,10 +198,10 @@ public Task UpTimeAsync { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("process-uptime-Completed", (result) => + BridgeConnector.Socket.On("process-uptime-Completed", (result) => { BridgeConnector.Socket.Off("process-uptime-Completed"); - taskCompletionSource.SetResult(double.Parse(result.ToString())); + taskCompletionSource.SetResult(result.GetDouble()); }); BridgeConnector.Socket.Emit("process-uptime"); @@ -220,10 +218,10 @@ public Task PidAsync { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("process-pid-Completed", (result) => + BridgeConnector.Socket.On("process-pid-Completed", (result) => { BridgeConnector.Socket.Off("process-pid-Completed"); - taskCompletionSource.SetResult(int.Parse(result.ToString())); + taskCompletionSource.SetResult(result.GetInt32()); }); BridgeConnector.Socket.Emit("process-pid"); @@ -241,10 +239,10 @@ public Task ArchAsync { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("process-arch-Completed", (result) => + BridgeConnector.Socket.On("process-arch-Completed", (result) => { BridgeConnector.Socket.Off("process-arch-Completed"); - taskCompletionSource.SetResult(result.ToString()); + taskCompletionSource.SetResult(result.GetString()); }); BridgeConnector.Socket.Emit("process-arch"); @@ -261,10 +259,10 @@ public Task PlatformAsync { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("process-platform-Completed", (result) => + BridgeConnector.Socket.On("process-platform-Completed", (result) => { BridgeConnector.Socket.Off("process-platform-Completed"); - taskCompletionSource.SetResult(result.ToString()); + taskCompletionSource.SetResult(result.GetString()); }); BridgeConnector.Socket.Emit("process-platform"); @@ -272,4 +270,4 @@ public Task PlatformAsync } } } -} \ No newline at end of file +} diff --git a/src/ElectronNET.API/API/Screen.cs b/src/ElectronNET.API/API/Screen.cs index fd94372b..7638961b 100644 --- a/src/ElectronNET.API/API/Screen.cs +++ b/src/ElectronNET.API/API/Screen.cs @@ -1,10 +1,9 @@ -using ElectronNET.API.Entities; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; +using ElectronNET.API.Entities; +using ElectronNET.API.Serialization; +using ElectronNET.Common; using System; +using System.Text.Json; using System.Threading.Tasks; -using ElectronNET.Common; namespace ElectronNET.API { @@ -18,7 +17,7 @@ public sealed class Screen /// public event Action OnDisplayAdded { - add => ApiEventManager.AddEvent("screen-display-added", GetHashCode(), _onDisplayAdded, value, (args) => ((JObject)args).ToObject()); + add => ApiEventManager.AddEvent("screen-display-added", GetHashCode(), _onDisplayAdded, value, (args) => JsonSerializer.Deserialize(args, Serialization.ElectronJsonContext.Default.Display)); remove => ApiEventManager.RemoveEvent("screen-display-added", GetHashCode(), _onDisplayAdded, value); } @@ -29,7 +28,7 @@ public event Action OnDisplayAdded /// public event Action OnDisplayRemoved { - add => ApiEventManager.AddEvent("screen-display-removed", GetHashCode(), _onDisplayRemoved, value, (args) => ((JObject)args).ToObject()); + add => ApiEventManager.AddEvent("screen-display-removed", GetHashCode(), _onDisplayRemoved, value, (args) => JsonSerializer.Deserialize(args, Serialization.ElectronJsonContext.Default.Display)); remove => ApiEventManager.RemoveEvent("screen-display-removed", GetHashCode(), _onDisplayRemoved, value); } @@ -82,11 +81,11 @@ public Task GetCursorScreenPointAsync() { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("screen-getCursorScreenPointCompleted", (point) => + BridgeConnector.Socket.On("screen-getCursorScreenPointCompleted", (point) => { BridgeConnector.Socket.Off("screen-getCursorScreenPointCompleted"); - taskCompletionSource.SetResult(((JObject)point).ToObject()); + taskCompletionSource.SetResult(JsonSerializer.Deserialize(point, Serialization.ElectronJson.Options)); }); BridgeConnector.Socket.Emit("screen-getCursorScreenPoint"); @@ -102,11 +101,11 @@ public Task GetMenuBarHeightAsync() { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("screen-getMenuBarHeightCompleted", (height) => + BridgeConnector.Socket.On("screen-getMenuBarHeightCompleted", (height) => { BridgeConnector.Socket.Off("screen-getMenuBarHeightCompleted"); - taskCompletionSource.SetResult(int.Parse(height.ToString())); + taskCompletionSource.SetResult(height.GetInt32()); }); BridgeConnector.Socket.Emit("screen-getMenuBarHeight"); @@ -122,11 +121,11 @@ public Task GetPrimaryDisplayAsync() { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("screen-getPrimaryDisplayCompleted", (display) => + BridgeConnector.Socket.On("screen-getPrimaryDisplayCompleted", (display) => { BridgeConnector.Socket.Off("screen-getPrimaryDisplayCompleted"); - taskCompletionSource.SetResult(((JObject)display).ToObject()); + taskCompletionSource.SetResult(display.Deserialize(ElectronJsonContext.Default.Display)); }); BridgeConnector.Socket.Emit("screen-getPrimaryDisplay"); @@ -142,11 +141,11 @@ public Task GetAllDisplaysAsync() { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("screen-getAllDisplaysCompleted", (displays) => + BridgeConnector.Socket.On("screen-getAllDisplaysCompleted", (displays) => { BridgeConnector.Socket.Off("screen-getAllDisplaysCompleted"); - taskCompletionSource.SetResult(((JArray)displays).ToObject()); + taskCompletionSource.SetResult(displays.Deserialize(ElectronJson.Options)); }); BridgeConnector.Socket.Emit("screen-getAllDisplays"); @@ -162,14 +161,14 @@ public Task GetDisplayNearestPointAsync(Point point) { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("screen-getDisplayNearestPointCompleted", (display) => + BridgeConnector.Socket.On("screen-getDisplayNearestPointCompleted", (display) => { BridgeConnector.Socket.Off("screen-getDisplayNearestPointCompleted"); - taskCompletionSource.SetResult(((JObject)display).ToObject()); + taskCompletionSource.SetResult(JsonSerializer.Deserialize(display, Serialization.ElectronJsonContext.Default.Display)); }); - BridgeConnector.Socket.Emit("screen-getDisplayNearestPoint", JObject.FromObject(point, _jsonSerializer)); + BridgeConnector.Socket.Emit("screen-getDisplayNearestPoint", point); return taskCompletionSource.Task; } @@ -183,23 +182,18 @@ public Task GetDisplayMatchingAsync(Rectangle rectangle) { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("screen-getDisplayMatching", (display) => + BridgeConnector.Socket.On("screen-getDisplayMatching", (display) => { BridgeConnector.Socket.Off("screen-getDisplayMatching"); - taskCompletionSource.SetResult(((JObject)display).ToObject()); + taskCompletionSource.SetResult(JsonSerializer.Deserialize(display, Serialization.ElectronJsonContext.Default.Display)); }); - BridgeConnector.Socket.Emit("screen-getDisplayMatching", JObject.FromObject(rectangle, _jsonSerializer)); + BridgeConnector.Socket.Emit("screen-getDisplayMatching", rectangle); return taskCompletionSource.Task; } - private JsonSerializer _jsonSerializer = new JsonSerializer() - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - NullValueHandling = NullValueHandling.Ignore, - DefaultValueHandling = DefaultValueHandling.Ignore - }; + } -} \ No newline at end of file +} diff --git a/src/ElectronNET.API/API/Session.cs b/src/ElectronNET.API/API/Session.cs index d5a18675..72cf0eea 100644 --- a/src/ElectronNET.API/API/Session.cs +++ b/src/ElectronNET.API/API/Session.cs @@ -1,8 +1,6 @@ -using ElectronNET.API.Entities; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; +using ElectronNET.API.Entities; using System; +using System.Text.Json; using System.Threading.Tasks; namespace ElectronNET.API @@ -59,7 +57,7 @@ public Task ClearAuthCacheAsync(RemovePassword options) taskCompletionSource.SetResult(null); }); - BridgeConnector.Socket.Emit("webContents-session-clearAuthCache", Id, JObject.FromObject(options, _jsonSerializer), guid); + BridgeConnector.Socket.Emit("webContents-session-clearAuthCache", Id, options, guid); return taskCompletionSource.Task; } @@ -159,7 +157,7 @@ public Task ClearStorageDataAsync(ClearStorageDataOptions options) taskCompletionSource.SetResult(null); }); - BridgeConnector.Socket.Emit("webContents-session-clearStorageData-options", Id, JObject.FromObject(options, _jsonSerializer), guid); + BridgeConnector.Socket.Emit("webContents-session-clearStorageData-options", Id, options, guid); return taskCompletionSource.Task; } @@ -174,7 +172,7 @@ public Task ClearStorageDataAsync(ClearStorageDataOptions options) /// public void CreateInterruptedDownload(CreateInterruptedDownloadOptions options) { - BridgeConnector.Socket.Emit("webContents-session-createInterruptedDownload", Id, JObject.FromObject(options, _jsonSerializer)); + BridgeConnector.Socket.Emit("webContents-session-createInterruptedDownload", Id, options); } /// @@ -192,7 +190,7 @@ public void DisableNetworkEmulation() /// public void EnableNetworkEmulation(EnableNetworkEmulationOptions options) { - BridgeConnector.Socket.Emit("webContents-session-enableNetworkEmulation", Id, JObject.FromObject(options, _jsonSerializer)); + BridgeConnector.Socket.Emit("webContents-session-enableNetworkEmulation", Id, options); } /// @@ -213,9 +211,9 @@ public Task GetBlobDataAsync(string identifier) var taskCompletionSource = new TaskCompletionSource(); string guid = Guid.NewGuid().ToString(); - BridgeConnector.Socket.On("webContents-session-getBlobData-completed" + guid, (buffer) => + BridgeConnector.Socket.On("webContents-session-getBlobData-completed" + guid, (buffer) => { - var result = ((JArray)buffer).ToObject(); + var result = JsonSerializer.Deserialize(buffer, Serialization.ElectronJson.Options); BridgeConnector.Socket.Off("webContents-session-getBlobData-completed" + guid); taskCompletionSource.SetResult(result); @@ -235,10 +233,10 @@ public Task GetCacheSizeAsync() var taskCompletionSource = new TaskCompletionSource(); string guid = Guid.NewGuid().ToString(); - BridgeConnector.Socket.On("webContents-session-getCacheSize-completed" + guid, (size) => + BridgeConnector.Socket.On("webContents-session-getCacheSize-completed" + guid, (size) => { BridgeConnector.Socket.Off("webContents-session-getCacheSize-completed" + guid); - taskCompletionSource.SetResult((int)size); + taskCompletionSource.SetResult(size.GetInt32()); }); BridgeConnector.Socket.Emit("webContents-session-getCacheSize", Id, guid); @@ -255,9 +253,9 @@ public Task GetPreloadsAsync() var taskCompletionSource = new TaskCompletionSource(); string guid = Guid.NewGuid().ToString(); - BridgeConnector.Socket.On("webContents-session-getPreloads-completed" + guid, (preloads) => + BridgeConnector.Socket.On("webContents-session-getPreloads-completed" + guid, (preloads) => { - var result = ((JArray)preloads).ToObject(); + var result = JsonSerializer.Deserialize(preloads, Serialization.ElectronJson.Options); BridgeConnector.Socket.Off("webContents-session-getPreloads-completed" + guid); taskCompletionSource.SetResult(result); }); @@ -276,10 +274,10 @@ public Task GetUserAgent() var taskCompletionSource = new TaskCompletionSource(); string guid = Guid.NewGuid().ToString(); - BridgeConnector.Socket.On("webContents-session-getUserAgent-completed" + guid, (userAgent) => + BridgeConnector.Socket.On("webContents-session-getUserAgent-completed" + guid, (userAgent) => { BridgeConnector.Socket.Off("webContents-session-getUserAgent-completed" + guid); - taskCompletionSource.SetResult(userAgent.ToString()); + taskCompletionSource.SetResult(userAgent.GetString()); }); BridgeConnector.Socket.Emit("webContents-session-getUserAgent", Id, guid); @@ -298,10 +296,10 @@ public Task ResolveProxyAsync(string url) var taskCompletionSource = new TaskCompletionSource(); string guid = Guid.NewGuid().ToString(); - BridgeConnector.Socket.On("webContents-session-resolveProxy-completed" + guid, (proxy) => + BridgeConnector.Socket.On("webContents-session-resolveProxy-completed" + guid, (proxy) => { BridgeConnector.Socket.Off("webContents-session-resolveProxy-completed" + guid); - taskCompletionSource.SetResult(proxy.ToString()); + taskCompletionSource.SetResult(proxy.GetString()); }); BridgeConnector.Socket.Emit("webContents-session-resolveProxy", Id, url, guid); @@ -346,7 +344,7 @@ public Task SetProxyAsync(ProxyConfig config) taskCompletionSource.SetResult(null); }); - BridgeConnector.Socket.Emit("webContents-session-setProxy", Id, JObject.FromObject(config, _jsonSerializer), guid); + BridgeConnector.Socket.Emit("webContents-session-setProxy", Id, config, guid); return taskCompletionSource.Task; } @@ -387,10 +385,10 @@ public Task GetAllExtensionsAsync() { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("webContents-session-getAllExtensions-completed", (extensionslist) => + BridgeConnector.Socket.On("webContents-session-getAllExtensions-completed", (extensionslist) => { BridgeConnector.Socket.Off("webContents-session-getAllExtensions-completed"); - var chromeExtensionInfos = ((JArray)extensionslist).ToObject(); + var chromeExtensionInfos = JsonSerializer.Deserialize(extensionslist, Serialization.ElectronJson.Options); taskCompletionSource.SetResult(chromeExtensionInfos); }); @@ -441,11 +439,11 @@ public Task LoadExtensionAsync(string path, bool allowFileAccess = fa { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("webContents-session-loadExtension-completed", (extension) => + BridgeConnector.Socket.On("webContents-session-loadExtension-completed", (extension) => { BridgeConnector.Socket.Off("webContents-session-loadExtension-completed"); - taskCompletionSource.SetResult(((JObject)extension).ToObject()); + taskCompletionSource.SetResult(JsonSerializer.Deserialize(extension, Serialization.ElectronJson.Options)); }); BridgeConnector.Socket.Emit("webContents-session-loadExtension", Id, path, allowFileAccess); @@ -453,11 +451,6 @@ public Task LoadExtensionAsync(string path, bool allowFileAccess = fa return taskCompletionSource.Task; } - private JsonSerializer _jsonSerializer = new JsonSerializer() - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - NullValueHandling = NullValueHandling.Ignore, - DefaultValueHandling = DefaultValueHandling.Ignore - }; + } -} \ No newline at end of file +} diff --git a/src/ElectronNET.API/API/Shell.cs b/src/ElectronNET.API/API/Shell.cs index 27d75ce7..87bd5535 100644 --- a/src/ElectronNET.API/API/Shell.cs +++ b/src/ElectronNET.API/API/Shell.cs @@ -1,9 +1,7 @@ -using ElectronNET.API.Entities; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; -using System.Threading.Tasks; +using ElectronNET.API.Entities; using ElectronNET.API.Extensions; +using System.Text.Json; +using System.Threading.Tasks; namespace ElectronNET.API { @@ -62,11 +60,11 @@ public Task OpenPathAsync(string path) { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("shell-openPathCompleted", (errorMessage) => + BridgeConnector.Socket.On("shell-openPathCompleted", (errorMessage) => { BridgeConnector.Socket.Off("shell-openPathCompleted"); - taskCompletionSource.SetResult((string)errorMessage); + taskCompletionSource.SetResult(errorMessage.GetString()); }); BridgeConnector.Socket.Emit("shell-openPath", path); @@ -96,11 +94,11 @@ public Task OpenExternalAsync(string url, OpenExternalOptions options) { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("shell-openExternalCompleted", (error) => + BridgeConnector.Socket.On("shell-openExternalCompleted", (error) => { BridgeConnector.Socket.Off("shell-openExternalCompleted"); - taskCompletionSource.SetResult((string)error); + taskCompletionSource.SetResult(error.GetString()); }); if (options == null) @@ -109,7 +107,7 @@ public Task OpenExternalAsync(string url, OpenExternalOptions options) } else { - BridgeConnector.Socket.Emit("shell-openExternal", url, JObject.FromObject(options, _jsonSerializer)); + BridgeConnector.Socket.Emit("shell-openExternal", url, options); } return taskCompletionSource.Task; @@ -124,11 +122,11 @@ public Task TrashItemAsync(string fullPath) { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("shell-trashItem-completed", (success) => + BridgeConnector.Socket.On("shell-trashItem-completed", (success) => { BridgeConnector.Socket.Off("shell-trashItem-completed"); - taskCompletionSource.SetResult((bool)success); + taskCompletionSource.SetResult(success.GetBoolean()); }); BridgeConnector.Socket.Emit("shell-trashItem", fullPath); @@ -155,14 +153,14 @@ public Task WriteShortcutLinkAsync(string shortcutPath, ShortcutLinkOperat { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("shell-writeShortcutLinkCompleted", (success) => + BridgeConnector.Socket.On("shell-writeShortcutLinkCompleted", (success) => { BridgeConnector.Socket.Off("shell-writeShortcutLinkCompleted"); - taskCompletionSource.SetResult((bool)success); + taskCompletionSource.SetResult(success.GetBoolean()); }); - BridgeConnector.Socket.Emit("shell-writeShortcutLink", shortcutPath, operation.GetDescription(), JObject.FromObject(options, _jsonSerializer)); + BridgeConnector.Socket.Emit("shell-writeShortcutLink", shortcutPath, operation.GetDescription(), options); return taskCompletionSource.Task; } @@ -177,12 +175,11 @@ public Task ReadShortcutLinkAsync(string shortcutPath) { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("shell-readShortcutLinkCompleted", (shortcutDetails) => + BridgeConnector.Socket.On("shell-readShortcutLinkCompleted", (shortcutDetails) => { BridgeConnector.Socket.Off("shell-readShortcutLinkCompleted"); - var shortcutObject = shortcutDetails as JObject; - var details = shortcutObject?.ToObject(); + var details = JsonSerializer.Deserialize(shortcutDetails, Serialization.ElectronJson.Options); taskCompletionSource.SetResult(details); }); @@ -192,11 +189,6 @@ public Task ReadShortcutLinkAsync(string shortcutPath) return taskCompletionSource.Task; } - private readonly JsonSerializer _jsonSerializer = new JsonSerializer() - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - NullValueHandling = NullValueHandling.Ignore, - DefaultValueHandling = DefaultValueHandling.Ignore - }; + } -} \ No newline at end of file +} diff --git a/src/ElectronNET.API/API/Tray.cs b/src/ElectronNET.API/API/Tray.cs index 7e559755..8f4f2aed 100644 --- a/src/ElectronNET.API/API/Tray.cs +++ b/src/ElectronNET.API/API/Tray.cs @@ -1,12 +1,9 @@ -using ElectronNET.API.Entities; +using ElectronNET.API.Entities; using ElectronNET.API.Extensions; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; +using ElectronNET.Common; using System; using System.Collections.Generic; using System.Threading.Tasks; -using ElectronNET.Common; // ReSharper disable InconsistentNaming @@ -140,7 +137,7 @@ public async Task Show(string image, MenuItem menuItem) public async Task Show(string image, MenuItem[] menuItems) { menuItems.AddMenuItemsId(); - await BridgeConnector.Socket.Emit("create-tray", image, JArray.FromObject(menuItems, this._jsonSerializer)).ConfigureAwait(false); + await BridgeConnector.Socket.Emit("create-tray", image, menuItems).ConfigureAwait(false); _items.Clear(); _items.AddRange(menuItems); @@ -212,7 +209,7 @@ public async Task SetTitle(string title) /// public async Task DisplayBalloon(DisplayBalloonOptions options) { - await BridgeConnector.Socket.Emit("tray-displayBalloon", JObject.FromObject(options, this._jsonSerializer)).ConfigureAwait(false); + await BridgeConnector.Socket.Emit("tray-displayBalloon", options).ConfigureAwait(false); } /// @@ -235,11 +232,7 @@ public async Task IsDestroyedAsync() return await taskCompletionSource.Task.ConfigureAwait(false); } - private readonly JsonSerializer _jsonSerializer = new() - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - NullValueHandling = NullValueHandling.Ignore - }; + private const string ModuleName = "tray"; @@ -275,4 +268,4 @@ public void Once(string eventName, Action action) public async Task Once(string eventName, Action action) => await Events.Instance.Once(ModuleName, eventName, action).ConfigureAwait(false); } -} \ No newline at end of file +} diff --git a/src/ElectronNET.API/API/WebContents.cs b/src/ElectronNET.API/API/WebContents.cs index 94cee556..ba0ec295 100644 --- a/src/ElectronNET.API/API/WebContents.cs +++ b/src/ElectronNET.API/API/WebContents.cs @@ -1,10 +1,9 @@ -using ElectronNET.API.Entities; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; +using ElectronNET.API.Entities; +using ElectronNET.API.Serialization; +using ElectronNET.Common; using System; +using System.Text.Json; using System.Threading.Tasks; -using ElectronNET.Common; // ReSharper disable InconsistentNaming @@ -33,7 +32,7 @@ public class WebContents /// public event Action OnCrashed { - add => ApiEventManager.AddEvent("webContents-crashed", Id, _crashed, value, (args) => (bool)args); + add => ApiEventManager.AddEvent("webContents-crashed", Id, _crashed, value, (args) => args.GetBoolean()); remove => ApiEventManager.RemoveEvent("webContents-crashed", Id, _crashed, value); } @@ -102,7 +101,7 @@ public event Action OnDidRedirectNavigation /// public event Action OnDidFailLoad { - add => ApiEventManager.AddEvent("webContents-didFailLoad", Id, _didFailLoad, value, (args) => ((JObject)args).ToObject()); + add => ApiEventManager.AddEvent("webContents-didFailLoad", Id, _didFailLoad, value, (args) => JsonSerializer.Deserialize(args, ElectronJson.Options)); remove => ApiEventManager.RemoveEvent("webContents-didFailLoad", Id, _didFailLoad, value); } @@ -113,7 +112,7 @@ public event Action OnDidFailLoad /// public event Action InputEvent { - add => ApiEventManager.AddEvent("webContents-input-event", Id, _inputEvent, value, (args) => ((JObject)args).ToObject()); + add => ApiEventManager.AddEvent("webContents-input-event", Id, _inputEvent, value, (args) => JsonSerializer.Deserialize(args, ElectronJson.Options)); remove => ApiEventManager.RemoveEvent("webContents-input-event", Id, _inputEvent, value); } @@ -150,7 +149,7 @@ public void OpenDevTools() /// public void OpenDevTools(OpenDevToolsOptions openDevToolsOptions) { - BridgeConnector.Socket.Emit("webContentsOpenDevTools", Id, JObject.FromObject(openDevToolsOptions, _jsonSerializer)); + BridgeConnector.Socket.Emit("webContentsOpenDevTools", Id, openDevToolsOptions); } /// @@ -161,11 +160,11 @@ public Task GetPrintersAsync() { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("webContents-getPrinters-completed", (printers) => + BridgeConnector.Socket.On("webContents-getPrinters-completed", (printers) => { BridgeConnector.Socket.Off("webContents-getPrinters-completed"); - taskCompletionSource.SetResult(((Newtonsoft.Json.Linq.JArray)printers).ToObject()); + taskCompletionSource.SetResult(JsonSerializer.Deserialize(printers, ElectronJson.Options)); }); BridgeConnector.Socket.Emit("webContents-getPrinters", Id); @@ -182,10 +181,10 @@ public Task PrintAsync(PrintOptions options = null) { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("webContents-print-completed", (success) => + BridgeConnector.Socket.On("webContents-print-completed", (success) => { BridgeConnector.Socket.Off("webContents-print-completed"); - taskCompletionSource.SetResult((bool)success); + taskCompletionSource.SetResult(success.GetBoolean()); }); if (options == null) @@ -194,7 +193,7 @@ public Task PrintAsync(PrintOptions options = null) } else { - BridgeConnector.Socket.Emit("webContents-print", Id, JObject.FromObject(options, _jsonSerializer)); + BridgeConnector.Socket.Emit("webContents-print", Id, options); } return taskCompletionSource.Task; @@ -213,10 +212,10 @@ public Task PrintToPDFAsync(string path, PrintToPDFOptions options = null) { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("webContents-printToPDF-completed", (success) => + BridgeConnector.Socket.On("webContents-printToPDF-completed", (success) => { BridgeConnector.Socket.Off("webContents-printToPDF-completed"); - taskCompletionSource.SetResult((bool)success); + taskCompletionSource.SetResult(success.GetBoolean()); }); if (options == null) @@ -225,7 +224,7 @@ public Task PrintToPDFAsync(string path, PrintToPDFOptions options = null) } else { - BridgeConnector.Socket.Emit("webContents-printToPDF", Id, JObject.FromObject(options, _jsonSerializer), path); + BridgeConnector.Socket.Emit("webContents-printToPDF", Id, options, path); } return taskCompletionSource.Task; @@ -247,14 +246,14 @@ public Task PrintToPDFAsync(string path, PrintToPDFOptions options = null) /// Code execution will be suspended until web page stop loading. /// /// - public Task ExecuteJavaScriptAsync(string code, bool userGesture = false) + public Task ExecuteJavaScriptAsync(string code, bool userGesture = false) { - var taskCompletionSource = new TaskCompletionSource(); + var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("webContents-executeJavaScript-completed", (result) => + BridgeConnector.Socket.On("webContents-executeJavaScript-completed", (result) => { BridgeConnector.Socket.Off("webContents-executeJavaScript-completed"); - taskCompletionSource.SetResult(result); + taskCompletionSource.SetResult(result.Deserialize(ElectronJson.Options)); }); BridgeConnector.Socket.Emit("webContents-executeJavaScript", Id, code, userGesture); @@ -272,10 +271,10 @@ public Task GetUrl() var taskCompletionSource = new TaskCompletionSource(); var eventString = "webContents-getUrl" + Id; - BridgeConnector.Socket.On(eventString, (url) => + BridgeConnector.Socket.On(eventString, (url) => { BridgeConnector.Socket.Off(eventString); - taskCompletionSource.SetResult((string)url); + taskCompletionSource.SetResult(url.GetString()); }); BridgeConnector.Socket.Emit("webContents-getUrl", Id); @@ -324,13 +323,13 @@ public Task LoadURLAsync(string url, LoadURLOptions options) taskCompletionSource.SetResult(null); }); - BridgeConnector.Socket.On("webContents-loadURL-error" + Id, (error) => + BridgeConnector.Socket.On("webContents-loadURL-error" + Id, (error) => { BridgeConnector.Socket.Off("webContents-loadURL-error" + Id); - taskCompletionSource.SetException(new InvalidOperationException(error.ToString())); + taskCompletionSource.SetException(new InvalidOperationException(error.GetString())); }); - BridgeConnector.Socket.Emit("webContents-loadURL", Id, url, JObject.FromObject(options, _jsonSerializer)); + BridgeConnector.Socket.Emit("webContents-loadURL", Id, url, options); return taskCompletionSource.Task; } @@ -347,10 +346,5 @@ public void InsertCSS(bool isBrowserWindow, string path) BridgeConnector.Socket.Emit("webContents-insertCSS", Id, isBrowserWindow, path); } - private readonly JsonSerializer _jsonSerializer = new() - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - NullValueHandling = NullValueHandling.Ignore, - DefaultValueHandling = DefaultValueHandling.Ignore - }; -} \ No newline at end of file + +} diff --git a/src/ElectronNET.API/API/WebRequest.cs b/src/ElectronNET.API/API/WebRequest.cs index 2aa448ad..3460ebc8 100644 --- a/src/ElectronNET.API/API/WebRequest.cs +++ b/src/ElectronNET.API/API/WebRequest.cs @@ -1,4 +1,3 @@ -using Newtonsoft.Json.Linq; using System; namespace ElectronNET.API.Entities @@ -33,18 +32,17 @@ public void OnBeforeRequest(WebRequestFilter filter, Action($"webContents-session-webRequest-onBeforeRequest{Id}", (args) => { - ////var details = ((JObject)args[0]).ToObject(); - ////var callback = args.Length > 1 ? (Action)((response) => { BridgeConnector.Socket.Emit($"webContents-session-webRequest-onBeforeRequest-response{Id}", response); }) : null; - var details = ((JObject)args).ToObject(); + //// var details0 = args[0].Deserialize(ElectronNET.API.Serialization.ElectronJson.Options); + var details = System.Text.Json.JsonSerializer.Deserialize(args, Serialization.ElectronJson.Options); var callback = (Action)((response) => { BridgeConnector.Socket.Emit($"webContents-session-webRequest-onBeforeRequest-response{Id}", response); }); _onBeforeRequest?.Invoke(details, callback); }); - BridgeConnector.Socket.Emit("register-webContents-session-webRequest-onBeforeRequest", Id, JObject.FromObject(filter)); + BridgeConnector.Socket.Emit("register-webContents-session-webRequest-onBeforeRequest", Id, filter); } _onBeforeRequest += listener; @@ -59,4 +57,4 @@ public void RemoveListener(Action> listen } } } -} \ No newline at end of file +} diff --git a/src/ElectronNET.API/API/WindowManager.cs b/src/ElectronNET.API/API/WindowManager.cs index 9ec0369f..dc7f0faf 100644 --- a/src/ElectronNET.API/API/WindowManager.cs +++ b/src/ElectronNET.API/API/WindowManager.cs @@ -1,12 +1,9 @@ -using ElectronNET.API.Entities; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Newtonsoft.Json.Serialization; +using ElectronNET.API.Entities; using System; using System.Collections.Generic; using System.Linq; -using System.Net.Sockets; using System.Runtime.InteropServices; +using System.Text.Json; using System.Threading.Tasks; namespace ElectronNET.API @@ -100,11 +97,11 @@ public async Task CreateWindowAsync(BrowserWindowOptions options, { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("BrowserWindowCreated", (id) => + BridgeConnector.Socket.On("BrowserWindowCreated", (id) => { BridgeConnector.Socket.Off("BrowserWindowCreated"); - var browserWindowId = int.Parse(id.ToString()!); + var browserWindowId = id.GetInt32(); var browserWindow = new BrowserWindow(browserWindowId); _browserWindows.Add(browserWindow); @@ -112,11 +109,11 @@ public async Task CreateWindowAsync(BrowserWindowOptions options, taskCompletionSource.SetResult(browserWindow); }); - BridgeConnector.Socket.On("BrowserWindowClosed", (ids) => + BridgeConnector.Socket.On("BrowserWindowClosed", (ids) => { BridgeConnector.Socket.Off("BrowserWindowClosed"); - var browserWindowIds = ((JArray)ids).ToObject(); + var browserWindowIds = ids.Deserialize(Serialization.ElectronJson.Options); for (int index = 0; index < _browserWindows.Count; index++) { @@ -127,7 +124,7 @@ public async Task CreateWindowAsync(BrowserWindowOptions options, } }); - if (loadUrl.ToUpper() == "HTTP://LOCALHOST" && ElectronNetRuntime.AspNetWebPort.HasValue) + if (loadUrl.Equals("http://localhost", StringComparison.OrdinalIgnoreCase) && ElectronNetRuntime.AspNetWebPort.HasValue) { loadUrl = $"{loadUrl}:{ElectronNetRuntime.AspNetWebPort}"; } @@ -145,7 +142,7 @@ public async Task CreateWindowAsync(BrowserWindowOptions options, options.X = 0; options.Y = 0; - await BridgeConnector.Socket.Emit("createBrowserWindow", JObject.FromObject(options, this._jsonSerializer), loadUrl).ConfigureAwait(false); + await BridgeConnector.Socket.Emit("createBrowserWindow", options, loadUrl).ConfigureAwait(false); } else { @@ -156,7 +153,7 @@ public async Task CreateWindowAsync(BrowserWindowOptions options, options.X -= 7; } - await BridgeConnector.Socket.Emit("createBrowserWindow", JObject.FromObject(options, this._jsonSerializer), loadUrl).ConfigureAwait(false); + await BridgeConnector.Socket.Emit("createBrowserWindow", options, loadUrl).ConfigureAwait(false); } return await taskCompletionSource.Task.ConfigureAwait(false); @@ -189,32 +186,22 @@ public async Task CreateBrowserViewAsync(BrowserViewConstructorOpti { var taskCompletionSource = new TaskCompletionSource(); - BridgeConnector.Socket.On("BrowserViewCreated", (id) => + BridgeConnector.Socket.On("BrowserViewCreated", (id) => { BridgeConnector.Socket.Off("BrowserViewCreated"); - string browserViewId = id.ToString(); - BrowserView browserView = new BrowserView(int.Parse(browserViewId)); + var browserViewId = id.GetInt32(); + BrowserView browserView = new(browserViewId); _browserViews.Add(browserView); taskCompletionSource.SetResult(browserView); }); - var ownjsonSerializer = new JsonSerializer() - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - NullValueHandling = NullValueHandling.Ignore - }; - await BridgeConnector.Socket.Emit("createBrowserView", JObject.FromObject(options, ownjsonSerializer)).ConfigureAwait(false); + await BridgeConnector.Socket.Emit("createBrowserView", options).ConfigureAwait(false); return await taskCompletionSource.Task.ConfigureAwait(false); } - private readonly JsonSerializer _jsonSerializer = new() - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - NullValueHandling = NullValueHandling.Ignore - }; } } \ No newline at end of file diff --git a/src/ElectronNET.API/Bridge/SocketIOFacade.cs b/src/ElectronNET.API/Bridge/SocketIOFacade.cs index 21c03ae2..86453637 100644 --- a/src/ElectronNET.API/Bridge/SocketIOFacade.cs +++ b/src/ElectronNET.API/Bridge/SocketIOFacade.cs @@ -2,11 +2,12 @@ // ReSharper disable once CheckNamespace namespace ElectronNET.API; +using ElectronNET.API.Serialization; +using SocketIO.Serializer.SystemTextJson; using System; +using System.Linq; +using System.Text.Json; using System.Threading.Tasks; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using SocketIO.Serializer.NewtonsoftJson; using SocketIO = SocketIOClient.SocketIO; internal class SocketIoFacade @@ -17,14 +18,9 @@ internal class SocketIoFacade public SocketIoFacade(string uri) { _socket = new SocketIO(uri); - var jsonSerializer = new NewtonsoftJsonSerializer(new JsonSerializerSettings - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - NullValueHandling = NullValueHandling.Ignore, - DefaultValueHandling = DefaultValueHandling.Ignore - }); - - _socket.Serializer = jsonSerializer; + _socket.Serializer = new SystemTextJsonSerializer(ElectronJson.Options); + // Use default System.Text.Json serializer from SocketIOClient. + // Outgoing args are normalized to camelCase via SerializeArg in Emit. } public event EventHandler BridgeDisconnected; @@ -70,14 +66,14 @@ public void On(string eventName, Action action) } } - // TODO: Remove this method when SocketIoClient supports object deserialization + // Keep object overload for compatibility; value will be a JsonElement boxed as object. public void On(string eventName, Action action) { lock (_lockObj) { _socket.On(eventName, response => { - var value = response.GetValue(); + var value = (object)response.GetValue(); ////Console.WriteLine($"Called Event {eventName} - data {value}"); Task.Run(() => action(value)); }); @@ -125,4 +121,4 @@ public void DisposeSocket() { _socket.Dispose(); } -} \ No newline at end of file +} diff --git a/src/ElectronNET.API/Common/ApiEventManager.cs b/src/ElectronNET.API/Common/ApiEventManager.cs index 61ef2c7d..1db069eb 100644 --- a/src/ElectronNET.API/Common/ApiEventManager.cs +++ b/src/ElectronNET.API/Common/ApiEventManager.cs @@ -1,7 +1,9 @@ -using System; using ElectronNET.API; using ElectronNET.API.Entities; -using Newtonsoft.Json.Linq; +using ElectronNET.API.Serialization; +using System; +using System.Linq; +using System.Text.Json; namespace ElectronNET.Common; @@ -24,11 +26,11 @@ internal static void RemoveEvent(string eventName, object id, Action callback, A if (callback == null) BridgeConnector.Socket.Off(eventName + id); } - internal static void AddEvent(string eventName, object id, Action callback, Action value, Func converter, string suffix = "") + internal static void AddEvent(string eventName, object id, Action callback, Action value, Func converter, string suffix = "") { if (callback == null) { - BridgeConnector.Socket.On(eventName + id, (args) => + BridgeConnector.Socket.On(eventName + id, (args) => { var converted = converter.Invoke(args); callback(converted); @@ -60,11 +62,11 @@ internal static void AddTrayEvent(string eventName, object id, Action(eventName + id, (result) => + BridgeConnector.Socket.On(eventName + id, (result) => { - var args = ((JArray)result).ToObject(); - var trayClickEventArgs = ((JObject)args[0]).ToObject(); - var bounds = ((JObject)args[1]).ToObject(); + var array = result.EnumerateArray().ToArray(); + var trayClickEventArgs = array[0].Deserialize(ElectronJsonContext.Default.TrayClickEventArgs); + var bounds = array[1].Deserialize(ElectronJsonContext.Default.Rectangle); callback(trayClickEventArgs, bounds); }); BridgeConnector.Socket.Emit($"register-{eventName}", id); @@ -82,10 +84,11 @@ internal static void AddScreenEvent(string eventName, object id, Action + BridgeConnector.Socket.On(eventName + id, (args) => { - var display = ((JArray)args).First.ToObject(); - var metrics = ((JArray)args).Last.ToObject(); + var arr = args.EnumerateArray().ToArray(); + var display = arr[0].Deserialize(ElectronJsonContext.Default.Display); + var metrics = arr[1].Deserialize(ElectronJson.Options); callback(display, metrics); }); BridgeConnector.Socket.Emit($"register-{eventName}", id); @@ -98,4 +101,5 @@ internal static void RemoveScreenEvent(string eventName, object id, Action - /// + /// [SuppressMessage("ReSharper", "SuspiciousLockOverSynchronizationPrimitive")] public class ProcessRunner : IDisposable { diff --git a/src/ElectronNET.API/Common/RunnerParams.cs b/src/ElectronNET.API/Common/RunnerParams.cs index 001b8812..ee185543 100644 --- a/src/ElectronNET.API/Common/RunnerParams.cs +++ b/src/ElectronNET.API/Common/RunnerParams.cs @@ -16,7 +16,7 @@ public sealed class RunnerParams private ProcessWindowStyle windowStyle; /// - /// Default constructor. At least the + /// Default constructor. At least the /// property must be set before starting the process. /// public RunnerParams() diff --git a/src/ElectronNET.API/Converter/ModifierTypeListConverter.cs b/src/ElectronNET.API/Converter/ModifierTypeListConverter.cs index 5d1daedb..737a0ab5 100644 --- a/src/ElectronNET.API/Converter/ModifierTypeListConverter.cs +++ b/src/ElectronNET.API/Converter/ModifierTypeListConverter.cs @@ -1,54 +1,45 @@ namespace ElectronNET.Converter; +using ElectronNET.API.Entities; using System; using System.Collections.Generic; -using System.Linq; -using ElectronNET.API.Entities; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; /// /// /// public class ModifierTypeListConverter : JsonConverter> { - /// - /// - /// - /// - /// - /// - /// - /// - /// - public override List ReadJson(JsonReader reader, Type objectType, List existingValue, bool hasExistingValue, JsonSerializer serializer) + public override List Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - var token = JToken.Load(reader); - - if (token.Type == JTokenType.Null) + if (reader.TokenType == JsonTokenType.Null) { return null; } - - return token.ToObject>().Select(m => (ModifierType)Enum.Parse(typeof(ModifierType), m)).ToList(); + var list = new List(); + if (reader.TokenType != JsonTokenType.StartArray) + { + throw new JsonException("Expected array for ModifierType list"); + } + while (reader.Read()) + { + if (reader.TokenType == JsonTokenType.EndArray) break; + if (reader.TokenType != JsonTokenType.String) throw new JsonException("Expected string enum value"); + var s = reader.GetString(); + list.Add((ModifierType)Enum.Parse(typeof(ModifierType), s, ignoreCase: true)); + } + return list; } - /// - /// - /// - /// - /// - /// - public override void WriteJson(JsonWriter writer, List value, JsonSerializer serializer) + public override void Write(Utf8JsonWriter writer, List value, JsonSerializerOptions options) { writer.WriteStartArray(); - foreach (var modifier in value) { - writer.WriteValue(modifier.ToString()); + writer.WriteStringValue(modifier.ToString()); } - writer.WriteEndArray(); } -} \ No newline at end of file +} diff --git a/src/ElectronNET.API/Converter/PageSizeConverter.cs b/src/ElectronNET.API/Converter/PageSizeConverter.cs index 5e5e559b..38a898bf 100644 --- a/src/ElectronNET.API/Converter/PageSizeConverter.cs +++ b/src/ElectronNET.API/Converter/PageSizeConverter.cs @@ -1,43 +1,47 @@ -using ElectronNET.API.Entities; -using Newtonsoft.Json; +using ElectronNET.API.Entities; using System; +using System.Text.Json; +using System.Text.Json.Serialization; namespace ElectronNET.Converter; public class PageSizeConverter : JsonConverter { - public override PageSize ReadJson(JsonReader reader, Type objectType, PageSize existingValue, bool hasExistingValue, JsonSerializer serializer) + public override PageSize Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - if (reader.TokenType == JsonToken.String) + if (reader.TokenType == JsonTokenType.String) { - return (string)reader.Value; + return (string)reader.GetString(); } - else if (reader.TokenType == JsonToken.StartObject) + else if (reader.TokenType == JsonTokenType.StartObject) { - return serializer.Deserialize(reader); + using var doc = JsonDocument.ParseValue(ref reader); + return doc.RootElement.Deserialize(API.Serialization.ElectronJson.Options); } else { - throw new JsonSerializationException("Invalid value for PageSize. Expected true, false, or an object."); + throw new JsonException("Invalid value for PageSize. Expected string or an object."); } } - public override void WriteJson(JsonWriter writer, PageSize value, JsonSerializer serializer) + public override void Write(Utf8JsonWriter writer, PageSize value, JsonSerializerOptions options) { if (value is null) { - writer.WriteUndefined(); + writer.WriteNullValue(); + return; } var str = (string)value; if (str is not null) { - writer.WriteValue(str); + writer.WriteStringValue(str); } else { - serializer.Serialize(writer, value); + JsonSerializer.Serialize(writer, value, API.Serialization.ElectronJson.Options); } } } + diff --git a/src/ElectronNET.API/Converter/TitleBarOverlayConverter.cs b/src/ElectronNET.API/Converter/TitleBarOverlayConverter.cs index 58bf53d8..b4b75d43 100644 --- a/src/ElectronNET.API/Converter/TitleBarOverlayConverter.cs +++ b/src/ElectronNET.API/Converter/TitleBarOverlayConverter.cs @@ -1,43 +1,46 @@ -using ElectronNET.API.Entities; -using Newtonsoft.Json; +using ElectronNET.API.Entities; using System; +using System.Text.Json; +using System.Text.Json.Serialization; namespace ElectronNET.Converter; public class TitleBarOverlayConverter : JsonConverter { - public override TitleBarOverlay ReadJson(JsonReader reader, Type objectType, TitleBarOverlay existingValue, bool hasExistingValue, JsonSerializer serializer) + public override TitleBarOverlay Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { - if (reader.TokenType == JsonToken.Boolean) + if (reader.TokenType == JsonTokenType.True || reader.TokenType == JsonTokenType.False) { - return (bool)reader.Value; + return (bool)reader.GetBoolean(); } - else if (reader.TokenType == JsonToken.StartObject) + else if (reader.TokenType == JsonTokenType.StartObject) { - return serializer.Deserialize(reader); + using var doc = JsonDocument.ParseValue(ref reader); + return doc.RootElement.Deserialize(API.Serialization.ElectronJson.Options); } else { - throw new JsonSerializationException("Invalid value for TitleBarOverlay. Expected true, false, or an object."); + throw new JsonException("Invalid value for TitleBarOverlay. Expected boolean or an object."); } } - public override void WriteJson(JsonWriter writer, TitleBarOverlay value, JsonSerializer serializer) + public override void Write(Utf8JsonWriter writer, TitleBarOverlay value, JsonSerializerOptions options) { if (value is null) { - writer.WriteUndefined(); + writer.WriteNullValue(); return; } var @bool = (bool?)value; if (@bool.HasValue) { - writer.WriteValue(@bool.Value); + writer.WriteBooleanValue(@bool.Value); } else { - serializer.Serialize(writer, value); + JsonSerializer.Serialize(writer, value, API.Serialization.ElectronJson.Options); } } -} \ No newline at end of file +} + diff --git a/src/ElectronNET.API/ElectronNET.API.csproj b/src/ElectronNET.API/ElectronNET.API.csproj index 3d568fe5..30435998 100644 --- a/src/ElectronNET.API/ElectronNET.API.csproj +++ b/src/ElectronNET.API/ElectronNET.API.csproj @@ -27,8 +27,6 @@ all runtime; build; native; contentfiles; analyzers - - @@ -38,4 +36,4 @@ - \ No newline at end of file + diff --git a/src/ElectronNET.API/ElectronNetRuntime.cs b/src/ElectronNET.API/ElectronNetRuntime.cs index bf3ce4e4..8fd0f0b0 100644 --- a/src/ElectronNET.API/ElectronNetRuntime.cs +++ b/src/ElectronNET.API/ElectronNetRuntime.cs @@ -1,12 +1,12 @@ namespace ElectronNET { - using System; - using System.Collections.Immutable; - using System.Threading.Tasks; using ElectronNET.API; using ElectronNET.Runtime; using ElectronNET.Runtime.Controllers; using ElectronNET.Runtime.Data; + using System; + using System.Collections.Immutable; + using System.Threading.Tasks; public static class ElectronNetRuntime { diff --git a/src/ElectronNET.API/Runtime/Controllers/RuntimeControllerBase.cs b/src/ElectronNET.API/Runtime/Controllers/RuntimeControllerBase.cs index 65c911ad..fe527c7e 100644 --- a/src/ElectronNET.API/Runtime/Controllers/RuntimeControllerBase.cs +++ b/src/ElectronNET.API/Runtime/Controllers/RuntimeControllerBase.cs @@ -1,10 +1,10 @@ namespace ElectronNET.Runtime.Controllers { - using System.Threading.Tasks; using ElectronNET.API; using ElectronNET.Runtime.Services; using ElectronNET.Runtime.Services.ElectronProcess; using ElectronNET.Runtime.Services.SocketBridge; + using System.Threading.Tasks; internal abstract class RuntimeControllerBase : LifetimeServiceBase, IElectronNetRuntimeController { diff --git a/src/ElectronNET.API/Runtime/Controllers/RuntimeControllerDotNetFirst.cs b/src/ElectronNET.API/Runtime/Controllers/RuntimeControllerDotNetFirst.cs index af615cfb..8e1633dd 100644 --- a/src/ElectronNET.API/Runtime/Controllers/RuntimeControllerDotNetFirst.cs +++ b/src/ElectronNET.API/Runtime/Controllers/RuntimeControllerDotNetFirst.cs @@ -1,13 +1,13 @@ namespace ElectronNET.Runtime.Controllers { - using System; - using System.Threading.Tasks; using ElectronNET.API; using ElectronNET.Common; using ElectronNET.Runtime.Data; using ElectronNET.Runtime.Helpers; using ElectronNET.Runtime.Services.ElectronProcess; using ElectronNET.Runtime.Services.SocketBridge; + using System; + using System.Threading.Tasks; internal class RuntimeControllerDotNetFirst : RuntimeControllerBase { diff --git a/src/ElectronNET.API/Runtime/Controllers/RuntimeControllerElectronFirst.cs b/src/ElectronNET.API/Runtime/Controllers/RuntimeControllerElectronFirst.cs index cc97cd01..fdb458f0 100644 --- a/src/ElectronNET.API/Runtime/Controllers/RuntimeControllerElectronFirst.cs +++ b/src/ElectronNET.API/Runtime/Controllers/RuntimeControllerElectronFirst.cs @@ -1,11 +1,11 @@ namespace ElectronNET.Runtime.Controllers { - using System; - using System.Threading.Tasks; using ElectronNET.API; using ElectronNET.Runtime.Data; using ElectronNET.Runtime.Services.ElectronProcess; using ElectronNET.Runtime.Services.SocketBridge; + using System; + using System.Threading.Tasks; internal class RuntimeControllerElectronFirst : RuntimeControllerBase { diff --git a/src/ElectronNET.API/Runtime/IElectronNetRuntimeController.cs b/src/ElectronNET.API/Runtime/IElectronNetRuntimeController.cs index 4b69c3ca..6aaf2bd8 100644 --- a/src/ElectronNET.API/Runtime/IElectronNetRuntimeController.cs +++ b/src/ElectronNET.API/Runtime/IElectronNetRuntimeController.cs @@ -1,8 +1,8 @@ namespace ElectronNET.Runtime { + using ElectronNET.Runtime.Data; using System; using System.Threading.Tasks; - using ElectronNET.Runtime.Data; public interface IElectronNetRuntimeController { diff --git a/src/ElectronNET.API/Runtime/Services/ElectronProcess/ElectronProcessActive.cs b/src/ElectronNET.API/Runtime/Services/ElectronProcess/ElectronProcessActive.cs index 57056fe1..297c17c5 100644 --- a/src/ElectronNET.API/Runtime/Services/ElectronProcess/ElectronProcessActive.cs +++ b/src/ElectronNET.API/Runtime/Services/ElectronProcess/ElectronProcessActive.cs @@ -1,11 +1,11 @@ namespace ElectronNET.Runtime.Services.ElectronProcess { + using ElectronNET.Common; + using ElectronNET.Runtime.Data; using System; using System.ComponentModel; using System.IO; using System.Threading.Tasks; - using ElectronNET.Common; - using ElectronNET.Runtime.Data; /// /// Launches and manages the Electron app process. diff --git a/src/ElectronNET.API/Runtime/Services/ElectronProcess/ElectronProcessPassive.cs b/src/ElectronNET.API/Runtime/Services/ElectronProcess/ElectronProcessPassive.cs index 7d13b3fc..d62cbd71 100644 --- a/src/ElectronNET.API/Runtime/Services/ElectronProcess/ElectronProcessPassive.cs +++ b/src/ElectronNET.API/Runtime/Services/ElectronProcess/ElectronProcessPassive.cs @@ -1,10 +1,10 @@ namespace ElectronNET.Runtime.Services.ElectronProcess { + using ElectronNET.Runtime.Data; using System; using System.ComponentModel; using System.Diagnostics; using System.Threading.Tasks; - using ElectronNET.Runtime.Data; /// /// Launches and manages the Electron app process. diff --git a/src/ElectronNET.API/Runtime/Services/LifetimeServiceBase.cs b/src/ElectronNET.API/Runtime/Services/LifetimeServiceBase.cs index 90a14108..16a9cdf9 100644 --- a/src/ElectronNET.API/Runtime/Services/LifetimeServiceBase.cs +++ b/src/ElectronNET.API/Runtime/Services/LifetimeServiceBase.cs @@ -1,9 +1,9 @@ namespace ElectronNET.Runtime.Services { + using ElectronNET.Runtime.Data; using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; - using ElectronNET.Runtime.Data; public abstract class LifetimeServiceBase { diff --git a/src/ElectronNET.API/Runtime/Services/SocketBridge/SocketBridgeService.cs b/src/ElectronNET.API/Runtime/Services/SocketBridge/SocketBridgeService.cs index 8d7c9dac..23ca4d86 100644 --- a/src/ElectronNET.API/Runtime/Services/SocketBridge/SocketBridgeService.cs +++ b/src/ElectronNET.API/Runtime/Services/SocketBridge/SocketBridgeService.cs @@ -1,9 +1,9 @@ namespace ElectronNET.Runtime.Services.SocketBridge { - using System; - using System.Threading.Tasks; using ElectronNET.API; using ElectronNET.Runtime.Data; + using System; + using System.Threading.Tasks; internal class SocketBridgeService : LifetimeServiceBase { diff --git a/src/ElectronNET.API/Runtime/StartupManager.cs b/src/ElectronNET.API/Runtime/StartupManager.cs index fd17d26c..81f79826 100644 --- a/src/ElectronNET.API/Runtime/StartupManager.cs +++ b/src/ElectronNET.API/Runtime/StartupManager.cs @@ -1,13 +1,13 @@ namespace ElectronNET.Runtime { + using ElectronNET.Runtime.Controllers; + using ElectronNET.Runtime.Data; + using ElectronNET.Runtime.Helpers; using System; using System.Collections.Immutable; using System.Globalization; using System.Linq; using System.Reflection; - using ElectronNET.Runtime.Controllers; - using ElectronNET.Runtime.Data; - using ElectronNET.Runtime.Helpers; internal class StartupManager { diff --git a/src/ElectronNET.API/Serialization/ElectronJson.cs b/src/ElectronNET.API/Serialization/ElectronJson.cs new file mode 100644 index 00000000..a34dc3a7 --- /dev/null +++ b/src/ElectronNET.API/Serialization/ElectronJson.cs @@ -0,0 +1,35 @@ +using ElectronNET.API.Entities; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace ElectronNET.API.Serialization +{ + internal static class ElectronJson + { + public static readonly JsonSerializerOptions Options = new JsonSerializerOptions + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + WriteIndented = false, + }; + + static ElectronJson() + { + Options.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)); + } + } + + // Use source generation where feasible for hot paths + [JsonSourceGenerationOptions(WriteIndented = false, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)] + [JsonSerializable(typeof(TrayClickEventArgs))] + [JsonSerializable(typeof(Rectangle))] + [JsonSerializable(typeof(Display))] + [JsonSerializable(typeof(UpdateInfo))] + [JsonSerializable(typeof(ProgressInfo))] + [JsonSerializable(typeof(UpdateCheckResult))] + [JsonSerializable(typeof(SemVer))] + internal partial class ElectronJsonContext : JsonSerializerContext + { + } +} + diff --git a/src/ElectronNET.IntegrationTests/Tests/BrowserWindowTests.cs b/src/ElectronNET.IntegrationTests/Tests/BrowserWindowTests.cs index 40077784..2d006963 100644 --- a/src/ElectronNET.IntegrationTests/Tests/BrowserWindowTests.cs +++ b/src/ElectronNET.IntegrationTests/Tests/BrowserWindowTests.cs @@ -48,7 +48,7 @@ public async Task Can_set_and_get_position() this.fx.MainWindow.SetPosition(134, 246); await Task.Delay(500); var pos = await this.fx.MainWindow.GetPositionAsync(); - pos.Should().BeEquivalentTo(new[] { 134, 246 }); + pos.Should().BeEquivalentTo([134, 246]); } [Fact] @@ -134,7 +134,7 @@ public async Task PageTitleUpdated_event_fires_on_title_change() window.WebContents.OnDomReady += () => domReadyTcs.TrySetResult(); await window.WebContents.LoadURLAsync("about:blank"); await domReadyTcs.Task; - await window.WebContents.ExecuteJavaScriptAsync("document.title='NewTitle';"); + await window.WebContents.ExecuteJavaScriptAsync("document.title='NewTitle';"); // Wait for event up to a short timeout var completed2 = await Task.WhenAny(tcs.Task, Task.Delay(3000)); diff --git a/src/ElectronNET.IntegrationTests/Tests/CookiesTests.cs b/src/ElectronNET.IntegrationTests/Tests/CookiesTests.cs index 284b381c..3113fe52 100644 --- a/src/ElectronNET.IntegrationTests/Tests/CookiesTests.cs +++ b/src/ElectronNET.IntegrationTests/Tests/CookiesTests.cs @@ -18,7 +18,7 @@ public async Task Cookie_set_get_remove_sequence() // Navigate to example.com so cookie domain matches await this.fx.MainWindow.WebContents.LoadURLAsync("https://example.com"); // Set via renderer for now - await this.fx.MainWindow.WebContents.ExecuteJavaScriptAsync("document.cookie='integration_cookie=1;path=/';"); + await this.fx.MainWindow.WebContents.ExecuteJavaScriptAsync("document.cookie='integration_cookie=1;path=/';"); await Task.Delay(500); changed.Should().BeTrue(); } diff --git a/src/ElectronNET.IntegrationTests/Tests/IpcMainTests.cs b/src/ElectronNET.IntegrationTests/Tests/IpcMainTests.cs index 9e49f46e..80b979bd 100644 --- a/src/ElectronNET.IntegrationTests/Tests/IpcMainTests.cs +++ b/src/ElectronNET.IntegrationTests/Tests/IpcMainTests.cs @@ -16,7 +16,7 @@ public async Task Ipc_On_receives_message_from_renderer() { var tcs = new TaskCompletionSource(); await Electron.IpcMain.On("ipc-on-test", obj => tcs.TrySetResult(obj?.ToString() ?? string.Empty)); - await this.fx.MainWindow.WebContents.ExecuteJavaScriptAsync("require('electron').ipcRenderer.send('ipc-on-test','payload123')"); + await this.fx.MainWindow.WebContents.ExecuteJavaScriptAsync("require('electron').ipcRenderer.send('ipc-on-test','payload123')"); var result = await tcs.Task.WaitAsync(TimeSpan.FromSeconds(5)); result.Should().Be("payload123"); } @@ -26,7 +26,7 @@ public async Task Ipc_Once_only_fires_once() { var count = 0; Electron.IpcMain.Once("ipc-once-test", _ => count++); - await this.fx.MainWindow.WebContents.ExecuteJavaScriptAsync("const {ipcRenderer}=require('electron'); ipcRenderer.send('ipc-once-test','a'); ipcRenderer.send('ipc-once-test','b');"); + await this.fx.MainWindow.WebContents.ExecuteJavaScriptAsync("const {ipcRenderer}=require('electron'); ipcRenderer.send('ipc-once-test','a'); ipcRenderer.send('ipc-once-test','b');"); await Task.Delay(500); count.Should().Be(1); } @@ -37,7 +37,7 @@ public async Task Ipc_RemoveAllListeners_stops_receiving() var fired = false; await Electron.IpcMain.On("ipc-remove-test", _ => fired = true); Electron.IpcMain.RemoveAllListeners("ipc-remove-test"); - await this.fx.MainWindow.WebContents.ExecuteJavaScriptAsync("require('electron').ipcRenderer.send('ipc-remove-test','x')"); + await this.fx.MainWindow.WebContents.ExecuteJavaScriptAsync("require('electron').ipcRenderer.send('ipc-remove-test','x')"); await Task.Delay(400); fired.Should().BeFalse(); } @@ -45,12 +45,12 @@ public async Task Ipc_RemoveAllListeners_stops_receiving() [Fact] public async Task Ipc_OnSync_returns_value() { - Electron.IpcMain.OnSync("ipc-sync-test", obj => + Electron.IpcMain.OnSync("ipc-sync-test", (obj) => { obj.Should().NotBeNull(); return "pong"; }); - var ret = await this.fx.MainWindow.WebContents.ExecuteJavaScriptAsync("require('electron').ipcRenderer.sendSync('ipc-sync-test','ping')"); + var ret = await this.fx.MainWindow.WebContents.ExecuteJavaScriptAsync("require('electron').ipcRenderer.sendSync('ipc-sync-test','ping')"); ret.Should().Be("pong"); } @@ -58,12 +58,12 @@ public async Task Ipc_OnSync_returns_value() public async Task Ipc_Send_from_main_reaches_renderer() { // Listener: store raw arg; if Electron packs differently we will normalize later - await this.fx.MainWindow.WebContents.ExecuteJavaScriptAsync(@"(function(){ const {ipcRenderer}=require('electron'); ipcRenderer.once('main-to-render',(e,arg)=>{ globalThis.__mainToRender = arg;}); return 'ready'; })();"); + await this.fx.MainWindow.WebContents.ExecuteJavaScriptAsync(@"(function(){ const {ipcRenderer}=require('electron'); ipcRenderer.once('main-to-render',(e,arg)=>{ globalThis.__mainToRender = arg;}); return 'ready'; })();"); Electron.IpcMain.Send(this.fx.MainWindow, "main-to-render", "hello-msg"); string value = ""; for (int i = 0; i < 20; i++) { - var jsVal = await this.fx.MainWindow.WebContents.ExecuteJavaScriptAsync("globalThis.__mainToRender === undefined ? '' : (typeof globalThis.__mainToRender === 'string' ? globalThis.__mainToRender : JSON.stringify(globalThis.__mainToRender))"); + var jsVal = await this.fx.MainWindow.WebContents.ExecuteJavaScriptAsync("globalThis.__mainToRender === undefined ? '' : (typeof globalThis.__mainToRender === 'string' ? globalThis.__mainToRender : JSON.stringify(globalThis.__mainToRender))"); value = jsVal?.ToString() ?? ""; if (!string.IsNullOrEmpty(value)) { diff --git a/src/ElectronNET.IntegrationTests/Tests/MenuTests.cs b/src/ElectronNET.IntegrationTests/Tests/MenuTests.cs index 511860b2..120f045b 100644 --- a/src/ElectronNET.IntegrationTests/Tests/MenuTests.cs +++ b/src/ElectronNET.IntegrationTests/Tests/MenuTests.cs @@ -29,7 +29,7 @@ public async Task ApplicationMenu_click_invokes_handler() }; Electron.Menu.SetApplicationMenu(items); var targetId = items[0].Submenu[0].Id; - await this.fx.MainWindow.WebContents.ExecuteJavaScriptAsync($"require('electron').ipcRenderer.send('integration-click-application-menu','{targetId}')"); + await this.fx.MainWindow.WebContents.ExecuteJavaScriptAsync($"require('electron').ipcRenderer.send('integration-click-application-menu','{targetId}')"); for (int i = 0; i < 20 && !clicked; i++) { await Task.Delay(100); @@ -48,7 +48,7 @@ public async Task ContextMenu_popup_registers_items() var ctxId = ctxItems[0].Id; // simulate popup then click Electron.Menu.ContextMenuPopup(win); - await this.fx.MainWindow.WebContents.ExecuteJavaScriptAsync($"require('electron').ipcRenderer.send('integration-click-context-menu',{win.Id},'{ctxId}')"); + await this.fx.MainWindow.WebContents.ExecuteJavaScriptAsync($"require('electron').ipcRenderer.send('integration-click-context-menu',{win.Id},'{ctxId}')"); for (int i = 0; i < 20 && !ctxClicked; i++) { await Task.Delay(100); diff --git a/src/ElectronNET.IntegrationTests/Tests/ProcessTests.cs b/src/ElectronNET.IntegrationTests/Tests/ProcessTests.cs index edfb986a..2c8ae098 100644 --- a/src/ElectronNET.IntegrationTests/Tests/ProcessTests.cs +++ b/src/ElectronNET.IntegrationTests/Tests/ProcessTests.cs @@ -10,7 +10,7 @@ public async Task Process_info_is_accessible() { // Use renderer to fetch process info and round-trip var execPath = await Electron.WindowManager.CreateWindowAsync(new API.Entities.BrowserWindowOptions { Show = false }); - var result = await execPath.WebContents.ExecuteJavaScriptAsync("process.execPath && process.platform ? 'ok' : 'fail'"); + var result = await execPath.WebContents.ExecuteJavaScriptAsync("process.execPath && process.platform ? 'ok' : 'fail'"); result.Should().Be("ok"); } diff --git a/src/ElectronNET.IntegrationTests/Tests/WebContentsTests.cs b/src/ElectronNET.IntegrationTests/Tests/WebContentsTests.cs index 066557e3..b3593abb 100644 --- a/src/ElectronNET.IntegrationTests/Tests/WebContentsTests.cs +++ b/src/ElectronNET.IntegrationTests/Tests/WebContentsTests.cs @@ -26,7 +26,7 @@ public async Task ExecuteJavaScript_returns_title() { var wc = this.fx.MainWindow.WebContents; await wc.LoadURLAsync("https://example.com"); - var title = await wc.ExecuteJavaScriptAsync("document.title"); + var title = await wc.ExecuteJavaScriptAsync("document.title"); title.Should().NotBeNull(); } diff --git a/src/ElectronNET.WebApp/Controllers/ClipboardController.cs b/src/ElectronNET.WebApp/Controllers/ClipboardController.cs index a290236a..1d89c2cf 100644 --- a/src/ElectronNET.WebApp/Controllers/ClipboardController.cs +++ b/src/ElectronNET.WebApp/Controllers/ClipboardController.cs @@ -1,11 +1,11 @@ -using System; +using System; using System.Drawing; using System.IO; using Microsoft.AspNetCore.Mvc; using ElectronNET.API; using System.Linq; using ElectronNET.API.Entities; -using Newtonsoft.Json; +using System.Text.Json; namespace ElectronNET.WebApp.Controllers { @@ -39,11 +39,11 @@ public IActionResult Index() { var nativeImage = await Electron.Clipboard.ReadImageAsync(); var mainWindow = Electron.WindowManager.BrowserWindows.First(); - Electron.IpcMain.Send(mainWindow, "paste-image-from", JsonConvert.SerializeObject(nativeImage)); + Electron.IpcMain.Send(mainWindow, "paste-image-from", JsonSerializer.Serialize(nativeImage)); }); } return View(); } } -} \ No newline at end of file +} diff --git a/src/ElectronNET.WebApp/Views/Clipboard/Index.cshtml b/src/ElectronNET.WebApp/Views/Clipboard/Index.cshtml index 99264763..00f6cb86 100644 --- a/src/ElectronNET.WebApp/Views/Clipboard/Index.cshtml +++ b/src/ElectronNET.WebApp/Views/Clipboard/Index.cshtml @@ -1,4 +1,4 @@ -