Compare commits

..

143 Commits

Author SHA1 Message Date
Florian Rappl
a0c0523c7d Change default framework version to net10.0
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-09-07 09:18:27 +02:00
Florian Rappl
6d94cf9538 Improved template 2026-09-07 08:52:56 +02:00
Florian Rappl
521e7c935a Removed references to electronize 2026-09-07 08:25:18 +02:00
Florian Rappl
730eacbd52 Improved templates for preview version 2026-09-04 21:06:47 +02:00
Florian Rappl
deca8166ec Added template #414 2026-09-04 20:44:55 +02:00
Florian Rappl
a04ca0b9bc Completed APIs from #956 2026-09-04 16:57:44 +02:00
Florian Rappl
fffd7dfb79 Added more missing APIs 2026-09-04 16:51:51 +02:00
Florian Rappl
98c72af3d6 Updated zoom level 2026-09-04 16:03:43 +02:00
Florian Rappl
703cf8f880 Updated to use nsis on Windows 2026-09-04 15:48:29 +02:00
Florian Rappl
248d4bd664 Updated and improved migration checks #946 2026-09-04 15:19:07 +02:00
Florian Rappl
d5da1dbc9b Fixed #1029 2026-09-04 15:05:55 +02:00
Florian Rappl
672ff6c40d Implemented #1003 2026-09-04 14:29:38 +02:00
Florian Rappl
7cd552a78f Finished #1106 2026-09-04 14:05:36 +02:00
Florian Rappl
042d8e6c70 Infra enhancements 2026-09-04 13:26:27 +02:00
Florian Rappl
0140749753 Fixed #1103 2026-09-04 11:52:21 +02:00
Florian Rappl
7af2e954c7 Fixed 1040 2026-09-04 11:37:42 +02:00
Florian Rappl
da0e1f17db Fixes #1097 2026-09-03 17:04:21 +02:00
Florian Rappl
9cb210040d Fixed #1105 2026-09-03 16:25:47 +02:00
Florian Rappl
7e8f45b16d Updated changelog 2026-09-03 16:17:19 +02:00
Florian Rappl
76dc687269 Merged 2026-09-03 11:28:37 +02:00
Florian Rappl
dcf4585510 Merge pull request #1108 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.WebApp/ElectronHostHook/humanfs/node-0.16.8
Bump @humanfs/node from 0.16.7 to 0.16.8 in /src/ElectronNET.WebApp/ElectronHostHook
2026-09-03 08:54:37 +02:00
dependabot[bot]
a6d7434adf Bump @humanfs/node in /src/ElectronNET.WebApp/ElectronHostHook
Bumps [@humanfs/node](https://github.com/humanwhocodes/humanfs/tree/HEAD/packages/node) from 0.16.7 to 0.16.8.
- [Release notes](https://github.com/humanwhocodes/humanfs/releases)
- [Changelog](https://github.com/humanwhocodes/humanfs/blob/main/packages/node/CHANGELOG.md)
- [Commits](https://github.com/humanwhocodes/humanfs/commits/node-v0.16.8/packages/node)

---
updated-dependencies:
- dependency-name: "@humanfs/node"
  dependency-version: 0.16.8
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-03 00:19:56 +00:00
Florian Rappl
76ff44f67e Merge pull request #1104 from epsitec-sa/feat/#1095
chore(build): allow customization of target framwork version in dev mode (#1095)
2026-08-14 13:07:48 +02:00
Samuel Nussbaum
20ab82b16d chore(build): fix error when props file is missing 2026-08-14 11:25:19 +02:00
Samuel Nussbaum
b27f705a6a chore(build): Change import barriere 2026-08-14 10:52:10 +02:00
Samuel Nussbaum
8697c4de44 chore(build): passthrough props barriere 2026-08-14 10:07:58 +02:00
Florian Rappl
376a791e48 Merge pull request #1099 from epsitec-sa/bug/#1096
chore(build): fix #1096 by depends on resolve unrelated target
2026-08-11 09:45:16 +02:00
Florian Rappl
195a29052e Merge pull request #1100 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.WebApp/ElectronHostHook/js-yaml-4.3.1
Bump js-yaml from 4.3.0 to 4.3.1 in /src/ElectronNET.WebApp/ElectronHostHook
2026-08-11 09:31:59 +02:00
Florian Rappl
f577a53227 Merge pull request #1102 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.Host/electron-39.8.10
Bump electron from 30.5.1 to 39.8.10 in /src/ElectronNET.Host
2026-08-11 08:52:04 +02:00
Florian Rappl
382d544468 Merge pull request #1101 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.WebApp/ElectronHostHook/brace-expansion-1.1.18
Bump brace-expansion from 1.1.14 to 1.1.18 in /src/ElectronNET.WebApp/ElectronHostHook
2026-08-11 08:51:42 +02:00
dependabot[bot]
18f08f9aff Bump electron from 30.5.1 to 39.8.10 in /src/ElectronNET.Host
Bumps [electron](https://github.com/electron/electron) from 30.5.1 to 39.8.10.
- [Release notes](https://github.com/electron/electron/releases)
- [Commits](https://github.com/electron/electron/compare/v30.5.1...v39.8.10)

---
updated-dependencies:
- dependency-name: electron
  dependency-version: 39.8.10
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-10 23:17:12 +00:00
dependabot[bot]
def289ab54 Bump brace-expansion in /src/ElectronNET.WebApp/ElectronHostHook
Bumps [brace-expansion](https://github.com/juliangruber/brace-expansion) from 1.1.14 to 1.1.18.
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](https://github.com/juliangruber/brace-expansion/compare/v1.1.14...v1.1.18)

---
updated-dependencies:
- dependency-name: brace-expansion
  dependency-version: 1.1.18
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-10 23:17:02 +00:00
dependabot[bot]
4011f3d30b Bump js-yaml in /src/ElectronNET.WebApp/ElectronHostHook
Bumps [js-yaml](https://github.com/nodeca/js-yaml) from 4.3.0 to 4.3.1.
- [Changelog](https://github.com/nodeca/js-yaml/blob/4.3.1/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/4.3.0...4.3.1)

---
updated-dependencies:
- dependency-name: js-yaml
  dependency-version: 4.3.1
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-10 23:17:01 +00:00
Samuel Nussbaum
26b9d86ee4 chore(build): target frameworks customization 2026-08-10 10:33:00 +02:00
Florian Rappl
3b57de976a Merge pull request #1098 from epsitec-sa/bug/#1097
fix(packaging): Restore cross-compile on same platform and packaging dir name behavior
2026-08-10 10:19:45 +02:00
Samuel Nussbaum
d9e9b3d2e6 fix(packaging): Architecture must be defined in electron-builder compile args in order to allow cross-compile on same platform. Enforce default-arch to be the default arch in order to avoid arch in package directory name. 2026-08-10 09:22:21 +02:00
Samuel Nussbaum
1ec1fde3c6 chore(build): fix #1096 by depends on not resolve related target 2026-08-07 14:37:13 +02:00
Florian Rappl
e5ccf75c9f Merge pull request #1094 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.Host/ElectronHostHook/socket.io-parser-4.2.7
Bump socket.io-parser from 4.2.6 to 4.2.7 in /src/ElectronNET.Host/ElectronHostHook
2026-08-05 09:08:03 +02:00
dependabot[bot]
819e643ab8 Bump socket.io-parser in /src/ElectronNET.Host/ElectronHostHook
Bumps [socket.io-parser](https://github.com/socketio/socket.io) from 4.2.6 to 4.2.7.
- [Release notes](https://github.com/socketio/socket.io/releases)
- [Changelog](https://github.com/socketio/socket.io/blob/main/CHANGELOG.md)
- [Commits](https://github.com/socketio/socket.io/compare/socket.io-parser@4.2.6...socket.io-parser@4.2.7)

---
updated-dependencies:
- dependency-name: socket.io-parser
  dependency-version: 4.2.7
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-05 05:07:46 +00:00
Florian Rappl
7fe3f9b5b6 Merge pull request #1093 from ElectronNET/develop
Release 0.5.2
2026-08-03 14:53:48 +02:00
Florian Rappl
16cbc5f2a4 Improved platform agnostic for test 2026-08-03 14:36:20 +02:00
Florian Rappl
3a2c997e6a Ensure windows are not retained after being destroyed #1008 2026-08-03 14:25:47 +02:00
Florian Rappl
f88f5f8b18 Added tests, improved icon implementation 2026-08-03 14:19:25 +02:00
Florian Rappl
4e39f5f377 Added support for MacOS modern app icon #1047 2026-08-03 14:12:09 +02:00
Florian Rappl
7fa5ec5b0b Fixed #1050 2026-08-03 14:09:01 +02:00
Florian Rappl
2f8f717dbb Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-08-03 11:13:32 +02:00
Florian Rappl
525d6185fb Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-08-03 11:13:08 +02:00
Florian Rappl
73703819be Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-08-03 11:12:56 +02:00
Florian Rappl
09249f74c6 Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-08-03 11:12:41 +02:00
Florian Rappl
cfd8be36f3 Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-08-03 11:12:19 +02:00
Florian Rappl
6055635eb5 Potential fix for pull request finding
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-08-03 11:11:15 +02:00
Florian Rappl
74a734ae58 Merge pull request #1092 from epsitec-sa/bug/#1091
Bug/#1091 - Fix CA1416 on AspNet project
2026-07-29 11:05:29 +02:00
Samuel Nussbaum
d4402d1040 chore(build): Apply same NoWarn regardless of current runtime, platform or architecture in order to avoid compile issue when used in development mode 2026-07-29 09:47:00 +02:00
Florian Rappl
4b65ed26a4 Merge pull request #1089 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.WebApp/ElectronHostHook/flatted-3.4.3
Bump flatted from 3.3.3 to 3.4.3 in /src/ElectronNET.WebApp/ElectronHostHook
2026-07-28 09:07:22 +02:00
Florian Rappl
e12145004e Merge pull request #1090 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.Host/socket.io-parser-4.2.7
Bump socket.io-parser from 4.2.5 to 4.2.7 in /src/ElectronNET.Host
2026-07-28 09:07:11 +02:00
Florian Rappl
3e8ebde05b Merge pull request #1088 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.Host/multi-32449639ce
Bump builder-util-runtime and electron-updater in /src/ElectronNET.Host
2026-07-28 09:06:58 +02:00
Florian Rappl
820d7bbcec Merge pull request #1087 from epsitec-sa/bug/#1084
Bug/#1084 - Visual studio loading issue
2026-07-28 09:05:52 +02:00
Samuel Nussbaum
5eeab1bd24 fix(warning): remove warining CS4014 2026-07-28 06:54:48 +02:00
Roger Vuistiner
1fff688098 chore: consolidate MSBuild configuration barriers
- Moved Directory.Build.* barriers from nuke to root folder to cover all projects.
- Added a Directory.Packages.props barrier to stop central package management.
- Removed obsolete 'ManagePackageVersionsCentrally' properties.
2026-07-28 06:54:43 +02:00
dependabot[bot]
9b701f5258 Bump socket.io-parser from 4.2.5 to 4.2.7 in /src/ElectronNET.Host
Bumps [socket.io-parser](https://github.com/socketio/socket.io) from 4.2.5 to 4.2.7.
- [Release notes](https://github.com/socketio/socket.io/releases)
- [Changelog](https://github.com/socketio/socket.io/blob/main/CHANGELOG.md)
- [Commits](https://github.com/socketio/socket.io/compare/socket.io-parser@4.2.5...socket.io-parser@4.2.7)

---
updated-dependencies:
- dependency-name: socket.io-parser
  dependency-version: 4.2.7
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-28 03:41:41 +00:00
dependabot[bot]
b41c7e51b1 Bump flatted in /src/ElectronNET.WebApp/ElectronHostHook
Bumps [flatted](https://github.com/WebReflection/flatted) from 3.3.3 to 3.4.3.
- [Commits](https://github.com/WebReflection/flatted/compare/v3.3.3...v3.4.3)

---
updated-dependencies:
- dependency-name: flatted
  dependency-version: 3.4.3
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-28 03:41:32 +00:00
dependabot[bot]
1d24067f4b Bump builder-util-runtime and electron-updater in /src/ElectronNET.Host
Bumps [builder-util-runtime](https://github.com/electron-userland/electron-builder/tree/HEAD/packages/builder-util-runtime) to 9.7.0 and updates ancestor dependency [electron-updater](https://github.com/electron-userland/electron-builder/tree/HEAD/packages/electron-updater). These dependencies need to be updated together.


Updates `builder-util-runtime` from 9.5.1 to 9.7.0
- [Release notes](https://github.com/electron-userland/electron-builder/releases)
- [Changelog](https://github.com/electron-userland/electron-builder/blob/master/packages/builder-util-runtime/CHANGELOG.md)
- [Commits](https://github.com/electron-userland/electron-builder/commits/HEAD/packages/builder-util-runtime)

Updates `electron-updater` from 6.8.3 to 6.8.9
- [Release notes](https://github.com/electron-userland/electron-builder/releases)
- [Changelog](https://github.com/electron-userland/electron-builder/blob/master/packages/electron-updater/CHANGELOG.md)
- [Commits](https://github.com/electron-userland/electron-builder/commits/electron-updater@6.8.9/packages/electron-updater)

---
updated-dependencies:
- dependency-name: builder-util-runtime
  dependency-version: 9.7.0
  dependency-type: indirect
- dependency-name: electron-updater
  dependency-version: 6.8.9
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-28 03:41:30 +00:00
Samuel Nussbaum
44e5c4e230 chore(build): runtime identifier is not required anymore 2026-07-27 16:45:52 +02:00
Samuel Nussbaum
0b3053477d chore(dx): visual studio load regression, let electron choose the required runtime. 2026-07-27 16:45:52 +02:00
Samuel Nussbaum
3fecc0ee1b fix: Visual studio load issue 2026-07-27 16:45:51 +02:00
Florian Rappl
95089e1721 Merge pull request #1085 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.WebApp/ElectronHostHook/js-yaml-4.3.0
Bump js-yaml from 4.1.1 to 4.3.0 in /src/ElectronNET.WebApp/ElectronHostHook
2026-07-22 07:12:18 +02:00
Florian Rappl
cec178cf50 Merge pull request #1086 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.Host/brace-expansion-1.1.16
Bump brace-expansion from 1.1.12 to 1.1.16 in /src/ElectronNET.Host
2026-07-22 07:12:07 +02:00
dependabot[bot]
20af8a692c Bump brace-expansion from 1.1.12 to 1.1.16 in /src/ElectronNET.Host
Bumps [brace-expansion](https://github.com/juliangruber/brace-expansion) from 1.1.12 to 1.1.16.
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](https://github.com/juliangruber/brace-expansion/compare/v1.1.12...v1.1.16)

---
updated-dependencies:
- dependency-name: brace-expansion
  dependency-version: 1.1.16
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-22 02:19:22 +00:00
dependabot[bot]
4e69bcf030 Bump js-yaml in /src/ElectronNET.WebApp/ElectronHostHook
Bumps [js-yaml](https://github.com/nodeca/js-yaml) from 4.1.1 to 4.3.0.
- [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/4.1.1...4.3.0)

---
updated-dependencies:
- dependency-name: js-yaml
  dependency-version: 4.3.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-22 02:19:18 +00:00
Florian Rappl
5ae5bf0df7 Merge pull request #1083 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.Host/js-yaml-4.3.0
Bump js-yaml from 4.1.1 to 4.3.0 in /src/ElectronNET.Host
2026-07-15 07:12:13 +02:00
dependabot[bot]
5da5d1c618 Bump js-yaml from 4.1.1 to 4.3.0 in /src/ElectronNET.Host
Bumps [js-yaml](https://github.com/nodeca/js-yaml) from 4.1.1 to 4.3.0.
- [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/4.1.1...4.3.0)

---
updated-dependencies:
- dependency-name: js-yaml
  dependency-version: 4.3.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-14 22:27:36 +00:00
Florian Rappl
b6e496b2c6 Merge pull request #1082 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.WebApp/ElectronHostHook/js-yaml-4.3.0
Bump js-yaml from 4.1.1 to 4.3.0 in /src/ElectronNET.WebApp/ElectronHostHook
2026-07-09 15:33:25 +02:00
Florian Rappl
5974cb9e43 Merge branch 'develop' into dependabot/npm_and_yarn/src/ElectronNET.WebApp/ElectronHostHook/js-yaml-4.3.0 2026-07-09 10:42:03 +02:00
dependabot[bot]
d4d4e9dddd Bump js-yaml in /src/ElectronNET.WebApp/ElectronHostHook
Bumps [js-yaml](https://github.com/nodeca/js-yaml) from 4.1.1 to 4.3.0.
- [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/4.1.1...4.3.0)

---
updated-dependencies:
- dependency-name: js-yaml
  dependency-version: 4.3.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-08 23:02:16 +00:00
Florian Rappl
3b5f21c724 Merge pull request #1081 from epsitec-sa/bug/default-runtime
chore: use default sdk runtime identifier
2026-07-06 15:17:02 +02:00
Samuel Nussbaum
5aebe807c3 change to less brittle solution 2026-07-06 11:02:48 +02:00
Samuel Nussbaum
bdee008cc8 use default sdk runtime identifier 2026-07-06 10:44:05 +02:00
Florian Rappl
7fc5c9b611 Merge pull request #1080 from epsitec-sa/bug/#1058
fix(shore): bloated asar and corrupted packaged directory
2026-07-05 11:08:43 +02:00
Samuel Nussbaum
86e5d74c03 dump to latest version 2026-07-03 15:24:49 +02:00
Samuel Nussbaum
e79b029e16 Fix scoped css naming issue 2026-07-03 15:09:49 +02:00
Samuel Nussbaum
5bdf6230b9 fix examples build and publish 2026-07-03 15:08:57 +02:00
Samuel Nussbaum
8c2382a05c Split packaging to avoid duplication in .asar archive 2026-07-03 11:28:52 +02:00
Florian Rappl
10b1b686cb Merge pull request #1079 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.WebApp/ElectronHostHook/js-yaml-4.2.0
Bump js-yaml from 4.1.1 to 4.2.0 in /src/ElectronNET.WebApp/ElectronHostHook
2026-06-24 14:51:00 +02:00
Florian Rappl
d7d2521d0c Merge pull request #1078 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.Host/multi-5f1280885e
Bump ws, engine.io and socket.io-adapter in /src/ElectronNET.Host
2026-06-24 14:50:35 +02:00
Florian Rappl
392419e5a7 Merge branch 'develop' into dependabot/npm_and_yarn/src/ElectronNET.Host/multi-5f1280885e 2026-06-24 14:50:10 +02:00
dependabot[bot]
f92f07a378 Bump js-yaml in /src/ElectronNET.WebApp/ElectronHostHook
Bumps [js-yaml](https://github.com/nodeca/js-yaml) from 4.1.1 to 4.2.0.
- [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/4.1.1...4.2.0)

---
updated-dependencies:
- dependency-name: js-yaml
  dependency-version: 4.2.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-24 07:11:36 +00:00
dependabot[bot]
9b045cbf01 Bump ws, engine.io and socket.io-adapter in /src/ElectronNET.Host
Bumps [ws](https://github.com/websockets/ws), [engine.io](https://github.com/socketio/socket.io) and [socket.io-adapter](https://github.com/socketio/socket.io). These dependencies needed to be updated together.

Updates `ws` from 8.20.1 to 8.21.0
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](https://github.com/websockets/ws/compare/8.20.1...8.21.0)

Updates `engine.io` from 6.6.8 to 6.6.9
- [Release notes](https://github.com/socketio/socket.io/releases)
- [Changelog](https://github.com/socketio/socket.io/blob/main/CHANGELOG.md)
- [Commits](https://github.com/socketio/socket.io/compare/engine.io@6.6.8...engine.io@6.6.9)

Updates `socket.io-adapter` from 2.5.7 to 2.5.8
- [Release notes](https://github.com/socketio/socket.io/releases)
- [Changelog](https://github.com/socketio/socket.io/blob/main/CHANGELOG.md)
- [Commits](https://github.com/socketio/socket.io/compare/socket.io-adapter@2.5.7...socket.io-adapter@2.5.8)

---
updated-dependencies:
- dependency-name: ws
  dependency-version: 8.21.0
  dependency-type: indirect
- dependency-name: engine.io
  dependency-version: 6.6.9
  dependency-type: indirect
- dependency-name: socket.io-adapter
  dependency-version: 2.5.8
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-06-24 03:30:33 +00:00
Florian Rappl
94ff3c1c4d Updated token usage 2026-06-22 23:23:44 +02:00
Florian Rappl
773937448d Updated version 2026-06-22 23:23:34 +02:00
Florian Rappl
b094051dcb Merge pull request #1077 from AeonSake/1076-add-overloads-for-useelectron
Add Overloads for `UseElectron`
2026-06-21 21:46:56 +02:00
Aeon
3a10e7e98d Add missing null-check 2026-06-20 01:38:58 +02:00
Aeon
056661028b Remove unused property 2026-06-20 01:26:55 +02:00
Aeon
27a8c69a9a Add missing extension method overloads 2026-06-20 01:26:25 +02:00
Aeon
8e900655b9 Replace static property with resolver service 2026-06-20 01:26:00 +02:00
Aeon
066efa80e2 Add service for resolving on-app-ready callback 2026-06-20 01:24:30 +02:00
Florian Rappl
18944fe222 Release 0.5.1 (#1074)
* Bump ws, engine.io and socket.io-adapter

Bumps [ws](https://github.com/websockets/ws), [engine.io](https://github.com/socketio/socket.io) and [socket.io-adapter](https://github.com/socketio/socket.io). These dependencies needed to be updated together.

Updates `ws` from 8.17.1 to 8.20.1
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](https://github.com/websockets/ws/compare/8.17.1...8.20.1)

Updates `engine.io` from 6.6.4 to 6.6.8
- [Release notes](https://github.com/socketio/socket.io/releases)
- [Changelog](https://github.com/socketio/socket.io/blob/main/CHANGELOG.md)
- [Commits](https://github.com/socketio/socket.io/compare/engine.io@6.6.4...engine.io@6.6.8)

Updates `socket.io-adapter` from 2.5.5 to 2.5.7
- [Release notes](https://github.com/socketio/socket.io/releases)
- [Changelog](https://github.com/socketio/socket.io/blob/main/CHANGELOG.md)
- [Commits](https://github.com/socketio/socket.io/compare/socket.io-adapter@2.5.5...socket.io-adapter@2.5.7)

---
updated-dependencies:
- dependency-name: ws
  dependency-version: 8.20.1
  dependency-type: indirect
- dependency-name: engine.io
  dependency-version: 6.6.8
  dependency-type: indirect
- dependency-name: socket.io-adapter
  dependency-version: 2.5.7
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

* Bump tmp and exceljs in /src/ElectronNET.WebApp/ElectronHostHook

Bumps [tmp](https://github.com/raszi/node-tmp) to 0.2.7 and updates ancestor dependency [exceljs](https://github.com/exceljs/exceljs). These dependencies need to be updated together.


Updates `tmp` from 0.1.0 to 0.2.7
- [Changelog](https://github.com/raszi/node-tmp/blob/master/CHANGELOG.md)
- [Commits](https://github.com/raszi/node-tmp/compare/v0.1.0...v0.2.7)

Updates `exceljs` from 1.15.0 to 4.4.0
- [Release notes](https://github.com/exceljs/exceljs/releases)
- [Commits](https://github.com/exceljs/exceljs/compare/v1.15.0...v4.4.0)

---
updated-dependencies:
- dependency-name: tmp
  dependency-version: 0.2.7
  dependency-type: indirect
- dependency-name: exceljs
  dependency-version: 4.4.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>

* Bump ws, engine.io and socket.io-adapter in /src/ElectronNET.Host

Bumps [ws](https://github.com/websockets/ws), [engine.io](https://github.com/socketio/socket.io) and [socket.io-adapter](https://github.com/socketio/socket.io). These dependencies needed to be updated together.

Updates `ws` from 8.18.3 to 8.20.1
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](https://github.com/websockets/ws/compare/8.18.3...8.20.1)

Updates `engine.io` from 6.6.5 to 6.6.8
- [Release notes](https://github.com/socketio/socket.io/releases)
- [Changelog](https://github.com/socketio/socket.io/blob/main/CHANGELOG.md)
- [Commits](https://github.com/socketio/socket.io/compare/engine.io@6.6.5...engine.io@6.6.8)

Updates `socket.io-adapter` from 2.5.6 to 2.5.7
- [Release notes](https://github.com/socketio/socket.io/releases)
- [Changelog](https://github.com/socketio/socket.io/blob/main/CHANGELOG.md)
- [Commits](https://github.com/socketio/socket.io/compare/socket.io-adapter@2.5.6...socket.io-adapter@2.5.7)

---
updated-dependencies:
- dependency-name: ws
  dependency-version: 8.20.1
  dependency-type: indirect
- dependency-name: engine.io
  dependency-version: 6.6.8
  dependency-type: indirect
- dependency-name: socket.io-adapter
  dependency-version: 2.5.7
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

* Bump ws, engine.io and socket.io-adapter

Bumps [ws](https://github.com/websockets/ws), [engine.io](https://github.com/socketio/socket.io) and [socket.io-adapter](https://github.com/socketio/socket.io). These dependencies needed to be updated together.

Updates `ws` from 8.18.3 to 8.20.1
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](https://github.com/websockets/ws/compare/8.18.3...8.20.1)

Updates `engine.io` from 6.6.5 to 6.6.8
- [Release notes](https://github.com/socketio/socket.io/releases)
- [Changelog](https://github.com/socketio/socket.io/blob/main/CHANGELOG.md)
- [Commits](https://github.com/socketio/socket.io/compare/engine.io@6.6.5...engine.io@6.6.8)

Updates `socket.io-adapter` from 2.5.6 to 2.5.7
- [Release notes](https://github.com/socketio/socket.io/releases)
- [Changelog](https://github.com/socketio/socket.io/blob/main/CHANGELOG.md)
- [Commits](https://github.com/socketio/socket.io/compare/socket.io-adapter@2.5.6...socket.io-adapter@2.5.7)

---
updated-dependencies:
- dependency-name: ws
  dependency-version: 8.20.1
  dependency-type: indirect
- dependency-name: engine.io
  dependency-version: 6.6.8
  dependency-type: indirect
- dependency-name: socket.io-adapter
  dependency-version: 2.5.7
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

* Improved argument forwarding

* Added support for Electron 42+

* Removed wrongly placed line

* Use path directly

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-08 21:28:22 +02:00
Florian Rappl
0e83af032c Merge branch 'develop' of https://github.com/ElectronNET/Electron.NET into develop 2026-06-07 14:48:15 +02:00
Florian Rappl
1ec84cfef0 Use path directly 2026-06-07 14:48:07 +02:00
Florian Rappl
1620c50627 Merge pull request #1071 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.WebApp/ElectronHostHook/multi-8c9a216550
Bump ws, engine.io and socket.io-adapter in /src/ElectronNET.WebApp/ElectronHostHook
2026-06-07 13:44:13 +02:00
Florian Rappl
295b250e58 Merge pull request #1070 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.Host/multi-8c9a216550
Bump ws, engine.io and socket.io-adapter in /src/ElectronNET.Host
2026-06-07 13:44:04 +02:00
Florian Rappl
644628c803 Merge pull request #1069 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.WebApp/ElectronHostHook/multi-19724e71a7
Bump tmp and exceljs in /src/ElectronNET.WebApp/ElectronHostHook
2026-06-07 13:43:45 +02:00
Florian Rappl
a18944d4a4 Removed wrongly placed line 2026-06-07 13:41:21 +02:00
Florian Rappl
b5858a697a Added support for Electron 42+ 2026-06-07 13:22:25 +02:00
Florian Rappl
58b9ad0125 Improved argument forwarding 2026-06-06 21:10:19 +02:00
dependabot[bot]
e44927a655 Bump ws, engine.io and socket.io-adapter
Bumps [ws](https://github.com/websockets/ws), [engine.io](https://github.com/socketio/socket.io) and [socket.io-adapter](https://github.com/socketio/socket.io). These dependencies needed to be updated together.

Updates `ws` from 8.18.3 to 8.20.1
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](https://github.com/websockets/ws/compare/8.18.3...8.20.1)

Updates `engine.io` from 6.6.5 to 6.6.8
- [Release notes](https://github.com/socketio/socket.io/releases)
- [Changelog](https://github.com/socketio/socket.io/blob/main/CHANGELOG.md)
- [Commits](https://github.com/socketio/socket.io/compare/engine.io@6.6.5...engine.io@6.6.8)

Updates `socket.io-adapter` from 2.5.6 to 2.5.7
- [Release notes](https://github.com/socketio/socket.io/releases)
- [Changelog](https://github.com/socketio/socket.io/blob/main/CHANGELOG.md)
- [Commits](https://github.com/socketio/socket.io/compare/socket.io-adapter@2.5.6...socket.io-adapter@2.5.7)

---
updated-dependencies:
- dependency-name: ws
  dependency-version: 8.20.1
  dependency-type: indirect
- dependency-name: engine.io
  dependency-version: 6.6.8
  dependency-type: indirect
- dependency-name: socket.io-adapter
  dependency-version: 2.5.7
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-29 21:29:26 +00:00
dependabot[bot]
ed9a24bb5e Bump ws, engine.io and socket.io-adapter in /src/ElectronNET.Host
Bumps [ws](https://github.com/websockets/ws), [engine.io](https://github.com/socketio/socket.io) and [socket.io-adapter](https://github.com/socketio/socket.io). These dependencies needed to be updated together.

Updates `ws` from 8.18.3 to 8.20.1
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](https://github.com/websockets/ws/compare/8.18.3...8.20.1)

Updates `engine.io` from 6.6.5 to 6.6.8
- [Release notes](https://github.com/socketio/socket.io/releases)
- [Changelog](https://github.com/socketio/socket.io/blob/main/CHANGELOG.md)
- [Commits](https://github.com/socketio/socket.io/compare/engine.io@6.6.5...engine.io@6.6.8)

Updates `socket.io-adapter` from 2.5.6 to 2.5.7
- [Release notes](https://github.com/socketio/socket.io/releases)
- [Changelog](https://github.com/socketio/socket.io/blob/main/CHANGELOG.md)
- [Commits](https://github.com/socketio/socket.io/compare/socket.io-adapter@2.5.6...socket.io-adapter@2.5.7)

---
updated-dependencies:
- dependency-name: ws
  dependency-version: 8.20.1
  dependency-type: indirect
- dependency-name: engine.io
  dependency-version: 6.6.8
  dependency-type: indirect
- dependency-name: socket.io-adapter
  dependency-version: 2.5.7
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-28 03:59:46 +00:00
dependabot[bot]
94df47efa6 Bump tmp and exceljs in /src/ElectronNET.WebApp/ElectronHostHook
Bumps [tmp](https://github.com/raszi/node-tmp) to 0.2.7 and updates ancestor dependency [exceljs](https://github.com/exceljs/exceljs). These dependencies need to be updated together.


Updates `tmp` from 0.1.0 to 0.2.7
- [Changelog](https://github.com/raszi/node-tmp/blob/master/CHANGELOG.md)
- [Commits](https://github.com/raszi/node-tmp/compare/v0.1.0...v0.2.7)

Updates `exceljs` from 1.15.0 to 4.4.0
- [Release notes](https://github.com/exceljs/exceljs/releases)
- [Commits](https://github.com/exceljs/exceljs/compare/v1.15.0...v4.4.0)

---
updated-dependencies:
- dependency-name: tmp
  dependency-version: 0.2.7
  dependency-type: indirect
- dependency-name: exceljs
  dependency-version: 4.4.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-28 00:35:30 +00:00
Florian Rappl
d9f3da87a8 Merge pull request #1068 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.Host/ElectronHostHook/multi-8c9a216550
Bump ws, engine.io and socket.io-adapter in /src/ElectronNET.Host/ElectronHostHook
2026-05-25 22:22:22 +02:00
dependabot[bot]
a33d76ae2f Bump ws, engine.io and socket.io-adapter
Bumps [ws](https://github.com/websockets/ws), [engine.io](https://github.com/socketio/socket.io) and [socket.io-adapter](https://github.com/socketio/socket.io). These dependencies needed to be updated together.

Updates `ws` from 8.17.1 to 8.20.1
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](https://github.com/websockets/ws/compare/8.17.1...8.20.1)

Updates `engine.io` from 6.6.4 to 6.6.8
- [Release notes](https://github.com/socketio/socket.io/releases)
- [Changelog](https://github.com/socketio/socket.io/blob/main/CHANGELOG.md)
- [Commits](https://github.com/socketio/socket.io/compare/engine.io@6.6.4...engine.io@6.6.8)

Updates `socket.io-adapter` from 2.5.5 to 2.5.7
- [Release notes](https://github.com/socketio/socket.io/releases)
- [Changelog](https://github.com/socketio/socket.io/blob/main/CHANGELOG.md)
- [Commits](https://github.com/socketio/socket.io/compare/socket.io-adapter@2.5.5...socket.io-adapter@2.5.7)

---
updated-dependencies:
- dependency-name: ws
  dependency-version: 8.20.1
  dependency-type: indirect
- dependency-name: engine.io
  dependency-version: 6.6.8
  dependency-type: indirect
- dependency-name: socket.io-adapter
  dependency-version: 2.5.7
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-05-25 20:11:16 +00:00
Florian Rappl
15d6a23016 Merge pull request #1067 from ElectronNET/develop
Release 0.5.0
2026-05-25 22:10:07 +02:00
Florian Rappl
c76ce9702d Merge pull request #1066 from ElectronNET/feature/auth-sample-docs
Added Auth Sample Docs
2026-05-25 21:56:35 +02:00
Florian Rappl
279a823eb7 Improved demo and updated docs 2026-05-25 21:44:07 +02:00
Florian Rappl
fdab81a3a6 Merge branch 'develop' of https://github.com/ElectronNET/Electron.NET into feature/auth-sample-docs 2026-05-25 21:27:52 +02:00
Florian Rappl
558e582789 Updated available lists 2026-05-25 21:18:00 +02:00
Florian Rappl
c4251955d9 Updated changelog 2026-05-25 20:56:21 +02:00
Florian Rappl
af5e70c000 Fixed missing namespace reference 2026-05-25 20:40:18 +02:00
Florian Rappl
fee3806953 Removed flag 2026-05-25 20:37:42 +02:00
Florian Rappl
979b25ffe7 Exclude file-system based transfer from #1038 (#1064) 2026-05-10 19:09:51 +02:00
Florian Rappl
07be82cca6 WIP 2026-05-10 18:21:30 +02:00
Gregor Biswanger
fe939e0fda ci: stop hanging PR workflows and remove duplicate runs (#1063)
- Build and Publish now only triggers on push to main/develop (was: every push), so feature-branch pushes no longer run a second full matrix in parallel to PR Validation.

- integration-tests concurrency group is now scoped per calling workflow (github.workflow + github.ref), preventing PR Validation and Build and Publish from canceling each other's reusable test runs.

- Added timeout-minutes (25 per matrix job, 15 per dotnet test step, 10 for summary job) so a hung Electron process no longer keeps a runner busy until the 6h default timeout, which previously required manual cancel.

- Added --blame-hang --blame-hang-timeout 5min to dotnet test so hung tests produce a dump and fail fast instead of stalling.

- Removed pointless 0-20s random sleep step at the start of every matrix job.
2026-05-09 22:26:43 +02:00
Gregor Biswanger
50c9076af6 fix: replace ReadAllLines with ReadAllText in MigrationChecks.targets… (#1062)
* fix: replace ReadAllLines with ReadAllText in MigrationChecks.targets (fixes #1035)

System.IO.File::ReadAllLines is not available as an MSBuild property function on
all platforms (e.g. macOS GitHub Actions), causing MSB4185.

ReadAllText is universally supported by MSBuild and sufficient for the regex check
that detects 'electron' references in a root package.json (ELECTRON008).
The intermediate ItemGroup for line accumulation is no longer needed.

* test: strengthen migration checks test with exit code assertion and remove reserved MSBuildProjectDirectory override

* test: locate MigrationChecks.targets via directory walk for path robustness

* test: replace em-dashes with ASCII hyphens to avoid bidi/hidden Unicode warning

* test: split build test into clean and electron-containing package.json scenarios
2026-05-09 22:08:36 +02:00
Gregor Biswanger
d7e1a09880 fix: correct ReleaseNotes deserialization for AutoUpdater (fixes #1039) (#1061)
* fix: correct ReleaseNotes deserialization for AutoUpdater (fixes #1039)

- TypeScript normalize() now maps string releaseNotes to { note } objects
  and also handles arrays of strings (both cases were broken in PR #1041)
- Added ReleaseNotesConverter (JsonConverter<ReleaseNoteInfo[]>) as defensive
  C# layer that handles all shapes: null, string, string[], object[]
- Added [JsonConverter] attribute on UpdateInfo.ReleaseNotes
- Added unit tests (no Electron required) covering all four input shapes

* chore: sync generated autoUpdater.js and .map with updated TypeScript source

* refactor: address Copilot PR review comments

- Fix namespace: ElectronNET.Converter -> ElectronNET.API.Converter
- Replace JsonDocument.ParseValue() with JsonSerializer.Deserialize<ReleaseNoteInfo>()
  for cleaner, allocation-free object array parsing
- Fix Write(): empty ReleaseNoteInfo[] now serializes as [] instead of null
- Use Array.Empty<ReleaseNoteInfo>() in UpdateInfo default initializer
- Add tests: Serialize_WithEmptyReleaseNotes and Serialize_WithNullReleaseNotes
2026-05-09 18:17:59 +02:00
dependabot[bot]
30b7b1d251 Bump socket.io-parser in /src/ElectronNET.Host/ElectronHostHook (#1043)
Bumps [socket.io-parser](https://github.com/socketio/socket.io) from 4.2.4 to 4.2.6.
- [Release notes](https://github.com/socketio/socket.io/releases)
- [Changelog](https://github.com/socketio/socket.io/blob/main/CHANGELOG.md)
- [Commits](https://github.com/socketio/socket.io/compare/socket.io-parser@4.2.4...socket.io-parser@4.2.6)

---
updated-dependencies:
- dependency-name: socket.io-parser
  dependency-version: 4.2.6
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: Florian Rappl <mail@florian-rappl.de>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-09 17:30:45 +02:00
dependabot[bot]
e9b3ba0add Bump socket.io-parser in /src/ElectronNET.WebApp/ElectronHostHook (#1044)
Bumps [socket.io-parser](https://github.com/socketio/socket.io) from 4.2.5 to 4.2.6.
- [Release notes](https://github.com/socketio/socket.io/releases)
- [Changelog](https://github.com/socketio/socket.io/blob/main/CHANGELOG.md)
- [Commits](https://github.com/socketio/socket.io/compare/socket.io-parser@4.2.5...socket.io-parser@4.2.6)

---
updated-dependencies:
- dependency-name: socket.io-parser
  dependency-version: 4.2.6
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: Florian Rappl <mail@florian-rappl.de>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-09 17:30:27 +02:00
dependabot[bot]
89f721d1b3 Bump brace-expansion from 1.1.12 to 1.1.14 in /src/ElectronNET.WebApp/ElectronHostHook (#1060)
* Bump lodash in /src/ElectronNET.WebApp/ElectronHostHook (#1056)

Bumps [lodash](https://github.com/lodash/lodash) from 4.17.23 to 4.18.1.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.23...4.18.1)

---
updated-dependencies:
- dependency-name: lodash
  dependency-version: 4.18.1
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Bump brace-expansion in /src/ElectronNET.WebApp/ElectronHostHook

Bumps [brace-expansion](https://github.com/juliangruber/brace-expansion) from 1.1.12 to 1.1.14.
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](https://github.com/juliangruber/brace-expansion/compare/v1.1.12...v1.1.14)

---
updated-dependencies:
- dependency-name: brace-expansion
  dependency-version: 1.1.14
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-09 17:26:55 +02:00
dependabot[bot]
833d288891 Bump lodash from 4.17.23 to 4.18.1 in /src/ElectronNET.Host (#1059)
* Bump lodash in /src/ElectronNET.WebApp/ElectronHostHook (#1056)

Bumps [lodash](https://github.com/lodash/lodash) from 4.17.23 to 4.18.1.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.23...4.18.1)

---
updated-dependencies:
- dependency-name: lodash
  dependency-version: 4.18.1
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Bump lodash from 4.17.23 to 4.18.1 in /src/ElectronNET.Host

Bumps [lodash](https://github.com/lodash/lodash) from 4.17.23 to 4.18.1.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.23...4.18.1)

---
updated-dependencies:
- dependency-name: lodash
  dependency-version: 4.18.1
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-09 17:24:25 +02:00
dependabot[bot]
e529d092c3 Bump lodash in /src/ElectronNET.WebApp/ElectronHostHook (#1056)
Bumps [lodash](https://github.com/lodash/lodash) from 4.17.23 to 4.18.1.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.23...4.18.1)

---
updated-dependencies:
- dependency-name: lodash
  dependency-version: 4.18.1
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-05-09 17:11:36 +02:00
Florian Rappl
11f71feeb8 Automatic Port Selection and Secured Communication (#1038)
Adds dynamic OS-selected socket port handling and secured Electron/.NET communication.

The dotnet-first startup flow now generates the auth token on the .NET side and passes it to Electron through an environment variable. Electron reports the selected socket port through a temporary startup-info file, avoiding any dependency on parsing Electron console output.

Also avoids logging backend startup parameters because they include the auth token.
2026-05-09 17:03:32 +02:00
Florian Rappl
1e8b02648a Merge pull request #1041 from ElectronNET/hotfix/autoupdater-checkforchanges
Fixed Serialization of Release Notes
2026-03-26 10:27:43 +01:00
Florian Rappl
2a14840c6b Merge pull request #1017 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.WebApp/ElectronHostHook/lodash-4.17.23
Bump lodash from 4.17.21 to 4.17.23 in /src/ElectronNET.WebApp/ElectronHostHook
2026-03-26 10:27:18 +01:00
Florian Rappl
005feddcc5 Merge pull request #1049 from AeonSake/1048-hasshadow-true-by-default
Fix `HasShadow` Not Being `true` by Default
2026-03-25 23:31:08 +01:00
Florian Rappl
3f14f9ae7e Merge branch 'develop' into dependabot/npm_and_yarn/src/ElectronNET.WebApp/ElectronHostHook/lodash-4.17.23 2026-03-25 23:30:11 +01:00
Florian Rappl
ce271fd30a Merge pull request #1046 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.Host/flatted-3.4.2
Bump flatted from 3.3.3 to 3.4.2 in /src/ElectronNET.Host
2026-03-25 23:26:37 +01:00
Florian Rappl
1d1b9537b5 Merge pull request #1016 from ElectronNET/dependabot/npm_and_yarn/src/ElectronNET.Host/lodash-4.17.23
Bump lodash from 4.17.21 to 4.17.23 in /src/ElectronNET.Host
2026-03-25 23:25:44 +01:00
Aeon
4c48588ce2 Fix HasShadow not being true by default 2026-03-25 02:37:20 +01:00
dependabot[bot]
c9945a87a9 Bump flatted from 3.3.3 to 3.4.2 in /src/ElectronNET.Host
Bumps [flatted](https://github.com/WebReflection/flatted) from 3.3.3 to 3.4.2.
- [Commits](https://github.com/WebReflection/flatted/compare/v3.3.3...v3.4.2)

---
updated-dependencies:
- dependency-name: flatted
  dependency-version: 3.4.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-21 10:29:48 +00:00
Florian Rappl
8fc197b32a Proposed fix for releaseNotes serialization #1039 2026-03-18 20:12:06 +01:00
Florian Rappl
7930831b6d Added sample for auth 2026-03-18 19:49:48 +01:00
Florian Rappl
201046164c Merge pull request #1037 from ElectronNET/feature/socket-interface
Changed facade to socket connection
2026-03-05 23:18:24 +01:00
Florian Rappl
b8151a2fad Changed facade to socket connection 2026-03-05 11:25:22 +01:00
Florian Rappl
c1bf6d9423 Updated version 2026-03-05 11:13:07 +01:00
dependabot[bot]
f4da9588c9 Bump lodash in /src/ElectronNET.WebApp/ElectronHostHook
Bumps [lodash](https://github.com/lodash/lodash) from 4.17.21 to 4.17.23.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.21...4.17.23)

---
updated-dependencies:
- dependency-name: lodash
  dependency-version: 4.17.23
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-21 23:55:31 +00:00
dependabot[bot]
04c1415f6d Bump lodash from 4.17.21 to 4.17.23 in /src/ElectronNET.Host
Bumps [lodash](https://github.com/lodash/lodash) from 4.17.21 to 4.17.23.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.21...4.17.23)

---
updated-dependencies:
- dependency-name: lodash
  dependency-version: 4.17.23
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-21 23:29:29 +00:00
186 changed files with 65539 additions and 764 deletions

View File

@@ -134,4 +134,16 @@ TL;DR: Unless there is a technical reason (e.g., a crucial new API not being ava
We pretty much release whenever we have something new (i.e., do fixes such as a 0.1.1, or add new features, such as a 0.2.0) quite quickly.
We will go for a 1.0.0 release of this as early as ~mid of January 2026 (unless we find some critical things or want to extend the beta phase for ElectronNET.Core). This should be sufficient time to get some user input and have enough experience to call it stable.
We will go for a 1.0.0 release of this as early as ~mid of June 2026 (unless we find some critical things or want to extend the beta phase for ElectronNET.Core). This should be sufficient time to get some user input and have enough experience to call it stable.
## Updating Electron Versions
The releases of Electron are found on the [releases.electronjs.org](https://releases.electronjs.org/release?page=1) website.
You can update the `src\ElectronNET\build\ElectronNETRules.Project.xaml` file with new entries using the following script (run it in the browser's console when being on the Electron Releases website):
```js
[...new Set([...document.querySelectorAll('tbody tr a[href^="/release/v"]')].map(m => m.getAttribute('href').replace('/release/v', '')))].map(m => `<EnumValue Name="${m}" DisplayName="${m}" />`).sort().join('\n')
```
Alternatively, use the website's information to feed into an AI agent of your choice.

View File

@@ -1,6 +1,8 @@
name: Build and Publish
on: [push]
on:
push:
branches: [main, develop]
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -4,13 +4,14 @@ on:
workflow_call:
concurrency:
group: integration-tests-${{ github.ref }}
group: integration-tests-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
tests:
name: ${{ matrix.os }} API-${{ matrix.electronVersion }}
runs-on: ${{ matrix.os }}
timeout-minutes: 25
strategy:
fail-fast: false
matrix:
@@ -42,13 +43,6 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
- name: Random delay (0-20 seconds)
shell: bash
run: |
DELAY=$((RANDOM % 21))
echo "Waiting for $DELAY seconds..."
sleep $DELAY
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
@@ -79,27 +73,31 @@ jobs:
- name: Run tests (Linux)
if: runner.os == 'Linux'
continue-on-error: true
timeout-minutes: 15
run: |
mkdir -p test-results
xvfb-run -a dotnet test src/ElectronNET.IntegrationTests/ElectronNET.IntegrationTests.csproj \
-c Release --no-build -r ${{ matrix.rid }} -p:RuntimeIdentifier=${{ matrix.rid }} -p:ElectronVersion=${{ matrix.electronVersion }} \
--logger "trx;LogFileName=${{ matrix.os }}-electron-${{ matrix.electronVersion }}.trx" \
--logger "console;verbosity=detailed" \
--blame-hang --blame-hang-timeout 5min \
--results-directory test-results
- name: Run tests (Windows)
if: runner.os == 'Windows'
continue-on-error: true
timeout-minutes: 15
run: |
New-Item -ItemType Directory -Force -Path test-results | Out-Null
dotnet test src/ElectronNET.IntegrationTests/ElectronNET.IntegrationTests.csproj -c Release --no-build -r ${{ matrix.rid }} -p:RuntimeIdentifier=${{ matrix.rid }} -p:ElectronVersion=${{ matrix.electronVersion }} --logger "trx;LogFileName=${{ matrix.os }}-electron-${{ matrix.electronVersion }}.trx" --logger "console;verbosity=detailed" --results-directory test-results
dotnet test src/ElectronNET.IntegrationTests/ElectronNET.IntegrationTests.csproj -c Release --no-build -r ${{ matrix.rid }} -p:RuntimeIdentifier=${{ matrix.rid }} -p:ElectronVersion=${{ matrix.electronVersion }} --logger "trx;LogFileName=${{ matrix.os }}-electron-${{ matrix.electronVersion }}.trx" --logger "console;verbosity=detailed" --blame-hang --blame-hang-timeout 5min --results-directory test-results
- name: Run tests (macOS)
if: runner.os == 'macOS'
continue-on-error: true
timeout-minutes: 15
run: |
mkdir -p test-results
dotnet test src/ElectronNET.IntegrationTests/ElectronNET.IntegrationTests.csproj -c Release --no-build -r ${{ matrix.rid }} -p:RuntimeIdentifier=${{ matrix.rid }} -p:ElectronVersion=${{ matrix.electronVersion }} --logger "trx;LogFileName=${{ matrix.os }}-electron-${{ matrix.electronVersion }}.trx" --logger "console;verbosity=detailed" --results-directory test-results
dotnet test src/ElectronNET.IntegrationTests/ElectronNET.IntegrationTests.csproj -c Release --no-build -r ${{ matrix.rid }} -p:RuntimeIdentifier=${{ matrix.rid }} -p:ElectronVersion=${{ matrix.electronVersion }} --logger "trx;LogFileName=${{ matrix.os }}-electron-${{ matrix.electronVersion }}.trx" --logger "console;verbosity=detailed" --blame-hang --blame-hang-timeout 5min --results-directory test-results
- name: Upload raw test results
if: always()
@@ -114,6 +112,7 @@ jobs:
runs-on: ubuntu-24.04
if: always()
needs: [tests]
timeout-minutes: 10
permissions:
actions: read

View File

@@ -27,7 +27,7 @@ jobs:
run: |
echo "Inspecting jobs of workflow run $RUN_ID in $REPO"
jobs_json="$(gh api -R $REPO repos/$REPO/actions/runs/$RUN_ID/jobs)"
jobs_json="$(gh api repos/$REPO/actions/runs/$RUN_ID/jobs)"
echo "Jobs and conclusions:"
echo "$jobs_json" | jq '.jobs[] | {name: .name, conclusion: .conclusion}'

View File

@@ -1,3 +1,62 @@
# 0.6.0
## ElectronNET.Core
- Updated dependencies
- Updated `WebContents` zoom level APIs to use `double` instead of `int` (#956)
- Improved migration checks to honor custom output paths and to detect `ProjectGuid` in publish profiles (#946)
- Fixed single instance handling on macOS (#1040)
- Fixed slow socket bridge startup by binding to an explicit loopback address (#1103)
- Fixed socket bridge connection when a system proxy is configured (#1105)
- Fixed electron-builder using the host RID instead of the target RID (#1097)
- Fixed cross-compilation behavior on same platform (#1098) @epsnm
- Fixed resolution of unrelated target (#1099) @epsnm
- Fixed false alarm for `ELECTRON001` on a root `package-lock.json` (#946)
- Added `ElectronNET.Core.Templates` package with a `dotnet new electron-blazor` template (#414)
- Added `WebContents.OnZoomChanged` event (#956)
- Added `WebContents` page loading APIs `LoadFileAsync`, `IsLoadingAsync`, `IsLoadingMainFrameAsync`, `IsWaitingForResponseAsync`, `Reload`, `ReloadIgnoringCache` and `Stop` (#956)
- Added `WebContents.InsertCSSAsync` and `WebContents.RemoveInsertedCSSAsync` for dynamic CSS (#956)
- Added `WebContents` editing and selection APIs (undo, redo, cut, copy, paste, insert text, select, ...) (#956)
- Added `WebContents.FindInPageAsync`, `WebContents.StopFindInPage` and the `OnFoundInPage` event (#956)
- Added `WebContents` audio events `OnAudioStateChanged`, `OnMediaStartedPlaying` and `OnMediaPaused` (#956)
- Added `WebContents.ScrollToTop` and `WebContents.ScrollToBottom` (#956)
- Added target framework customization (#1095) @epsnm
- Added configurable Electron root directory for custom packaging layouts (#1106) @DYH1319
- Added ability for `custom_main.js` to modify command line switches (#1029) @AeonSake
- Added migration checks for incomplete `ElectronHostHook` folders (`ELECTRON010`, `ELECTRON011`) (#946)
- Added `ElectronExecutableName` to separate the product name from the executable name (#1003) @AeonSake
- Added build extensibility properties `ElectronSkipExecCommands` and `ElectronIntermediatePublishDir` (#1106) @DYH1319
# 0.5.2
## ElectronNET.Core
- Fixed token param being appended to external URLs (#1075)
- Fixed startup mode discriminator in case of existing `wwwroot` (#1050)
- Fixed CA1416 on ASP.NET project (#1091) @epsnm
- Fixed loading issue in plain Visual Studio (#1084) @epsnm
- Fixed bloated ASAR file (#1080) @epsnm
- Improved selection of runtime identifier (#1081) @epsnm
- Added more variants for `UseElectron` (#1076) @AeonSake
- Added support for modern MacOS app icon (#1047)
# 0.5.1
## ElectronNET.Core
- Fixed slicing of arguments for packaged applications (#1072)
- Added support for Electron 42+ (#1073)
# 0.5.0
## ElectronNET.Core
- Updated internal facade from `SocketIoFacade` to `ISocketConnection` (#1037)
- Fixed `HasShadow` is not `true` by default (#1049) @AeonSake
- Fixed missing `ReadAllLines` in MSBuild execution (#1035)
- Fixed serialization of release notes for the updater (#1041)
- Added automatic port selection and secured IPC communication (#1038)
# 0.4.1
## ElectronNET.Core

15
Directory.Build.props Normal file
View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- This file prevents unintended imports of unrelated MSBuild files -->
<!-- Uncomment to include parent Directory.Build.props file -->
<!--<Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" />-->
<PropertyGroup>
<ElectronNetBuildProps>$([MSBuild]::GetPathOfFileAbove('ElectronNet.Build.props', '$(MSBuildThisFileDirectory)../'))</ElectronNetBuildProps>
</PropertyGroup>
<!-- Only import specific project related MSBuild file -->
<Import Project="$(ElectronNetBuildProps)" Condition=" '$(ElectronNetBuildProps)' != '' " />
</Project>

View File

@@ -2,7 +2,7 @@
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- This file prevents unintended imports of unrelated MSBuild files -->
<!-- Uncomment to include parent Directory.Build.props file -->
<!--<Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" />-->
<!-- Uncomment to include parent Directory.Packages.props file -->
<!--<Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Packages.props', '$(MSBuildThisFileDirectory)../'))" />-->
</Project>

View File

@@ -23,13 +23,14 @@ While the classic Electron.NET setup (using an ASP.NET host run by the Electron
* ElectronNET.Core: [![NuGet](https://img.shields.io/nuget/v/ElectronNET.Core.svg?style=flat-square)](https://www.nuget.org/packages/ElectronNET.Core.API/)
* ElectronNET.Core.API: [![NuGet](https://img.shields.io/nuget/v/ElectronNET.Core.API.svg?style=flat-square)](https://www.nuget.org/packages/ElectronNET.Core.API/)
* ElectronNET.Core.AspNet: [![NuGet](https://img.shields.io/nuget/v/ElectronNET.Core.AspNet.svg?style=flat-square)](https://www.nuget.org/packages/ElectronNET.Core.AspNet/)
* ElectronNET.Core.Templates: [![NuGet](https://img.shields.io/nuget/v/ElectronNET.Core.Templates.svg?style=flat-square)](https://www.nuget.org/packages/ElectronNET.Core.Templates/)
## 🛠 Requirements to Run
You should have installed:
* .NET 6/8 or later.
* The minimum base OS is the same as [.NET 6](https://github.com/dotnet/core/blob/main/release-notes/6.0/supported-os.md) / [.NET 8](https://github.com/dotnet/core/blob/main/release-notes/8.0/supported-os.md).
* .NET 8/10 or later.
* The minimum base OS is the same as [.NET 8](https://github.com/dotnet/core/blob/main/release-notes/8.0/supported-os.md) / [.NET 10](https://github.com/dotnet/core/blob/main/release-notes/10.0/supported-os.md).
* Node.JS using at least [Version 22.x](https://nodejs.org).
## 👩‍🏫 Usage with ASP.NET
@@ -202,6 +203,8 @@ Alternatively, consider using a GitHub sponsorship for the core maintainers:
- [Gregor Biswanger](https://github.com/sponsors/GregorBiswanger)
- [Florian Rappl](https://github.com/sponsors/FlorianRappl)
Or just [buy Florian a coffee](https://buymeacoffee.com/florianrappl) :coffee:.
Any support appreciated! 🍻
## 🎉 License

View File

@@ -58,6 +58,23 @@ Works for both BrowserWindows and BrowserViews.
- `isBrowserWindow` - Whether the webContents belong to a BrowserWindow or not (the other option is a BrowserView)
- `path` - Absolute path to the CSS file location
#### 🧊 `Task<string> InsertCSSAsync(string css, string cssOrigin = null)`
Injects CSS into the current web page and returns a unique key for the inserted style sheet.
**Parameters:**
- `css` - The style sheet to inject
- `cssOrigin` - Can be either `user` or `author`, defaults to `author`
**Returns:**
The key of the inserted style sheet, to be used with `RemoveInsertedCSSAsync`.
#### 🧊 `Task RemoveInsertedCSSAsync(string key)`
Removes a previously inserted style sheet from the current web page.
**Parameters:**
- `key` - The key returned by `InsertCSSAsync`
#### 🧊 `Task LoadURLAsync(string url)`
Loads the url in the window. The url must contain the protocol prefix.
@@ -113,6 +130,106 @@ Prints window's web page as PDF with Chromium's preview printing custom settings
Whether the PDF generation succeeded.
#### 🧊 `Task<double> GetZoomFactorAsync()`
Returns the current zoom factor. A factor of `1.0` means 100%.
#### 🧊 `void SetZoomFactor(double factor)`
Changes the zoom factor to the specified factor. The zoom factor is the zoom percent divided by 100, so 300% = `3.0`. The factor must be greater than `0.0`.
**Parameters:**
- `factor` - The zoom factor
#### 🧊 `Task<double> GetZoomLevelAsync()`
Returns the current zoom level.
#### 🧊 `void SetZoomLevel(double level)`
Changes the zoom level to the specified level. The original size is `0` and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of the original size, respectively.
**Parameters:**
- `level` - The zoom level
#### 🧊 `Task SetVisualZoomLevelLimitsAsync(double minimumLevel, double maximumLevel)`
Sets the maximum and minimum pinch-to-zoom level.
**Parameters:**
- `minimumLevel` - The minimum pinch-to-zoom level
- `maximumLevel` - The maximum pinch-to-zoom level
#### 🧊 `Task LoadFileAsync(string filePath, LoadFileOptions options = null)`
Loads the given HTML file, relative to the root of the application.
**Parameters:**
- `filePath` - Path to the HTML file
- `options` - Optional `Query`, `Search` and `Hash` parts of the resulting URL
#### 🧊 `void SetAudioMuted(bool muted)`
Mutes or unmutes the audio on the current web page.
#### 🧊 `Task<bool> IsAudioMutedAsync()`
Whether this page has been muted.
#### 🧊 `Task<bool> IsCurrentlyAudibleAsync()`
Whether audio is currently playing.
#### 🧊 `Task<string> GetUserAgentAsync()` / `void SetUserAgent(string userAgent)`
Gets or overrides the user agent for this web page.
#### 🧊 `Task<bool> IsLoadingAsync()`
Whether the web page is still loading resources.
#### 🧊 `Task<bool> IsLoadingMainFrameAsync()`
Whether the main frame (and not just iframes or frames within it) is still loading.
#### 🧊 `Task<bool> IsWaitingForResponseAsync()`
Whether the web page is waiting for a first response from the main resource of the page.
#### 🧊 `void Reload()`
Reloads the current web page.
#### 🧊 `void ReloadIgnoringCache()`
Reloads the current web page and ignores the cache.
#### 🧊 `void Stop()`
Stops any pending navigation.
#### 🧊 `void Undo()` / `void Redo()`
Executes the `undo` / `redo` editing command in the web page.
#### 🧊 `void Cut()` / `void Copy()` / `void Paste()` / `void PasteAndMatchStyle()` / `void Delete()`
Executes the corresponding editing command in the web page.
#### 🧊 `void CopyImageAt(int x, int y)`
Copies the image at the given position to the clipboard.
#### 🧊 `void SelectAll()` / `void Unselect()` / `void CenterSelection()`
Selects all content, clears the selection, or scrolls to the current selection.
#### 🧊 `void ScrollToTop()` / `void ScrollToBottom()`
Scrolls to the top or the bottom of the current web page.
#### 🧊 `void AdjustSelection(AdjustSelectionOptions options)`
Adjusts the start and end points of the current text selection by the given amounts. Negative amounts move towards the beginning of the document.
#### 🧊 `Task InsertTextAsync(string text)`
Inserts text into the focused element.
#### 🧊 `void Replace(string text)` / `void ReplaceMisspelling(string text)`
Replaces the current selection, or the currently misspelled word, with the given text.
#### 🧊 `Task<int> FindInPageAsync(string text, FindInPageOptions options = null)`
Starts a request to find all matches for the text in the web page. Results are reported via the `OnFoundInPage` event.
**Parameters:**
- `text` - Content to be searched, must not be empty
- `options` - Optional `Forward`, `FindNext` and `MatchCase` flags
**Returns:**
The request id of the find request.
#### 🧊 `void StopFindInPage(StopFindInPageAction action)`
Stops any `FindInPageAsync` request with the given action (`ClearSelection`, `KeepSelection` or `ActivateSelection`).
## Events
#### ⚡ `InputEvent`
@@ -142,6 +259,21 @@ Emitted when the document in the top-level frame is loaded.
#### ⚡ `OnWillRedirect`
Emitted when a server side redirect occurs during navigation.
#### ⚡ `OnZoomChanged`
Emitted when the user changes the zoom level using the mouse wheel or the keyboard. The handler receives the `ZoomDirection` (`In` or `Out`).
#### ⚡ `OnFoundInPage`
Emitted when a result is available for a `FindInPageAsync` request. The handler receives a `FoundInPageResult`.
#### ⚡ `OnAudioStateChanged`
Emitted when media becomes audible or inaudible. The handler receives `true` if one or more frames or child web contents are emitting audio.
#### ⚡ `OnMediaStartedPlaying`
Emitted when media starts playing.
#### ⚡ `OnMediaPaused`
Emitted when media is paused or done playing.
## Usage Examples
### Page Loading
@@ -279,6 +411,82 @@ webContents.OnCrashed += (killed) =>
};
```
### Zoom Control
```csharp
// Set the zoom to 150%
webContents.SetZoomFactor(1.5);
var factor = await webContents.GetZoomFactorAsync();
Console.WriteLine($"Current zoom: {factor * 100}%");
// Zoom levels are relative: each step is 20% larger/smaller, 0 is the original size
webContents.SetZoomLevel(2);
// Restrict pinch-to-zoom
await webContents.SetVisualZoomLevelLimitsAsync(1, 3);
// React to zoom changes triggered by the user
webContents.OnZoomChanged += (direction) =>
{
Console.WriteLine($"User zoomed {direction}");
};
```
> **Note:** The zoom factor is shared by all windows using the same session partition. Assign a unique `WebPreferences.Partition` per window if each window should keep its own zoom.
### Dynamic CSS
```csharp
var key = await webContents.InsertCSSAsync("body { background-color: #202020; }");
// ... later
await webContents.RemoveInsertedCSSAsync(key);
```
### Editing and Selection
```csharp
await webContents.InsertTextAsync("Hello from .NET");
webContents.SelectAll();
webContents.Copy();
webContents.Unselect();
```
### Find in Page
```csharp
webContents.OnFoundInPage += (result) =>
{
Console.WriteLine($"{result.ActiveMatchOrdinal}/{result.Matches} matches");
if (result.FinalUpdate)
{
webContents.StopFindInPage(StopFindInPageAction.ClearSelection);
}
};
var requestId = await webContents.FindInPageAsync("electron", new FindInPageOptions { MatchCase = false });
```
### Audio
```csharp
webContents.SetAudioMuted(true);
var muted = await webContents.IsAudioMutedAsync();
var audible = await webContents.IsCurrentlyAudibleAsync();
webContents.OnAudioStateChanged += (isAudible) =>
{
Console.WriteLine(isAudible ? "Page started emitting audio" : "Page went silent");
};
webContents.OnMediaStartedPlaying += () => Console.WriteLine("Media playing");
webContents.OnMediaPaused += () => Console.WriteLine("Media paused");
```
## Related APIs
- [Electron.WindowManager](WindowManager.md) - Windows containing web contents

View File

@@ -17,6 +17,10 @@ When you build an Electron.NET project, the following validation checks are perf
| [ELECTRON005](#4-parent-paths-not-allowed-in-electron-builderjson) | Parent paths not allowed | Checks for `..` references in config |
| [ELECTRON006](#5-publish-profile-validation) | ASP.NET publish profile mismatch | Warns when ASP.NET projects have console-style profiles |
| [ELECTRON007](#5-publish-profile-validation) | Console publish profile mismatch | Warns when console projects have ASP.NET-style profiles |
| [ELECTRON010](#6-electronhosthook-folder-validation) | ElectronHostHook without package.json | Warns when hook TypeScript files exist without a `package.json` |
| [ELECTRON011](#6-electronhosthook-folder-validation) | ElectronHostHook without tsconfig.json | Warns when hook TypeScript files exist without a `tsconfig.json` |
All checks skip the build output folders (`bin`, `obj`, `publish`, `.electron`, `node_modules`) as well as any custom output paths configured via `BaseOutputPath` / `BaseIntermediateOutputPath` (for example the .NET `artifacts` output layout).
---
@@ -32,7 +36,7 @@ Rules:
- **ELECTRON001**: `package.json` / `package-lock.json` must not exist in the project directory or subdirectories
- Exception: `ElectronHostHook` folder is allowed
- Note: a **root** `package.json` is **excluded** from `ELECTRON001` and validated by `ELECTRON008` / `ELECTRON009`
- Note: a **root** `package.json` (and its `package-lock.json`) is **excluded** from `ELECTRON001` and validated by `ELECTRON008` / `ELECTRON009`
- **ELECTRON008**: If a root `package.json` exists, it must **not** contain electron-related dependencies or configuration.
@@ -113,6 +117,10 @@ The `electron.manifest.json` file format is deprecated. All configuration should
"mac": {
"icon": "Assets/app.icns",
"target": ["dmg", "zip"]
},
"nsis": {
"oneClick": true,
"perMachine": false
}
}
```
@@ -208,7 +216,7 @@ The build system examines `.pubxml` files in the `Properties/PublishProfiles` fo
- **ELECTRON006**: For **ASP.NET projects** (using `Microsoft.NET.Sdk.Web`), checks that publish profiles include `WebPublishMethod`. This property is required for proper ASP.NET publishing.
- **ELECTRON007**: For **console/other projects** (not using the Web SDK), checks that publish profiles do NOT include the `WebPublishMethod` property. These ASP.NET-specific properties are incorrect for non-web applications.
- **ELECTRON007**: For **console/other projects** (not using the Web SDK), checks that publish profiles do NOT include the `WebPublishMethod` or `ProjectGuid` property. These ASP.NET-specific properties are incorrect for non-web applications.
### Why this matters
@@ -233,9 +241,54 @@ For correct publish profile examples for both ASP.NET and Console applications,
---
## 6. ElectronHostHook Folder Validation
**Warning Codes:** `ELECTRON010`, `ELECTRON011`
### What is checked
If the project contains an `ElectronHostHook` folder with TypeScript files:
- **ELECTRON010**: The folder must contain a `package.json`
- **ELECTRON011**: The folder must contain a `tsconfig.json`
### Why this matters
Custom host hook code is only compiled and packaged when the `ElectronHostHook` folder declares its npm dependencies in a `package.json`. If that file is missing, the hook is silently dropped and the corresponding `Electron.HostHook` calls fail at runtime. The `tsconfig.json` is required so the hook sources are compiled with the expected settings.
### How to fix
Add the missing files to the `ElectronHostHook` folder:
```json
{
"name": "electron-host-hook",
"version": "1.0.0",
"main": "index.js",
"dependencies": {
"socket.io": "^4.8.1"
},
"devDependencies": {
"typescript": "^5.9.3"
}
}
```
> **See also:** [HostHook API](../API/HostHook.md)
---
## Disabling Migration Checks
If you need to disable specific migration checks (not recommended), you can set the following properties in your `.csproj` file:
Individual checks can be downgraded to messages by their warning code:
```xml
<PropertyGroup>
<MSBuildWarningsAsMessages>$(MSBuildWarningsAsMessages);ELECTRON005</MSBuildWarningsAsMessages>
</PropertyGroup>
```
If you need to disable all migration checks (not recommended), you can set the following property in your `.csproj` file:
```xml
<PropertyGroup>

View File

@@ -48,17 +48,19 @@ You can also manually edit `electron-builder.json`:
```json
{
"linux": {
"target": [
"tar.xz"
]
"target": ["tar.xz"]
},
"win": {
"target": [
{
"target": "portable",
"target": "nsis",
"arch": "x64"
}
]
},
"nsis": {
"oneClick": true,
"perMachine": false
}
}
```

View File

@@ -10,6 +10,11 @@ See [System Requirements](../GettingStarted/System-Requirements.md).
## 🚀 Quick Start
> [!Tip]
> To skip the manual setup below, scaffold a ready-to-run app with the
> [project templates](Templates.md): `dotnet new install ElectronNET.Core.Templates` followed by
> `dotnet new electron-blazor -n MyDesktopApp`.
### 1. Create ASP.NET Core Project
#### Visual Studio

View File

@@ -54,7 +54,7 @@ Add the Electron.NET configuration to your `.csproj` file:
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ElectronNET.Core" Version="0.4.1" />
<PackageReference Include="ElectronNET.Core" Version="0.6.0" />
</ItemGroup>
```

View File

@@ -0,0 +1,88 @@
# Project Templates
Electron.NET ships a `dotnet new` template package so you can scaffold a ready-to-run desktop app instead of wiring up an ASP.NET project by hand.
## 🛠 System Requirements
See [System Requirements](../GettingStarted/System-Requirements.md).
## 📦 Install the Templates
```bash
dotnet new install ElectronNET.Core.Templates
```
To update to the latest version, run the same command again. To remove them:
```bash
dotnet new uninstall ElectronNET.Core.Templates
```
## 🚀 Available Templates
| Template | Short name | Description |
|----------|------------|-------------|
| Electron.NET Blazor App | `electron-blazor` | A Blazor Server app hosted in an Electron shell |
## 🧱 Create a Blazor App
```bash
dotnet new electron-blazor -n MyDesktopApp
cd MyDesktopApp
```
Then start it in the Electron shell:
```bash
dotnet build
dotnet run
```
### Options
| Option | Values | Default | Description |
|--------|--------|---------|-------------|
| `-f`, `--framework` | `net8.0`, `net10.0` | `net10.0` | The target framework of the generated project |
| `-e`, `--electron-version` | any Electron version | `38.2.2` | The Electron version the app is built against |
| `-p`, `--port` | port number | `8001` | The port the ASP.NET server uses during development |
| `--no-restore` | — | — | Skip the automatic `dotnet restore` |
Example:
```bash
dotnet new electron-blazor -n MyDesktopApp -f net10.0 -e 30.4.0 -p 8123
```
## 📁 What You Get
```
MyDesktopApp/
├── Components/
│ ├── Layout/ MainLayout.razor, NavMenu.razor
│ ├── Pages/ Home.razor, Counter.razor
│ ├── App.razor
│ ├── Routes.razor
│ └── _Imports.razor
├── Properties/
│ ├── PublishProfiles/ win-x64, linux-x64 and osx-arm64 folder profiles
│ ├── electron-builder.json
│ └── launchSettings.json
├── wwwroot/app.css
├── appsettings.json
├── Program.cs
└── MyDesktopApp.csproj
```
The project already references `ElectronNET.Core` and `ElectronNET.Core.AspNet`, calls `builder.UseElectron(...)` in `Program.cs`, and passes all [Migration Checks](../Core/Migration-Checks.md) out of the box.
> [!Note]
> `ElectronNET.API` also defines a type named `App`, which collides with the Blazor root
> component. That is why the template calls `app.MapRazorComponents<MyDesktopApp.Components.App>()`
> with a fully qualified type name.
## 🚀 Next Steps
- **[Configuration](../Using/Configuration.md)** - Adjust app metadata and Electron settings
- **[Debugging](../Using/Debugging.md)** - Debug the .NET and Electron sides
- **[Package Building](../Using/Package-Building.md)** - Create distributable packages

View File

@@ -28,9 +28,77 @@ These are the current default values when you don't make any changes:
<ElectronPackageId>$(MSBuildProjectName.Replace(".", "-").ToLower())</ElectronPackageId>
<ElectronBuilderJson>electron-builder.json</ElectronBuilderJson>
<Title>$(MSBuildProjectName)</Title>
<ElectronExecutableName></ElectronExecutableName>
<ElectronRootDir>../..</ElectronRootDir>
<ElectronSkipExecCommands>false</ElectronSkipExecCommands>
</PropertyGroup>
```
### Product Name and Executable Name
`Title` is the product name of the application. It is used for the window title, the installer, the macOS app bundle and the Linux desktop entry, and it may contain spaces and other characters that are awkward in a file name.
`ElectronExecutableName` controls the name of the executable inside the package (electron-builder's `executableName`). When it is not set, it defaults to the following behavior:
| Target | Default |
| --- | --- |
| Windows | `$(Title)` |
| Linux / macOS | `$(ElectronPackageId)` |
So to ship a product called `My Great App` with a `mygreatapp` binary on every platform:
```xml
<PropertyGroup>
<Title>My Great App</Title>
<ElectronExecutableName>mygreatapp</ElectronExecutableName>
</PropertyGroup>
```
> [!NOTE]
> `ElectronExecutable` is a separate, advanced setting: it is the binary Electron.NET launches when the .NET app starts first. It defaults to `ElectronExecutableName` and only needs to be changed when the package contains a launcher stub (for example added by an electron-builder hook) that should be started instead of the Electron binary.
### Custom Packaging Layout
`ElectronRootDir` tells the .NET app where to find the Electron binary when it is started first (DotNet-First startup of a packaged app). The path is resolved relative to the directory of the .NET executable; absolute paths are used as-is.
The default `../..` matches the standard Electron-First packaging layout produced by `dotnet publish`, where the .NET app is placed in `resources/bin` of the Electron package:
```
<install-root>/
MyApp # Electron executable
resources/
bin/
MyApp # .NET executable
```
If your own packaging pipeline places the .NET executable at the package root and Electron in a subdirectory, set `ElectronRootDir` accordingly:
```xml
<ElectronRootDir>electron</ElectronRootDir>
```
```
<install-root>/
MyApp # .NET executable
electron/
MyApp # Electron executable
resources/
locales/
```
The property is also used to detect whether the app runs packaged or unpackaged, so it must point to the directory that actually contains the Electron binary.
### Build Extensibility
These properties are useful when Electron.NET is embedded into a custom build or CI pipeline:
| Property | Default | Description |
| --- | --- | --- |
| `ElectronSkipExecCommands` | `false` | Skips all `npm`/`npx` invocations of the Electron build and publish targets. Use it when the dependencies and the Electron distribution are provided by the pipeline itself (for example from a cache or an offline mirror). |
| `ElectronIntermediatePublishDir` | `$(IntermediateOutputPath)PubTmp\` | Overrides the intermediate directory the .NET app is published to before it is assembled into the Electron package. |
`ElectronPackageId` and `Title` only fall back to the project name when they are not already set, so both can be defined by a `Directory.Build.props` or passed on the command line.
### Relation to package.json
ElectronNET.Core does not work with an `electron-manifest.json` file anymore.
@@ -42,11 +110,17 @@ Since electron builder still expects a `package.json` file to exist, ElectronNET
"productName": "$(ElectronTitle)",
"build": {
"appId": "$(ElectronPackageId)",
"win": {
"executableName": "$(ElectronExecutableName)"
},
"mac": {
"executableName": "$(ElectronExecutableName)"
},
"linux": {
"desktop": {
"entry": { "Name": "$(Title)" }
},
"executableName": "$(ElectronPackageId)"
"executableName": "$(ElectronExecutableName)"
},
"deb": {
"desktop": {
@@ -70,6 +144,12 @@ Since electron builder still expects a `package.json` file to exist, ElectronNET
}
```
### App Icon Path
The `ElectronIcon` property supports classic icon files (such as `.ico` and `.icns`) and modern macOS `.icon` app icon packages.
For `.icon`, provide the folder path (for example `Assets/MyApp.icon`). During build/publish, Electron.NET copies the full directory into the Electron output so `electron-builder.json` can reference it (for example `"mac": { "icon": "MyApp.icon" }`).
### Node.js Integration
Electron.NET requires Node.js integration to be enabled for IPC to function. If you are not using the IPC functionality you can disable Node.js integration like so:

View File

@@ -7,6 +7,7 @@ This guide explains how to include and use a `custom_main.js` file in your Elect
- Register custom protocol handlers (e.g., `myapp://`) — protocols must be registered before the app is fully initialized
- Integrate Node.js modules (e.g., telemetry, OS APIs)
- Control startup logic (abort, environment checks)
- Modify Chromium / Electron.NET command line switches before they are evaluated
- Set up IPC messaging or preload scripts
## Step-by-Step Process
@@ -65,10 +66,29 @@ Use environment variables to control features:
if (env === 'Development') { /* enable dev features */ }
```
### Modifying Command Line Switches
`onStartup` is invoked before Electron.NET reads any of its own switches (`manifest`, `unpackedelectron`, `unpackeddotnet`, `dotnetpacked`, `electronforcedport`, `electronurl`), so the hook can append or override them:
```javascript
module.exports.onStartup = function (host) {
const { app } = require('electron');
// Force a fixed socket bridge port
app.commandLine.appendSwitch('electronforcedport', '8000');
// Chromium switches, e.g. to disable the GPU sandbox
app.commandLine.appendSwitch('disable-gpu-sandbox');
return true;
};
```
## Notes
- `custom_main.js` must use CommonJS syntax (`module.exports.onStartup = ...`).
- Place the file in your source directory and copy it to `.electron` using `.csproj`.
- Electron.NET will abort startup if `onStartup` returns `false`.
- `onStartup` runs before the Electron.NET command line switches are evaluated, so switches set there are picked up by the host.
### Complete example is available here [ElectronNetSampleApp](https://github.com/niteshsinghal85/ElectronNetSampleApp)

View File

@@ -222,6 +222,15 @@ The publish process will:
> macOS builds can't be created on Windows machines because they require symlinks that aren't supported on Windows (per [this Electron issue](https://github.com/electron-userland/electron-packager/issues/71)). macOS builds can be produced on either Linux or macOS machines.
## Custom Packaging Pipelines
The default layout is Electron-First: electron-builder produces the Electron package and the .NET app is placed in `resources/bin`. If you assemble the package yourself and put the .NET executable at the package root with Electron in a subdirectory, set `ElectronRootDir` so the .NET app can locate the Electron binary at runtime.
For pipelines that provide the npm dependencies themselves, `ElectronSkipExecCommands` suppresses all `npm`/`npx` invocations, and `ElectronIntermediatePublishDir` redirects the intermediate publish output.
See [Configuration](Configuration.md#custom-packaging-layout) for details.
## 🚀 Next Steps
- **[Startup Methods](Startup-Methods.md)** - Understanding different launch modes for packaged apps

View File

@@ -0,0 +1,32 @@
# Secure Communication
By default, the IPC communication between .NET and Node.js is secured on startup. Consequently, multiple instances running on different user accounts (but shared on the same machine) can safely co-exist. However, this protection is not enough to secure the web application behind - or make any security statement w.r.t. a malicious root user.
## Securing the Web Application
You can opt-in to also guard your ASP.NET Core application using the same mechanism that is already used to protected the IPC broker that deals with the .NET to Node.js communication.
The key to opt-in is to provide another service *before* calling `AddElectron` on the service collection.
The following two namespaces are used in the next instructions:
```cs
using ElectronNET.AspNet.Middleware;
using ElectronNET.AspNet.Services;
```
You'll need the following line:
```cs
builder.Services.AddSingleton<IElectronAuthenticationService, ElectronAuthenticationService>();
```
This way, Electron.NET is notified that you want to store and re-use the authentication token that has been negotiated between the .NET and Node.js processes at startup.
With this being set up you can register a middleware to actually deny requests that have originated outside of your Electron.NET application:
```cs
app.UseMiddleware<ElectronAuthenticationMiddleware>();
```
This must be placed above any routing (e.g., before calling `UseRouting` on the web application) in order to properly take effect.

View File

@@ -15,6 +15,7 @@
# Getting Started
- [System Requirements](GettingStarted/System-Requirements.md)
- [Project Templates](GettingStarted/Templates.md)
- [With ASP.Net](GettingStarted/ASP.Net.md)
- [With a Console App](GettingStarted/Console-App.md)
@@ -24,6 +25,7 @@
- [Startup-Methods](Using/Startup-Methods.md)
- [Debugging](Using/Debugging.md)
- [Package Building](Using/Package-Building.md)
- [Secure Communication](Using/Secure-Communication.md)
- [Adding a `custom_main.js`](Using/Custom_main.md)
# API Reference

View File

@@ -0,0 +1,18 @@
namespace ElectronNET.API.Entities
{
/// <summary>
/// Options for <see cref="WebContents.AdjustSelection"/>.
/// </summary>
public class AdjustSelectionOptions
{
/// <summary>
/// Amount to shift the start index of the current selection.
/// </summary>
public int? Start { get; set; }
/// <summary>
/// Amount to shift the end index of the current selection.
/// </summary>
public int? End { get; set; }
}
}

View File

@@ -215,7 +215,8 @@ namespace ElectronNET.API.Entities
/// <summary>
/// Whether window should have a shadow. Default is true.
/// </summary>
public bool HasShadow { get; set; }
[DefaultValue(true)]
public bool HasShadow { get; set; } = true;
/// <summary>
/// Forces using dark theme for the window, only works on some GTK+3 desktop environments. Default is false.

View File

@@ -0,0 +1,24 @@
namespace ElectronNET.API.Entities
{
/// <summary>
/// Options for <see cref="WebContents.FindInPageAsync"/>.
/// </summary>
public class FindInPageOptions
{
/// <summary>
/// Whether to search forward or backward, defaults to true.
/// </summary>
public bool? Forward { get; set; }
/// <summary>
/// Whether to begin a new text finding session with this request. Should be true
/// for initial requests, and false for subsequent requests. Defaults to false.
/// </summary>
public bool? FindNext { get; set; }
/// <summary>
/// Whether search should be case-sensitive, defaults to false.
/// </summary>
public bool? MatchCase { get; set; }
}
}

View File

@@ -0,0 +1,33 @@
namespace ElectronNET.API.Entities
{
/// <summary>
/// The result of a text finding session, reported by the found-in-page event.
/// </summary>
public class FoundInPageResult
{
/// <summary>
/// The identifier of the request returned by FindInPageAsync.
/// </summary>
public int RequestId { get; set; }
/// <summary>
/// Position of the active match.
/// </summary>
public int ActiveMatchOrdinal { get; set; }
/// <summary>
/// Number of matches.
/// </summary>
public int Matches { get; set; }
/// <summary>
/// Coordinates of the first match region.
/// </summary>
public Rectangle SelectionArea { get; set; }
/// <summary>
/// Indicates whether more responses are to follow.
/// </summary>
public bool FinalUpdate { get; set; }
}
}

View File

@@ -0,0 +1,25 @@
using System.Collections.Generic;
namespace ElectronNET.API.Entities
{
/// <summary>
/// Options for loading a local file into a web page.
/// </summary>
public class LoadFileOptions
{
/// <summary>
/// Passed to url.format().
/// </summary>
public Dictionary<string, string> Query { get; set; }
/// <summary>
/// Passed to url.format().
/// </summary>
public string Search { get; set; }
/// <summary>
/// Passed to url.format().
/// </summary>
public string Hash { get; set; }
}
}

View File

@@ -0,0 +1,23 @@
namespace ElectronNET.API.Entities
{
/// <summary>
/// Determines what happens to the selection when a text finding session is stopped.
/// </summary>
public enum StopFindInPageAction
{
/// <summary>
/// Clear the selection.
/// </summary>
ClearSelection,
/// <summary>
/// Translate the selection into a normal selection.
/// </summary>
KeepSelection,
/// <summary>
/// Focus and click the selection node.
/// </summary>
ActivateSelection
}
}

View File

@@ -1,4 +1,8 @@
namespace ElectronNET.API.Entities
using System;
using System.Text.Json.Serialization;
using ElectronNET.API.Converter;
namespace ElectronNET.API.Entities
{
/// <summary>
///
@@ -24,7 +28,8 @@
/// <summary>
/// Gets or sets the release notes.
/// </summary>
public ReleaseNoteInfo[] ReleaseNotes { get; set; } = new ReleaseNoteInfo[0];
[JsonConverter(typeof(ReleaseNotesConverter))]
public ReleaseNoteInfo[] ReleaseNotes { get; set; } = Array.Empty<ReleaseNoteInfo>();
/// <summary>
/// Gets or sets the release date.

View File

@@ -0,0 +1,18 @@
namespace ElectronNET.API.Entities
{
/// <summary>
/// The direction of a zoom change triggered by the user.
/// </summary>
public enum ZoomDirection
{
/// <summary>
/// The user zoomed in.
/// </summary>
In,
/// <summary>
/// The user zoomed out.
/// </summary>
Out
}
}

View File

@@ -113,6 +113,52 @@ public class WebContents : ApiBase
remove => RemoveEvent(value, Id);
}
/// <summary>
/// Emitted when the user is requesting to change the zoom level using the mouse wheel or the keyboard.
/// </summary>
public event Action<ZoomDirection> OnZoomChanged
{
add => AddEvent(value, Id);
remove => RemoveEvent(value, Id);
}
/// <summary>
/// Emitted when a result is available for a <see cref="FindInPageAsync(string, FindInPageOptions)"/> request.
/// </summary>
public event Action<FoundInPageResult> OnFoundInPage
{
add => AddEvent(value, Id);
remove => RemoveEvent(value, Id);
}
/// <summary>
/// Emitted when media becomes audible or inaudible. The parameter is true if one or more
/// frames or child web contents are emitting audio.
/// </summary>
public event Action<bool> OnAudioStateChanged
{
add => AddEvent(value, Id);
remove => RemoveEvent(value, Id);
}
/// <summary>
/// Emitted when media starts playing.
/// </summary>
public event Action OnMediaStartedPlaying
{
add => AddEvent(value, Id);
remove => RemoveEvent(value, Id);
}
/// <summary>
/// Emitted when media is paused or done playing.
/// </summary>
public event Action OnMediaPaused
{
add => AddEvent(value, Id);
remove => RemoveEvent(value, Id);
}
internal WebContents(int id)
{
Id = id;
@@ -304,6 +350,68 @@ public class WebContents : ApiBase
return tcs.Task;
}
/// <summary>
/// Loads the given file in the window. The file path must be a path to an HTML file
/// relative to the root of your application.
/// </summary>
/// <param name="filePath">Path to the HTML file.</param>
/// <param name="options">Optional query, search and hash parts of the resulting URL.</param>
public Task LoadFileAsync(string filePath, LoadFileOptions options = null)
{
var tcs = new TaskCompletionSource();
BridgeConnector.Socket.Once("webContents-loadFile-complete" + Id, () =>
{
BridgeConnector.Socket.Off("webContents-loadFile-error" + Id);
tcs.SetResult();
});
BridgeConnector.Socket.Once<string>("webContents-loadFile-error" + Id, (error) => { tcs.SetException(new InvalidOperationException(error)); });
BridgeConnector.Socket.Emit("webContents-loadFile", Id, filePath, options);
return tcs.Task;
}
/// <summary>
/// Returns boolean - Whether web page is still loading resources.
/// </summary>
public Task<bool> IsLoadingAsync() => InvokeAsync<bool>();
/// <summary>
/// Returns boolean - Whether the main frame (and not just iframes or frames within it) is still loading.
/// </summary>
public Task<bool> IsLoadingMainFrameAsync() => InvokeAsync<bool>();
/// <summary>
/// Returns boolean - Whether the web page is waiting for a first-response from the main resource of the page.
/// </summary>
public Task<bool> IsWaitingForResponseAsync() => InvokeAsync<bool>();
/// <summary>
/// Reloads the current web page.
/// </summary>
public void Reload()
{
BridgeConnector.Socket.Emit("webContents-reload", Id);
}
/// <summary>
/// Reloads the current page and ignores cache.
/// </summary>
public void ReloadIgnoringCache()
{
BridgeConnector.Socket.Emit("webContents-reloadIgnoringCache", Id);
}
/// <summary>
/// Stops any pending navigation.
/// </summary>
public void Stop()
{
BridgeConnector.Socket.Emit("webContents-stop", Id);
}
/// <summary>
/// Inserts CSS into the web page.
/// See: https://www.electronjs.org/docs/api/web-contents#contentsinsertcsscss-options
@@ -316,6 +424,37 @@ public class WebContents : ApiBase
BridgeConnector.Socket.Emit("webContents-insertCSS", Id, isBrowserWindow, path);
}
/// <summary>
/// Injects CSS into the current web page and returns a unique key for the inserted
/// stylesheet, which can be used with <see cref="RemoveInsertedCSSAsync"/>.
/// </summary>
/// <param name="css">The style sheet to inject.</param>
/// <param name="cssOrigin">Can be either 'user' or 'author'. Defaults to 'author'.</param>
/// <returns>The key of the inserted style sheet.</returns>
public Task<string> InsertCSSAsync(string css, string cssOrigin = null)
{
var tcs = new TaskCompletionSource<string>();
BridgeConnector.Socket.Once<string>("webContents-insertCSSText-completed" + Id, tcs.SetResult);
BridgeConnector.Socket.Emit("webContents-insertCSSText", Id, css, cssOrigin);
return tcs.Task;
}
/// <summary>
/// Removes the inserted CSS from the current web page.
/// </summary>
/// <param name="key">The key returned by <see cref="InsertCSSAsync"/>.</param>
public Task RemoveInsertedCSSAsync(string key)
{
var tcs = new TaskCompletionSource();
BridgeConnector.Socket.Once("webContents-removeInsertedCSS-completed" + Id, tcs.SetResult);
BridgeConnector.Socket.Emit("webContents-removeInsertedCSS", Id, key);
return tcs.Task;
}
/// <summary>
/// Returns number - The current zoom factor.
/// </summary>
@@ -337,14 +476,14 @@ public class WebContents : ApiBase
/// Returns number - The current zoom level.
/// </summary>
/// <returns></returns>
public Task<int> GetZoomLevelAsync() => InvokeAsync<int>();
public Task<double> GetZoomLevelAsync() => InvokeAsync<double>();
/// <summary>
/// Changes the zoom level to the specified level.
/// The original size is 0 and each increment above or below represents zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively.
/// </summary>
/// <param name="level"></param>
public void SetZoomLevel(int level)
public void SetZoomLevel(double level)
{
BridgeConnector.Socket.Emit("webContents-setZoomLevel", Id, level);
}
@@ -354,7 +493,7 @@ public class WebContents : ApiBase
/// </summary>
/// <param name="minimumLevel"></param>
/// <param name="maximumLevel"></param>
public Task SetVisualZoomLevelLimitsAsync(int minimumLevel, int maximumLevel)
public Task SetVisualZoomLevelLimitsAsync(double minimumLevel, double maximumLevel)
{
var tcs = new TaskCompletionSource();
@@ -399,4 +538,178 @@ public class WebContents : ApiBase
{
BridgeConnector.Socket.Emit("webContents-setUserAgent", Id, userAgent);
}
/// <summary>
/// Executes the editing command undo in web page.
/// </summary>
public void Undo()
{
BridgeConnector.Socket.Emit("webContents-undo", Id);
}
/// <summary>
/// Executes the editing command redo in web page.
/// </summary>
public void Redo()
{
BridgeConnector.Socket.Emit("webContents-redo", Id);
}
/// <summary>
/// Executes the editing command cut in web page.
/// </summary>
public void Cut()
{
BridgeConnector.Socket.Emit("webContents-cut", Id);
}
/// <summary>
/// Executes the editing command copy in web page.
/// </summary>
public void Copy()
{
BridgeConnector.Socket.Emit("webContents-copy", Id);
}
/// <summary>
/// Copies the image at the given position to the clipboard.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
public void CopyImageAt(int x, int y)
{
BridgeConnector.Socket.Emit("webContents-copyImageAt", Id, x, y);
}
/// <summary>
/// Executes the editing command paste in web page.
/// </summary>
public void Paste()
{
BridgeConnector.Socket.Emit("webContents-paste", Id);
}
/// <summary>
/// Executes the editing command pasteAndMatchStyle in web page.
/// </summary>
public void PasteAndMatchStyle()
{
BridgeConnector.Socket.Emit("webContents-pasteAndMatchStyle", Id);
}
/// <summary>
/// Executes the editing command delete in web page.
/// </summary>
public void Delete()
{
BridgeConnector.Socket.Emit("webContents-delete", Id);
}
/// <summary>
/// Executes the editing command selectAll in web page.
/// </summary>
public void SelectAll()
{
BridgeConnector.Socket.Emit("webContents-selectAll", Id);
}
/// <summary>
/// Executes the editing command unselect in web page.
/// </summary>
public void Unselect()
{
BridgeConnector.Socket.Emit("webContents-unselect", Id);
}
/// <summary>
/// Adjusts the current text selection starting and ending points by the given amounts.
/// A negative amount moves the selection towards the beginning of the document.
/// </summary>
/// <param name="options"></param>
public void AdjustSelection(AdjustSelectionOptions options)
{
BridgeConnector.Socket.Emit("webContents-adjustSelection", Id, options);
}
/// <summary>
/// Scrolls to the current text selection.
/// </summary>
public void CenterSelection()
{
BridgeConnector.Socket.Emit("webContents-centerSelection", Id);
}
/// <summary>
/// Scrolls to the top of the current web page.
/// </summary>
public void ScrollToTop()
{
BridgeConnector.Socket.Emit("webContents-scrollToTop", Id);
}
/// <summary>
/// Scrolls to the bottom of the current web page.
/// </summary>
public void ScrollToBottom()
{
BridgeConnector.Socket.Emit("webContents-scrollToBottom", Id);
}
/// <summary>
/// Inserts text to the focused element.
/// </summary>
/// <param name="text">The text to be inserted.</param>
public Task InsertTextAsync(string text)
{
var tcs = new TaskCompletionSource();
BridgeConnector.Socket.Once("webContents-insertText-completed" + Id, tcs.SetResult);
BridgeConnector.Socket.Emit("webContents-insertText", Id, text);
return tcs.Task;
}
/// <summary>
/// Executes the editing command replace in web page.
/// </summary>
/// <param name="text"></param>
public void Replace(string text)
{
BridgeConnector.Socket.Emit("webContents-replace", Id, text);
}
/// <summary>
/// Executes the editing command replaceMisspelling in web page.
/// </summary>
/// <param name="text"></param>
public void ReplaceMisspelling(string text)
{
BridgeConnector.Socket.Emit("webContents-replaceMisspelling", Id, text);
}
/// <summary>
/// Starts a request to find all matches for the text in the web page.
/// The result of the request can be obtained by subscribing to the <see cref="OnFoundInPage"/> event.
/// </summary>
/// <param name="text">Content to be searched, must not be empty.</param>
/// <param name="options"></param>
/// <returns>The request id used for the request.</returns>
public Task<int> FindInPageAsync(string text, FindInPageOptions options = null)
{
var tcs = new TaskCompletionSource<int>();
BridgeConnector.Socket.Once<int>("webContents-findInPage-completed" + Id, tcs.SetResult);
BridgeConnector.Socket.Emit("webContents-findInPage", Id, text, options);
return tcs.Task;
}
/// <summary>
/// Stops any findInPage request for the web contents with the provided action.
/// </summary>
/// <param name="action"></param>
public void StopFindInPage(StopFindInPageAction action)
{
BridgeConnector.Socket.Emit("webContents-stopFindInPage", Id, action);
}
}

View File

@@ -19,6 +19,7 @@ namespace ElectronNET.API
internal WindowManager()
{
EnsureBrowserWindowClosedSubscription();
}
internal static WindowManager Instance
@@ -106,17 +107,6 @@ namespace ElectronNET.API
tcs.SetResult(browserWindow);
});
BridgeConnector.Socket.Once<int[]>("BrowserWindowClosed", (ids) =>
{
for (int index = 0; index < _browserWindows.Count; index++)
{
if (!ids.Contains(_browserWindows[index].Id))
{
_browserWindows.RemoveAt(index);
}
}
});
if (loadUrl.Equals("http://localhost", StringComparison.OrdinalIgnoreCase) && ElectronNetRuntime.AspNetWebPort.HasValue)
{
loadUrl = $"{loadUrl}:{ElectronNetRuntime.AspNetWebPort}";
@@ -149,6 +139,49 @@ namespace ElectronNET.API
return await tcs.Task.ConfigureAwait(false);
}
private readonly object _browserWindowSubscriptionSync = new();
private bool _browserWindowClosedSubscribed;
private void EnsureBrowserWindowClosedSubscription()
{
if (_browserWindowClosedSubscribed)
{
return;
}
lock (_browserWindowSubscriptionSync)
{
if (_browserWindowClosedSubscribed)
{
return;
}
BridgeConnector.Socket.On<int[]>("BrowserWindowClosed", HandleBrowserWindowClosed);
BridgeConnector.Socket.On<int>("BrowserWindowRecreated", HandleBrowserWindowRecreated);
_browserWindowClosedSubscribed = true;
}
}
private void HandleBrowserWindowRecreated(int id)
{
if (_browserWindows.All(window => window.Id != id))
{
_browserWindows.Add(new BrowserWindow(id));
}
}
private void HandleBrowserWindowClosed(int[] ids)
{
if (ids == null || ids.Length == 0)
{
_browserWindows.Clear();
return;
}
var existingIds = ids.ToHashSet();
_browserWindows.RemoveAll(window => !existingIds.Contains(window.Id));
}
private bool IsWindows10()
{
return RuntimeInformation.OSDescription.Contains("Windows 10");

View File

@@ -4,7 +4,7 @@ namespace ElectronNET.API
{
internal static class BridgeConnector
{
public static SocketIoFacade Socket
public static ISocketConnection Socket
{
get
{

View File

@@ -0,0 +1,56 @@
namespace ElectronNET.API;
using System;
using System.Threading.Tasks;
/// <summary>
/// Common interface for communication facades.
/// Provides methods for bidirectional communication between .NET and Electron.
/// </summary>
internal interface ISocketConnection : IDisposable
{
/// <summary>
/// Raised when the bridge connection is established.
/// </summary>
event EventHandler BridgeConnected;
/// <summary>
/// Raised when the bridge connection is lost.
/// </summary>
event EventHandler BridgeDisconnected;
/// <summary>
/// Establishes the connection to Electron.
/// </summary>
void Connect();
/// <summary>
/// Registers a persistent event handler.
/// </summary>
void On(string eventName, Action action);
/// <summary>
/// Registers a persistent event handler with a typed parameter.
/// </summary>
void On<T>(string eventName, Action<T> action);
/// <summary>
/// Registers a one-time event handler.
/// </summary>
void Once(string eventName, Action action);
/// <summary>
/// Registers a one-time event handler with a typed parameter.
/// </summary>
void Once<T>(string eventName, Action<T> action);
/// <summary>
/// Removes an event handler.
/// </summary>
void Off(string eventName);
/// <summary>
/// Sends a message to Electron.
/// </summary>
Task Emit(string eventName, params object[] args);
}

View File

@@ -3,20 +3,38 @@
namespace ElectronNET.API;
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading.Tasks;
using ElectronNET.API.Serialization;
using SocketIO.Serializer.SystemTextJson;
using SocketIO = SocketIOClient.SocketIO;
using SocketIOOptions = SocketIOClient.SocketIOOptions;
internal class SocketIoFacade : IDisposable
internal class SocketIOConnection : ISocketConnection
{
private readonly SocketIO _socket;
private readonly object _lockObj = new object();
private bool _isDisposed;
public SocketIoFacade(string uri)
public SocketIOConnection(string uri, string authorization)
{
_socket = new SocketIO(uri);
var opts = new SocketIOOptions
{
// The bridge is a loopback IPC channel, so it must never go through a
// (system) proxy - otherwise the handshake never reaches the socket server.
Proxy = DirectProxy.Instance,
};
if (!string.IsNullOrEmpty(authorization))
{
opts.ExtraHeaders = new Dictionary<string, string>
{
["authorization"] = authorization
};
}
_socket = new SocketIO(uri, opts);
_socket.Serializer = new SystemTextJsonSerializer(ElectronJson.Options);
// Use default System.Text.Json serializer from SocketIOClient.
// Outgoing args are normalized to camelCase via SerializeArg in Emit.
@@ -140,7 +158,18 @@ internal class SocketIoFacade : IDisposable
{
if (this._isDisposed)
{
throw new ObjectDisposedException(nameof(SocketIoFacade));
throw new ObjectDisposedException(nameof(SocketIOConnection));
}
}
private sealed class DirectProxy : IWebProxy
{
public static readonly DirectProxy Instance = new DirectProxy();
public ICredentials Credentials { get; set; }
public Uri GetProxy(Uri destination) => destination;
public bool IsBypassed(Uri host) => true;
}
}

View File

@@ -26,6 +26,8 @@
private readonly StringBuilder stdOut = new StringBuilder(4 * 1024);
private readonly StringBuilder stdErr = new StringBuilder(4 * 1024);
public event EventHandler<string> LineReceived;
private volatile ManualResetEvent stdOutEvent;
private volatile ManualResetEvent stdErrEvent;
private volatile Stopwatch stopwatch;
@@ -35,10 +37,18 @@
public ProcessRunner(string name)
{
this.Name = name;
this.ExitWaitTimeout = DefaultExitWaitTimeout;
}
public event EventHandler<EventArgs> ProcessExited;
/// <summary>Gets or sets the value <see cref="ExitWaitTimeout"/> is initialized with.</summary>
public static int DefaultExitWaitTimeout { get; set; } = 5000;
/// <summary>Gets or sets the time in milliseconds to wait for the process and its I/O to finish
/// after the exited event has been raised. Values of zero or less wait indefinitely.</summary>
public int ExitWaitTimeout { get; set; }
public bool IsDisposed { get; private set; }
private Process Process
@@ -496,8 +506,17 @@
{
try
{
var timeout = this.ExitWaitTimeout;
// This shouldn't throw here, but the mono process implementation doesn't always behave as it should.
this.process.WaitForExit();
if (timeout > 0)
{
this.process.WaitForExit(timeout);
}
else
{
this.process.WaitForExit();
}
}
catch (Exception ex)
{
@@ -571,6 +590,7 @@
if (e.Data != null)
{
Console.WriteLine("|| " + e.Data);
LineReceived?.Invoke(this, e.Data);
}
else
{

View File

@@ -0,0 +1,91 @@
using ElectronNET.API.Entities;
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace ElectronNET.API.Converter;
/// <summary>
/// Handles the polymorphic shape of releaseNotes coming from electron-builder.
/// Depending on the updater.fullChangelog setting, electron-builder sends:
/// - null → when there are no notes
/// - "some string" → plain string (FullChangelog = false, default)
/// - ["note A", "note B"] → array of strings (after broken normalize in older TS)
/// - [{ version, note }, ...] → array of objects (FullChangelog = true)
/// All forms are normalised to ReleaseNoteInfo[] so the C# model stays clean.
/// See: https://github.com/ElectronNET/Electron.NET/issues/1039
/// </summary>
public class ReleaseNotesConverter : JsonConverter<ReleaseNoteInfo[]>
{
// Ensure the converter is called even when the JSON token is null,
// so we can return an empty array instead of null.
public override bool HandleNull => true;
public override ReleaseNoteInfo[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
switch (reader.TokenType)
{
case JsonTokenType.Null:
return Array.Empty<ReleaseNoteInfo>();
case JsonTokenType.String:
// Plain string: "Some release notes"
return new[] { new ReleaseNoteInfo { Note = reader.GetString() } };
case JsonTokenType.StartArray:
var list = new List<ReleaseNoteInfo>();
while (reader.Read() && reader.TokenType != JsonTokenType.EndArray)
{
if (reader.TokenType == JsonTokenType.String)
{
// Array of strings: ["Note A", "Note B"]
list.Add(new ReleaseNoteInfo { Note = reader.GetString() });
}
else if (reader.TokenType == JsonTokenType.StartObject)
{
// Array of objects: [{ "version": "1.0", "note": "..." }]
var entry = JsonSerializer.Deserialize<ReleaseNoteInfo>(ref reader, options) ?? new ReleaseNoteInfo();
list.Add(entry);
}
else
{
reader.Skip();
}
}
return list.ToArray();
default:
throw new JsonException($"Unexpected token {reader.TokenType} when reading releaseNotes.");
}
}
public override void Write(Utf8JsonWriter writer, ReleaseNoteInfo[] value, JsonSerializerOptions options)
{
if (value is null)
{
writer.WriteNullValue();
return;
}
if (value.Length == 0)
{
writer.WriteStartArray();
writer.WriteEndArray();
return;
}
writer.WriteStartArray();
foreach (var item in value)
{
writer.WriteStartObject();
if (item.Version is not null)
{
writer.WriteString("version", item.Version);
}
writer.WriteString("note", item.Note);
writer.WriteEndObject();
}
writer.WriteEndArray();
}
}

View File

@@ -3,7 +3,7 @@
<Import Project="..\common.props" />
<PropertyGroup>
<TargetFrameworks>net6.0;net8.0;net10.0</TargetFrameworks>
<TargetFrameworks>$(ElectronNetTargetFrameworks)</TargetFrameworks>
<PackageOutputPath>..\..\artifacts</PackageOutputPath>
<PackageId>$(PackageNamePrefix).API</PackageId>
<Title>$(PackageId)</Title>
@@ -29,7 +29,7 @@
</PackageReference>
<PackageReference Include="SocketIOClient" Version="3.1.2" />
<PackageReference Include="System.Drawing.Common" Version="8.0.22" />
<PackageReference Include="System.Text.Json" Version="8.0.6" />
<PackageReference Include="System.Text.Json" Version="8.0.6" Condition=" '$(TargetFramework)' == 'net6.0' " />
</ItemGroup>
<ItemGroup>

View File

@@ -15,7 +15,9 @@
internal const int DefaultSocketPort = 8000;
internal const int DefaultWebPort = 8001;
internal const string ElectronPortArgumentName = "electronPort";
internal const string ElectronHostArgumentName = "electronHost";
internal const string ElectronPidArgumentName = "electronPID";
internal const string ElectronAuthTokenArgumentName = "electronAuthToken";
/// <summary>Initializes the <see cref="ElectronNetRuntime"/> class.</summary>
static ElectronNetRuntime()
@@ -26,8 +28,15 @@
public static string ElectronExtraArguments { get; set; }
public static string ElectronAuthToken { get; internal set; }
public static int? ElectronSocketPort { get; internal set; }
/// <summary>
/// The loopback address the Electron socket bridge is listening on.
/// </summary>
public static string ElectronSocketHost { get; internal set; }
public static int? AspNetWebPort { get; internal set; }
public static StartupMethod StartupMethod { get; internal set; }
@@ -47,9 +56,7 @@
internal static int? ElectronProcessId { get; set; }
internal static Func<Task> OnAppReadyCallback { get; set; }
internal static SocketIoFacade GetSocket()
internal static ISocketConnection GetSocket()
{
return RuntimeControllerCore?.Socket;
}

View File

@@ -12,7 +12,7 @@
{
}
internal abstract SocketIoFacade Socket { get; }
internal abstract ISocketConnection Socket { get; }
internal abstract ElectronProcessBase ElectronProcess { get; }

View File

@@ -13,13 +13,12 @@
{
private ElectronProcessBase electronProcess;
private SocketBridgeService socketBridge;
private int? port;
public RuntimeControllerDotNetFirst()
{
}
internal override SocketIoFacade Socket
internal override ISocketConnection Socket
{
get
{
@@ -41,19 +40,13 @@
var isUnPacked = ElectronNetRuntime.StartupMethod.IsUnpackaged();
var electronBinaryName = ElectronNetRuntime.ElectronExecutable;
var args = string.Format("{0} {1}", ElectronNetRuntime.ElectronExtraArguments, Environment.CommandLine).Trim();
this.port = ElectronNetRuntime.ElectronSocketPort;
if (!this.port.HasValue)
{
this.port = PortHelper.GetFreePort(ElectronNetRuntime.DefaultSocketPort);
ElectronNetRuntime.ElectronSocketPort = this.port;
}
var port = ElectronNetRuntime.ElectronSocketPort ?? 0;
Console.Error.WriteLine("[StartCore]: isUnPacked: {0}", isUnPacked);
Console.Error.WriteLine("[StartCore]: electronBinaryName: {0}", electronBinaryName);
Console.Error.WriteLine("[StartCore]: args: {0}", args);
this.electronProcess = new ElectronProcessActive(isUnPacked, electronBinaryName, args, this.port.Value);
this.electronProcess = new ElectronProcessActive(isUnPacked, electronBinaryName, args, port);
this.electronProcess.Ready += this.ElectronProcess_Ready;
this.electronProcess.Stopped += this.ElectronProcess_Stopped;
@@ -63,8 +56,10 @@
private void ElectronProcess_Ready(object sender, EventArgs e)
{
var port = ElectronNetRuntime.ElectronSocketPort.Value;
var token = ElectronNetRuntime.ElectronAuthToken;
this.TransitionState(LifetimeState.Started);
this.socketBridge = new SocketBridgeService(this.port!.Value);
this.socketBridge = new SocketBridgeService(port, token);
this.socketBridge.Ready += this.SocketBridge_Ready;
this.socketBridge.Stopped += this.SocketBridge_Stopped;
this.socketBridge.Start();

View File

@@ -11,13 +11,12 @@
{
private ElectronProcessBase electronProcess;
private SocketBridgeService socketBridge;
private int? port;
public RuntimeControllerElectronFirst()
{
}
internal override SocketIoFacade Socket
internal override ISocketConnection Socket
{
get
{
@@ -36,12 +35,8 @@
protected override Task StartCore()
{
this.port = ElectronNetRuntime.ElectronSocketPort;
if (!this.port.HasValue)
{
throw new Exception("No port has been specified by Electron!");
}
var port = ElectronNetRuntime.ElectronSocketPort.Value;
var token = ElectronNetRuntime.ElectronAuthToken;
if (!ElectronNetRuntime.ElectronProcessId.HasValue)
{
@@ -49,7 +44,7 @@
}
this.TransitionState(LifetimeState.Starting);
this.socketBridge = new SocketBridgeService(this.port!.Value);
this.socketBridge = new SocketBridgeService(port, token);
this.socketBridge.Ready += this.SocketBridge_Ready;
this.socketBridge.Stopped += this.SocketBridge_Stopped;
this.socketBridge.Start();

View File

@@ -6,6 +6,8 @@
public string ElectronVersion { get; internal set; }
public string ElectronRootDir { get; internal set; }
public string RuntimeIdentifier { get; internal set; }
public bool ElectronSingleInstance { get; internal set; }

View File

@@ -0,0 +1,31 @@
namespace ElectronNET.Runtime.Helpers
{
using System;
using System.IO;
/// <summary>
/// Resolves the directory that contains the Electron binary of a packaged application.
/// </summary>
internal static class ElectronRootDirResolver
{
/// <summary>The location of the Electron binary relative to the .NET application directory in the
/// default (Electron-first) layout, where the .NET application is placed in 'resources/bin'.</summary>
internal const string DefaultElectronRootDir = "../..";
/// <summary>Resolves the Electron root directory relative to the given .NET application directory.</summary>
/// <param name="baseDirectory">The directory containing the .NET application.</param>
/// <returns>The directory containing the Electron binary.</returns>
public static DirectoryInfo Resolve(DirectoryInfo baseDirectory)
{
var rootDir = ElectronNetRuntime.BuildInfo?.ElectronRootDir;
if (string.IsNullOrWhiteSpace(rootDir))
{
rootDir = DefaultElectronRootDir;
}
// An absolute ElectronRootDir is used as-is by Path.Combine.
return new DirectoryInfo(Path.GetFullPath(Path.Combine(baseDirectory.FullName, rootDir)));
}
}
}

View File

@@ -69,6 +69,15 @@
return false;
}
// Packaged, if the Electron binary is found where ElectronRootDir points to.
var electronExecutable = ElectronNetRuntime.ElectronExecutable;
if (!string.IsNullOrEmpty(electronExecutable) &&
File.Exists(Path.Combine(ElectronRootDirResolver.Resolve(dir).FullName, electronExecutable)))
{
return false;
}
if (dir.GetDirectories().Any(e => e.Name == ".electron"))
{
return true;

View File

@@ -2,12 +2,16 @@
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using ElectronNET.Common;
using ElectronNET.Runtime.Data;
using ElectronNET.Runtime.Helpers;
/// <summary>
/// Launches and manages the Electron app process.
@@ -15,6 +19,8 @@
[Localizable(false)]
internal class ElectronProcessActive : ElectronProcessBase
{
private readonly Regex extractor = new Regex("^Electron Socket: listening on port (\\d+) at (\\S+) using ([a-f0-9]+)$");
private readonly bool isUnpackaged;
private readonly string electronBinaryName;
private readonly string extraArguments;
@@ -82,7 +88,7 @@
}
else
{
dir = dir.Parent!.Parent!;
dir = ElectronRootDirResolver.Resolve(dir);
startCmd = Path.Combine(dir.FullName, this.electronBinaryName);
args = $"-dotnetpacked -electronforcedport={this.socketPort:D} " + this.extraArguments;
workingDir = dir.FullName;
@@ -101,7 +107,6 @@
}
var osPart = buildInfoRid.Split('-').First();
var mismatch = false;
switch (osPart)
@@ -155,20 +160,61 @@
return Task.CompletedTask;
}
private async Task StartInternal(string startCmd, string args, string directoriy)
private async Task StartInternal(string startCmd, string args, string directory)
{
var tcs = new TaskCompletionSource();
using var cts = new CancellationTokenSource(2 * 60_000); // cancel after 2 minutes
using var _ = cts.Token.Register(() =>
{
// Time is over - let's kill the process and move on
this.process.Cancel();
// We don't want to raise exceptions here - just pass the barrier
tcs.TrySetResult();
});
void Read_SocketIO_Parameters(object sender, string line)
{
// Look for "Electron Socket: listening on port %s at ..."
var match = extractor.Match(line);
if (match?.Success ?? false)
{
var port = int.Parse(match.Groups[1].Value);
var host = match.Groups[2].Value;
var token = match.Groups[3].Value;
this.process.LineReceived -= Read_SocketIO_Parameters;
ElectronNetRuntime.ElectronAuthToken = token;
ElectronNetRuntime.ElectronSocketPort = port;
ElectronNetRuntime.ElectronSocketHost = host;
tcs.SetResult();
}
}
void Monitor_SocketIO_Failure(object sender, EventArgs e)
{
// We don't want to raise exceptions here - just pass the barrier
if (tcs.Task.IsCompleted)
{
this.Process_Exited(sender, e);
}
else
{
tcs.TrySetResult();
}
}
try
{
await Task.Delay(10.ms()).ConfigureAwait(false);
Console.Error.WriteLine("[StartInternal]: startCmd: {0}", startCmd);
Console.Error.WriteLine("[StartInternal]: args: {0}", args);
this.process = new ProcessRunner("ElectronRunner");
this.process.ProcessExited += this.Process_Exited;
this.process.Run(startCmd, args, directoriy);
this.process.ProcessExited += Monitor_SocketIO_Failure;
this.process.LineReceived += Read_SocketIO_Parameters;
this.process.Run(startCmd, args, directory);
await Task.Delay(500.ms()).ConfigureAwait(false);
await tcs.Task.ConfigureAwait(false);
Console.Error.WriteLine("[StartInternal]: after run:");
@@ -178,11 +224,11 @@
Console.Error.WriteLine("[StartInternal]: Process is not running: " + this.process.StandardOutput);
Task.Run(() => this.TransitionState(LifetimeState.Stopped));
throw new Exception("Failed to launch the Electron process.");
}
this.TransitionState(LifetimeState.Ready);
else
{
this.TransitionState(LifetimeState.Ready);
}
}
catch (Exception ex)
{

View File

@@ -8,22 +8,36 @@
internal class SocketBridgeService : LifetimeServiceBase
{
private readonly int socketPort;
private readonly string authorization;
private readonly string socketUrl;
private SocketIoFacade socket;
private SocketIOConnection socket;
public SocketBridgeService(int socketPort)
public SocketBridgeService(int socketPort, string authorization)
{
this.socketPort = socketPort;
this.socketUrl = $"http://localhost:{this.socketPort}";
this.authorization = authorization;
this.socketUrl = $"http://{FormatHost(ElectronNetRuntime.ElectronSocketHost)}:{this.socketPort}";
}
// The Electron host reports the loopback address it is actually listening on; only
// when it is unknown we have to fall back to the ambiguous hostname.
private static string FormatHost(string socketHost)
{
if (string.IsNullOrWhiteSpace(socketHost))
{
return "localhost";
}
return socketHost.Contains(':') ? $"[{socketHost}]" : socketHost;
}
public int SocketPort => this.socketPort;
internal SocketIoFacade Socket => this.socket;
internal SocketIOConnection Socket => this.socket;
protected override Task StartCore()
{
this.socket = new SocketIoFacade(this.socketUrl);
this.socket = new SocketIOConnection(this.socketUrl, this.authorization);
this.socket.BridgeConnected += this.Socket_BridgeConnected;
this.socket.BridgeDisconnected += this.Socket_BridgeDisconnected;
Task.Run(this.Connect);

View File

@@ -94,8 +94,20 @@
}
}
var pidArg = argsList.FirstOrDefault(e => e.Contains(ElectronNetRuntime.ElectronPidArgumentName, StringComparison.OrdinalIgnoreCase));
var hostArg = argsList.FirstOrDefault(e => e.Contains(ElectronNetRuntime.ElectronHostArgumentName, StringComparison.OrdinalIgnoreCase));
if (hostArg != null)
{
var parts = hostArg.Split('=', StringSplitOptions.TrimEntries);
if (parts.Length > 1 && !string.IsNullOrWhiteSpace(parts[1]))
{
ElectronNetRuntime.ElectronSocketHost = parts[1];
Console.WriteLine("Use Electron Host: " + parts[1]);
}
}
var pidArg = argsList.FirstOrDefault(e => e.Contains(ElectronNetRuntime.ElectronPidArgumentName, StringComparison.OrdinalIgnoreCase));
if (pidArg != null)
{
var parts = pidArg.Split('=', StringSplitOptions.TrimEntries);
@@ -106,6 +118,20 @@
Console.WriteLine("Electron Process ID: " + result);
}
}
var authTokenArg = argsList.FirstOrDefault(e => e.Contains(ElectronNetRuntime.ElectronAuthTokenArgumentName, StringComparison.OrdinalIgnoreCase));
if (authTokenArg != null)
{
var parts = authTokenArg.Split('=', StringSplitOptions.TrimEntries);
if (parts.Length > 1 && !string.IsNullOrWhiteSpace(parts[1]))
{
var result = parts[1];
ElectronNetRuntime.ElectronAuthToken = result;
Console.WriteLine("Use Auth Token: " + result);
}
}
}
private void SetElectronExecutable()
@@ -152,6 +178,7 @@
{
buildInfo.ElectronExecutable = attributes.FirstOrDefault(e => e.Key == nameof(buildInfo.ElectronExecutable))?.Value;
buildInfo.ElectronVersion = attributes.FirstOrDefault(e => e.Key == nameof(buildInfo.ElectronVersion))?.Value;
buildInfo.ElectronRootDir = attributes.FirstOrDefault(e => e.Key == nameof(buildInfo.ElectronRootDir))?.Value;
buildInfo.RuntimeIdentifier = attributes.FirstOrDefault(e => e.Key == nameof(buildInfo.RuntimeIdentifier))?.Value;
buildInfo.Title = attributes.FirstOrDefault(e => e.Key == nameof(buildInfo.Title))?.Value;
buildInfo.Version = attributes.FirstOrDefault(e => e.Key == nameof(buildInfo.Version))?.Value;

View File

@@ -44,5 +44,98 @@
return builder;
}
/// <summary>
/// Adds Electron.NET support to the current ASP.NET Core application and registers an application-ready callback.
/// </summary>
/// <param name="builder">The <see cref="WebApplicationBuilder"/> to extend.</param>
/// <param name="args">The command-line arguments passed to the process, forwarded to Electron.</param>
/// <param name="onAppReadyCallback">
/// An asynchronous callback invoked when the Electron app is ready. Use this to create windows or perform initialization.
/// </param>
/// <returns>
/// The same <see cref="WebApplicationBuilder"/> instance to enable fluent configuration.
/// </returns>
/// <example>
/// <code language="csharp">
/// var builder = WebApplication.CreateBuilder(args)
/// .UseElectron(args, async (processArgs) =>
/// {
/// // Create the main browser window or perform other startup tasks.
/// });
///
/// var app = builder.Build();
/// app.MapRazorPages();
/// app.Run();
/// </code>
/// </example>
public static WebApplicationBuilder UseElectron(this WebApplicationBuilder builder, string[] args, Func<string[], Task> onAppReadyCallback)
{
builder.WebHost.UseElectron(args, onAppReadyCallback);
return builder;
}
/// <summary>
/// Adds Electron.NET support to the current ASP.NET Core application and registers an application-ready callback.
/// </summary>
/// <param name="builder">The <see cref="WebApplicationBuilder"/> to extend.</param>
/// <param name="args">The command-line arguments passed to the process, forwarded to Electron.</param>
/// <param name="onAppReadyCallback">
/// An asynchronous callback invoked when the Electron app is ready. Use this to create windows or perform initialization.
/// </param>
/// <returns>
/// The same <see cref="WebApplicationBuilder"/> instance to enable fluent configuration.
/// </returns>
/// <example>
/// <code language="csharp">
/// var builder = WebApplication.CreateBuilder(args)
/// .UseElectron(args, async (serviceProvider) =>
/// {
/// // Create the main browser window or perform other startup tasks.
/// });
///
/// var app = builder.Build();
/// app.MapRazorPages();
/// app.Run();
/// </code>
/// </example>
public static WebApplicationBuilder UseElectron(this WebApplicationBuilder builder, string[] args, Func<IServiceProvider, Task> onAppReadyCallback)
{
builder.WebHost.UseElectron(args, onAppReadyCallback);
return builder;
}
/// <summary>
/// Adds Electron.NET support to the current ASP.NET Core application and registers an application-ready callback.
/// </summary>
/// <param name="builder">The <see cref="WebApplicationBuilder"/> to extend.</param>
/// <param name="args">The command-line arguments passed to the process, forwarded to Electron.</param>
/// <param name="onAppReadyCallback">
/// An asynchronous callback invoked when the Electron app is ready. Use this to create windows or perform initialization.
/// </param>
/// <returns>
/// The same <see cref="WebApplicationBuilder"/> instance to enable fluent configuration.
/// </returns>
/// <example>
/// <code language="csharp">
/// var builder = WebApplication.CreateBuilder(args)
/// .UseElectron(args, async (serviceProvider, processArgs) =>
/// {
/// // Create the main browser window or perform other startup tasks.
/// });
///
/// var app = builder.Build();
/// app.MapRazorPages();
/// app.Run();
/// </code>
/// </example>
public static WebApplicationBuilder UseElectron(this WebApplicationBuilder builder, string[] args, Func<IServiceProvider, string[], Task> onAppReadyCallback)
{
builder.WebHost.UseElectron(args, onAppReadyCallback);
return builder;
}
}
}

View File

@@ -1,6 +1,7 @@
namespace ElectronNET.API
{
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using ElectronNET.AspNet;
@@ -10,6 +11,7 @@
using ElectronNET.Runtime.Helpers;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
/// <summary>
/// Provides extension methods for <see cref="IWebHostBuilder"/> to enable Electron.NET
@@ -59,30 +61,181 @@
/// </example>
public static IWebHostBuilder UseElectron(this IWebHostBuilder builder, string[] args, Func<Task> onAppReadyCallback)
{
ElectronNetRuntime.OnAppReadyCallback = onAppReadyCallback;
builder.ConfigureServices(services =>
{
services.AddSingleton<IAppReadyCallbackResolver>(_ => new AppReadyCallbackResolver(onAppReadyCallback));
});
return UseElectronCore(builder, args);
}
/// <summary>
/// Adds Electron.NET support to the current ASP.NET Core web host and registers an application-ready callback.
/// </summary>
/// <param name="builder">The <see cref="IWebHostBuilder"/> to extend.</param>
/// <param name="args">The command-line arguments passed to the process.</param>
/// <param name="onAppReadyCallback">
/// An asynchronous callback invoked when the Electron app is ready. Use this to create windows or perform initialization.
/// </param>
/// <returns>
/// The same <see cref="IWebHostBuilder"/> instance to enable fluent configuration.
/// </returns>
/// <example>
/// <code language="csharp">
/// using Microsoft.AspNetCore.Hosting;
/// using Microsoft.Extensions.Hosting;
/// using ElectronNET.API;
///
/// public class Program
/// {
/// public static void Main(string[] args)
/// {
/// Host.CreateDefaultBuilder(args)
/// .ConfigureWebHostDefaults(webBuilder =>
/// {
/// webBuilder.UseStartup&lt;Startup&gt;();
/// webBuilder.UseElectron(args, async (processArgs) =>
/// {
/// // Create the main browser window or perform other startup tasks.
/// });
/// })
/// .Build()
/// .Run();
/// }
/// }
/// </code>
/// </example>
public static IWebHostBuilder UseElectron(this IWebHostBuilder builder, string[] args, Func<string[], Task> onAppReadyCallback)
{
builder.ConfigureServices(services =>
{
services.AddSingleton<IAppReadyCallbackResolver>(_ => new AppReadyCallbackResolver(args, onAppReadyCallback));
});
return UseElectronCore(builder, args);
}
/// <summary>
/// Adds Electron.NET support to the current ASP.NET Core web host and registers an application-ready callback.
/// </summary>
/// <param name="builder">The <see cref="IWebHostBuilder"/> to extend.</param>
/// <param name="args">The command-line arguments passed to the process.</param>
/// <param name="onAppReadyCallback">
/// An asynchronous callback invoked when the Electron app is ready. Use this to create windows or perform initialization.
/// </param>
/// <returns>
/// The same <see cref="IWebHostBuilder"/> instance to enable fluent configuration.
/// </returns>
/// <example>
/// <code language="csharp">
/// using Microsoft.AspNetCore.Hosting;
/// using Microsoft.Extensions.Hosting;
/// using ElectronNET.API;
///
/// public class Program
/// {
/// public static void Main(string[] args)
/// {
/// Host.CreateDefaultBuilder(args)
/// .ConfigureWebHostDefaults(webBuilder =>
/// {
/// webBuilder.UseStartup&lt;Startup&gt;();
/// webBuilder.UseElectron(args, async (serviceProvider) =>
/// {
/// // Create the main browser window or perform other startup tasks.
/// });
/// })
/// .Build()
/// .Run();
/// }
/// }
/// </code>
/// </example>
public static IWebHostBuilder UseElectron(this IWebHostBuilder builder, string[] args, Func<IServiceProvider, Task> onAppReadyCallback)
{
builder.ConfigureServices(services =>
{
services.AddSingleton<IAppReadyCallbackResolver>(provider => new AppReadyCallbackResolver(provider, onAppReadyCallback));
});
return UseElectronCore(builder, args);
}
/// <summary>
/// Adds Electron.NET support to the current ASP.NET Core web host and registers an application-ready callback.
/// </summary>
/// <param name="builder">The <see cref="IWebHostBuilder"/> to extend.</param>
/// <param name="args">The command-line arguments passed to the process.</param>
/// <param name="onAppReadyCallback">
/// An asynchronous callback invoked when the Electron app is ready. Use this to create windows or perform initialization.
/// </param>
/// <returns>
/// The same <see cref="IWebHostBuilder"/> instance to enable fluent configuration.
/// </returns>
/// <example>
/// <code language="csharp">
/// using Microsoft.AspNetCore.Hosting;
/// using Microsoft.Extensions.Hosting;
/// using ElectronNET.API;
///
/// public class Program
/// {
/// public static void Main(string[] args)
/// {
/// Host.CreateDefaultBuilder(args)
/// .ConfigureWebHostDefaults(webBuilder =>
/// {
/// webBuilder.UseStartup&lt;Startup&gt;();
/// webBuilder.UseElectron(args, async (serviceProvider, processArgs) =>
/// {
/// // Create the main browser window or perform other startup tasks.
/// });
/// })
/// .Build()
/// .Run();
/// }
/// }
/// </code>
/// </example>
public static IWebHostBuilder UseElectron(this IWebHostBuilder builder, string[] args, Func<IServiceProvider, string[], Task> onAppReadyCallback)
{
builder.ConfigureServices(services =>
{
services.AddSingleton<IAppReadyCallbackResolver>(provider => new AppReadyCallbackResolver(provider, args, onAppReadyCallback));
});
return UseElectronCore(builder, args);
}
private static IWebHostBuilder UseElectronCore(IWebHostBuilder builder, string[] args)
{
// no matter how this is set - let's unset to prevent Electron not starting as expected
// e.g., VS Code sets this env variable, but this will cause `require("electron")` to not
// work as expected, see issue #952
Environment.SetEnvironmentVariable("ELECTRON_RUN_AS_NODE", null);
var webPort = PortHelper.GetFreePort(ElectronNetRuntime.AspNetWebPort ?? ElectronNetRuntime.DefaultWebPort);
ElectronNetRuntime.AspNetWebPort = webPort;
var webPort = ElectronNetRuntime.AspNetWebPort ?? 0;
// check for the content folder if its exists in base director otherwise no need to include
// It was used before because we are publishing the project which copies everything to bin folder and contentroot wwwroot was folder there.
// now we have implemented the live reload if app is run using /watch then we need to use the default project path.
if (Directory.Exists($"{AppDomain.CurrentDomain.BaseDirectory}\\wwwroot"))
// In packaged mode, static content is deployed alongside the app binaries, so we must
// point content root to the process base directory. In unpackaged/watch scenarios we
// keep the default project content root to preserve live reload behavior.
var isPackagedStartup = ElectronNetRuntime.StartupMethod == StartupMethod.PackagedElectronFirst ||
ElectronNetRuntime.StartupMethod == StartupMethod.PackagedDotnetFirst;
// For port 0 (dynamic port assignment), Kestrel requires binding to specific IP (127.0.0.1) not localhost
var host = webPort == 0 ? "127.0.0.1" : "localhost";
if (isPackagedStartup)
{
builder = builder.UseContentRoot(AppDomain.CurrentDomain.BaseDirectory)
.UseUrls("http://localhost:" + webPort);
.UseUrls($"http://{host}:{webPort}");
}
else
{
builder = builder.UseUrls("http://localhost:" + webPort);
builder = builder.UseUrls($"http://{host}:{webPort}");
}
builder = builder.ConfigureServices(services =>
builder = builder.ConfigureServices((context, services) =>
{
services.AddTransient<IStartupFilter, ServerReadyStartupFilter>();
services.AddSingleton<AspNetLifetimeAdapter>();

View File

@@ -3,7 +3,7 @@
<Import Project="..\common.props" />
<PropertyGroup>
<TargetFrameworks>net6.0;net8.0;net10.0</TargetFrameworks>
<TargetFrameworks>$(ElectronNetTargetFrameworks)</TargetFrameworks>
<PackageOutputPath>..\..\artifacts</PackageOutputPath>
<PackageId>$(PackageNamePrefix).AspNet</PackageId>
<Title>$(PackageId)</Title>
@@ -13,23 +13,6 @@
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<Nullable>disable</Nullable>
<RootNamespace>ElectronNET</RootNamespace>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|net6.0|AnyCPU'">
<NoWarn>1701;1702;4014;CS4014;CA1416;CS1591</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|net8.0|AnyCPU'">
<NoWarn>1701;1702;4014;CS4014;CA1416;CS1591</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|net10.0|AnyCPU'">
<NoWarn>1701;1702;4014;CS4014;CA1416;CS1591</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net6.0|AnyCPU'">
<NoWarn>1701;1702;4014;CS4014;CA1416;CS1591</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net8.0|AnyCPU'">
<NoWarn>1701;1702;4014;CS4014;CA1416;CS1591</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|net10.0|AnyCPU'">
<NoWarn>1701;1702;4014;CS4014;CA1416;CS1591</NoWarn>
</PropertyGroup>
<ItemGroup>

View File

@@ -0,0 +1,100 @@
namespace ElectronNET.AspNet.Middleware
{
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using ElectronNET.AspNet.Services;
/// <summary>
/// Middleware that validates authentication for all Electron requests.
/// Checks for authentication cookie or token query parameter on first request.
/// Sets HttpOnly cookie for subsequent requests.
///
/// Security Model:
/// - First request includes token as query parameter (?token=guid)
/// - Middleware validates token and sets secure HttpOnly cookie
/// - Subsequent requests use cookie (no token in URL)
/// - HTTP endpoints protected
/// </summary>
public class ElectronAuthenticationMiddleware
{
private readonly RequestDelegate _next;
private readonly IElectronAuthenticationService _authService;
private readonly ILogger<ElectronAuthenticationMiddleware> _logger;
private const string AuthCookieName = "ElectronAuth";
public ElectronAuthenticationMiddleware(
RequestDelegate next,
IElectronAuthenticationService authService,
ILogger<ElectronAuthenticationMiddleware> logger)
{
_next = next;
_authService = authService;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
var path = context.Request.Path.Value;
// Check if authentication cookie exists
var authCookie = context.Request.Cookies[AuthCookieName];
if (!string.IsNullOrEmpty(authCookie))
{
// Cookie present - validate it
if (_authService.ValidateToken(authCookie))
{
await _next(context);
return;
}
else
{
// Invalid cookie - reject
_logger.LogWarning("Authentication failed: Invalid cookie for path {Path} from {RemoteIp}", path, context.Connection.RemoteIpAddress);
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized: Invalid authentication");
return;
}
}
// No cookie - check for token in query string (first-time authentication)
var token = context.Request.Query["token"].ToString();
if (!string.IsNullOrEmpty(token))
{
if (_authService.ValidateToken(token))
{
// Valid token - set cookie for future requests
_logger.LogInformation("Authentication successful: Setting cookie for path {Path}", path);
context.Response.Cookies.Append(AuthCookieName, token, new CookieOptions
{
HttpOnly = true, // Prevent JavaScript access (XSS protection)
SameSite = SameSiteMode.Strict, // CSRF protection
Path = "/", // Valid for all routes
Secure = false, // False because localhost is HTTP
IsEssential = true // Required for app to function
});
await _next(context);
return;
}
else
{
// Invalid token - reject
_logger.LogWarning("Authentication failed: Invalid token (prefix: {TokenPrefix}...) for path {Path} from {RemoteIp}", token.Length > 8 ? token.Substring(0, 8) : token, path, context.Connection.RemoteIpAddress);
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized: Invalid authentication");
return;
}
}
// Neither cookie nor valid token present - reject
_logger.LogWarning("Authentication failed: No cookie or token provided for path {Path} from {RemoteIp}", path, context.Connection.RemoteIpAddress);
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized: Authentication required");
}
}
}

View File

@@ -1,8 +1,13 @@
namespace ElectronNET.AspNet.Runtime
{
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.DependencyInjection;
using ElectronNET.API;
using ElectronNET.AspNet.Services;
using ElectronNET.Common;
using ElectronNET.Runtime.Controllers;
using ElectronNET.Runtime.Data;
@@ -10,12 +15,18 @@
internal abstract class RuntimeControllerAspNetBase : RuntimeControllerBase
{
private readonly IServer server;
private readonly AspNetLifetimeAdapter aspNetLifetimeAdapter;
private readonly IAppReadyCallbackResolver callbackResolver;
private readonly IElectronAuthenticationService authenticationService;
private SocketBridgeService socketBridge;
protected RuntimeControllerAspNetBase(AspNetLifetimeAdapter aspNetLifetimeAdapter)
protected RuntimeControllerAspNetBase(IServer server, AspNetLifetimeAdapter aspNetLifetimeAdapter, IAppReadyCallbackResolver callbackResolver, IElectronAuthenticationService authenticationService = null)
{
this.server = server;
this.aspNetLifetimeAdapter = aspNetLifetimeAdapter;
this.callbackResolver = callbackResolver;
this.authenticationService = authenticationService;
this.aspNetLifetimeAdapter.Ready += this.AspNetLifetimeAdapter_Ready;
this.aspNetLifetimeAdapter.Stopping += this.AspNetLifetimeAdapter_Stopping;
this.aspNetLifetimeAdapter.Stopped += this.AspNetLifetimeAdapter_Stopped;
@@ -25,7 +36,7 @@
internal override SocketBridgeService SocketBridge => this.socketBridge;
internal override SocketIoFacade Socket
internal override ISocketConnection Socket
{
get
{
@@ -38,9 +49,9 @@
}
}
protected void CreateSocketBridge(int port)
protected void CreateSocketBridge(int port, string authorization)
{
this.socketBridge = new SocketBridgeService(port);
this.socketBridge = new SocketBridgeService(port, authorization);
this.socketBridge.Ready += this.SocketBridge_Ready;
this.socketBridge.Stopped += this.SocketBridge_Stopped;
this.socketBridge.Start();
@@ -52,6 +63,15 @@
this.ElectronProcess.IsReady() &&
this.aspNetLifetimeAdapter.IsReady())
{
var token = ElectronNetRuntime.ElectronAuthToken;
var serverAddressesFeature = this.server.Features.Get<IServerAddressesFeature>();
var address = serverAddressesFeature.Addresses.First();
var uri = new Uri(address);
// Only if somebody registered an IElectronAuthenticationService service - otherwise we do not care
this.authenticationService?.SetExpectedToken(token);
ElectronNetRuntime.AspNetWebPort = uri.Port;
this.TransitionState(LifetimeState.Ready);
Task.Run(this.RunReadyCallback);
}
@@ -112,20 +132,20 @@
private async Task RunReadyCallback()
{
if (ElectronNetRuntime.OnAppReadyCallback == null)
if (!callbackResolver.HasCallback)
{
Console.WriteLine("Warning: Non OnReadyCallback provided in UseElectron() setup.");
Console.WriteLine("Warning: No OnReadyCallback provided in UseElectron() setup.");
return;
}
try
{
await ElectronNetRuntime.OnAppReadyCallback().ConfigureAwait(false);
await callbackResolver.Invoke().ConfigureAwait(false);
}
catch (Exception ex)
{
Console.WriteLine("Exception while executing OnAppReadyCallback. Stopping...\n" + ex);
this.Stop();
_ = this.Stop();
}
}
}

View File

@@ -2,6 +2,9 @@
{
using System;
using System.Threading.Tasks;
using System.Security.Principal;
using Microsoft.AspNetCore.Hosting.Server;
using ElectronNET.AspNet.Services;
using ElectronNET.Common;
using ElectronNET.Runtime.Data;
using ElectronNET.Runtime.Helpers;
@@ -10,9 +13,8 @@
internal class RuntimeControllerAspNetDotnetFirst : RuntimeControllerAspNetBase
{
private ElectronProcessBase electronProcess;
private int? port;
public RuntimeControllerAspNetDotnetFirst(AspNetLifetimeAdapter aspNetLifetimeAdapter) : base(aspNetLifetimeAdapter)
public RuntimeControllerAspNetDotnetFirst(IServer server, AspNetLifetimeAdapter aspNetLifetimeAdapter, IAppReadyCallbackResolver callbackResolver, IElectronAuthenticationService authenticationService = null) : base(server, aspNetLifetimeAdapter, callbackResolver, authenticationService)
{
}
@@ -23,15 +25,9 @@
var isUnPacked = ElectronNetRuntime.StartupMethod.IsUnpackaged();
var electronBinaryName = ElectronNetRuntime.ElectronExecutable;
var args = Environment.CommandLine;
this.port = ElectronNetRuntime.ElectronSocketPort;
var port = ElectronNetRuntime.ElectronSocketPort ?? 0;
if (!this.port.HasValue)
{
this.port = PortHelper.GetFreePort(ElectronNetRuntime.DefaultSocketPort);
ElectronNetRuntime.ElectronSocketPort = this.port;
}
this.electronProcess = new ElectronProcessActive(isUnPacked, electronBinaryName, args, this.port.Value);
this.electronProcess = new ElectronProcessActive(isUnPacked, electronBinaryName, args, port);
this.electronProcess.Ready += this.ElectronProcess_Ready;
this.electronProcess.Stopped += this.ElectronProcess_Stopped;
@@ -46,8 +42,10 @@
private void ElectronProcess_Ready(object sender, EventArgs e)
{
var port = ElectronNetRuntime.ElectronSocketPort.Value;
var token = ElectronNetRuntime.ElectronAuthToken;
this.TransitionState(LifetimeState.Started);
this.CreateSocketBridge(this.port!.Value);
this.CreateSocketBridge(port, token);
}
private void ElectronProcess_Stopped(object sender, EventArgs e)

View File

@@ -2,15 +2,16 @@
{
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting.Server;
using ElectronNET.AspNet.Services;
using ElectronNET.Runtime.Data;
using ElectronNET.Runtime.Services.ElectronProcess;
internal class RuntimeControllerAspNetElectronFirst : RuntimeControllerAspNetBase
{
private ElectronProcessBase electronProcess;
private int? port;
public RuntimeControllerAspNetElectronFirst(AspNetLifetimeAdapter aspNetLifetimeAdapter) : base(aspNetLifetimeAdapter)
public RuntimeControllerAspNetElectronFirst(IServer server, AspNetLifetimeAdapter aspNetLifetimeAdapter, IAppReadyCallbackResolver callbackResolver, IElectronAuthenticationService authenticationService = null) : base(server, aspNetLifetimeAdapter, callbackResolver, authenticationService)
{
}
@@ -18,19 +19,15 @@
protected override Task StartCore()
{
this.port = ElectronNetRuntime.ElectronSocketPort;
if (!this.port.HasValue)
{
throw new Exception("No port has been specified by Electron!");
}
var port = ElectronNetRuntime.ElectronSocketPort.Value;
var token = ElectronNetRuntime.ElectronAuthToken;
if (!ElectronNetRuntime.ElectronProcessId.HasValue)
{
throw new Exception("No electronPID has been specified by Electron!");
}
this.CreateSocketBridge(this.port!.Value);
this.CreateSocketBridge(port, token);
this.electronProcess = new ElectronProcessPassive(ElectronNetRuntime.ElectronProcessId.Value);
this.electronProcess.Stopped += this.ElectronProcess_Stopped;

View File

@@ -0,0 +1,46 @@
using System;
using System.Threading.Tasks;
namespace ElectronNET.AspNet.Runtime
{
internal class AppReadyCallbackResolver : IAppReadyCallbackResolver
{
private readonly Func<Task> _callback;
public AppReadyCallbackResolver()
{ }
public AppReadyCallbackResolver(Func<Task> callback)
{
_callback = callback;
}
public AppReadyCallbackResolver(string[] args, Func<string[], Task> callback)
{
if (callback != null)
{
_callback = () => callback.Invoke(args);
}
}
public AppReadyCallbackResolver(IServiceProvider serviceProvider, Func<IServiceProvider, Task> callback)
{
if (callback != null)
{
_callback = () => callback.Invoke(serviceProvider);
}
}
public AppReadyCallbackResolver(IServiceProvider serviceProvider, string[] args, Func<IServiceProvider, string[], Task> callback)
{
if (callback != null)
{
_callback = () => callback.Invoke(serviceProvider, args);
}
}
public bool HasCallback => _callback != null;
public Task Invoke() => _callback?.Invoke() ?? Task.CompletedTask;
}
}

View File

@@ -0,0 +1,11 @@
using System.Threading.Tasks;
namespace ElectronNET.AspNet.Runtime
{
internal interface IAppReadyCallbackResolver
{
public bool HasCallback { get; }
public Task Invoke();
}
}

View File

@@ -0,0 +1,53 @@
namespace ElectronNET.AspNet.Services
{
/// <summary>
/// Implementation of authentication service for Electron clients.
/// Stores and validates the authentication token to ensure only the spawned Electron process can connect.
/// </summary>
public class ElectronAuthenticationService : IElectronAuthenticationService
{
private string _expectedToken;
private readonly object _lock = new object();
/// <inheritdoc />
public void SetExpectedToken(string token)
{
lock (_lock)
{
_expectedToken = token;
}
}
/// <inheritdoc />
public bool ValidateToken(string token)
{
if (string.IsNullOrEmpty(token))
return false;
lock (_lock)
{
if (string.IsNullOrEmpty(_expectedToken))
return false;
// Constant-time comparison to prevent timing attacks
return ConstantTimeEquals(token, _expectedToken);
}
}
/// <summary>
/// Performs constant-time string comparison to prevent timing attacks.
/// </summary>
private static bool ConstantTimeEquals(string a, string b)
{
if (a == null || b == null || a.Length != b.Length)
return false;
var result = 0;
for (int i = 0; i < a.Length; i++)
{
result |= a[i] ^ b[i];
}
return result == 0;
}
}
}

View File

@@ -0,0 +1,24 @@
namespace ElectronNET.AspNet.Services
{
/// <summary>
/// Service for validating authentication tokens from Electron clients.
/// Used to ensure only the Electron process spawned by this .NET instance can connect.
/// </summary>
public interface IElectronAuthenticationService
{
/// <summary>
/// Sets the expected authentication token for this instance.
/// Should be called when launching Electron with the generated token.
/// </summary>
/// <param name="token">The authentication token</param>
void SetExpectedToken(string token);
/// <summary>
/// Validates an incoming token against the expected token.
/// Uses constant-time comparison to prevent timing attacks.
/// </summary>
/// <param name="token">The token to validate</param>
/// <returns>True if token is valid, false otherwise</returns>
bool ValidateToken(string token);
}
}

View File

@@ -70,7 +70,7 @@
<ProjectReference Include="..\ElectronNET.API\ElectronNET.API.csproj" Condition="$(ElectronNetDevMode)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="ElectronNET.Core" Version="0.4.1" Condition="'$(ElectronNetDevMode)' != 'true'" />
<PackageReference Include="ElectronNET.Core" Version="0.6.0" Condition="'$(ElectronNetDevMode)' != 'true'" />
</ItemGroup>
<Import Project="..\ElectronNET\build\ElectronNET.Core.targets" Condition="$(ElectronNetDevMode)" />

View File

@@ -39,6 +39,15 @@
"undici-types": "~7.14.0"
}
},
"node_modules/@types/ws": {
"version": "8.18.1",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
"integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/accepts": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
@@ -101,20 +110,21 @@
}
},
"node_modules/engine.io": {
"version": "6.6.4",
"resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.6.4.tgz",
"integrity": "sha512-ZCkIjSYNDyGn0R6ewHDtXgns/Zre/NT6Agvq1/WobF7JXgFff4SeDroKiCO3fNJreU9YG429Sc81o4w5ok/W5g==",
"version": "6.6.8",
"resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.6.8.tgz",
"integrity": "sha512-2agL3ueZhqxoVrfmntO8yuVj+uNSlIOnhykYHk3Cq0ShYPdUjjUiSJrQvXjq01I9jAuI0Zl2YO8Evv5Mqytm5g==",
"license": "MIT",
"dependencies": {
"@types/cors": "^2.8.12",
"@types/node": ">=10.0.0",
"@types/ws": "^8.5.12",
"accepts": "~1.3.4",
"base64id": "2.0.0",
"cookie": "~0.7.2",
"cors": "~2.8.5",
"debug": "~4.3.1",
"debug": "~4.4.1",
"engine.io-parser": "~5.2.1",
"ws": "~8.17.1"
"ws": "~8.20.1"
},
"engines": {
"node": ">=10.2.0"
@@ -129,6 +139,23 @@
"node": ">=10.0.0"
}
},
"node_modules/engine.io/node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
@@ -193,28 +220,62 @@
}
},
"node_modules/socket.io-adapter": {
"version": "2.5.5",
"resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.5.tgz",
"integrity": "sha512-eLDQas5dzPgOWCk9GuuJC2lBqItuhKI4uxGgo9aIV7MYbk2h9Q6uULEh8WBzThoI7l+qU9Ast9fVUmkqPP9wYg==",
"version": "2.5.7",
"resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.7.tgz",
"integrity": "sha512-e0LyK91f3cUxTmv95/KzoLg47+zF+s/sbxRGDNsyG4dmIP8ZSX8ax6byOxfJXeNNtS/8AZlfD+uP7gBeR7DLlg==",
"license": "MIT",
"dependencies": {
"debug": "~4.3.4",
"ws": "~8.17.1"
"debug": "~4.4.1",
"ws": "~8.20.1"
}
},
"node_modules/socket.io-adapter/node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/socket.io-parser": {
"version": "4.2.4",
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz",
"integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==",
"version": "4.2.7",
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.7.tgz",
"integrity": "sha512-IH/iSeO9T6gz1KkFleGDWkG9N3dl4jXVYUtMhIqH10Md0ttMer8nUNWiP1DKuNrybD2xBrixLJdCC9J6ECoYkg==",
"license": "MIT",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.3.1"
"debug": "~4.4.1"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/socket.io-parser/node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
@@ -245,9 +306,9 @@
}
},
"node_modules/ws": {
"version": "8.17.1",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz",
"integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==",
"version": "8.20.1",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.20.1.tgz",
"integrity": "sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"

View File

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.VisualStudio.JavaScript.Sdk/1.0.3864779">
<Project Sdk="Microsoft.VisualStudio.JavaScript.Sdk/1.0.6537497">
<ItemGroup>
<None Include=".vscode\tasks.json" />
</ItemGroup>

View File

@@ -1,6 +1,14 @@
"use strict";
const electron_updater_1 = require("electron-updater");
let electronSocket;
function normalize(updateInfo) {
if (typeof updateInfo?.releaseNotes === "string") {
updateInfo.releaseNotes = [{ note: updateInfo.releaseNotes }];
}
else if (Array.isArray(updateInfo?.releaseNotes)) {
updateInfo.releaseNotes = updateInfo.releaseNotes.map((entry) => typeof entry === "string" ? { note: entry } : entry);
}
}
module.exports = (socket) => {
electronSocket = socket;
socket.on("register-autoUpdater-error", (id) => {
@@ -15,11 +23,13 @@ module.exports = (socket) => {
});
socket.on("register-autoUpdater-update-available", (id) => {
electron_updater_1.autoUpdater.on("update-available", (updateInfo) => {
normalize(updateInfo);
electronSocket.emit("autoUpdater-update-available" + id, updateInfo);
});
});
socket.on("register-autoUpdater-update-not-available", (id) => {
electron_updater_1.autoUpdater.on("update-not-available", (updateInfo) => {
normalize(updateInfo);
electronSocket.emit("autoUpdater-update-not-available" + id, updateInfo);
});
});
@@ -30,6 +40,7 @@ module.exports = (socket) => {
});
socket.on("register-autoUpdater-update-downloaded", (id) => {
electron_updater_1.autoUpdater.on("update-downloaded", (updateInfo) => {
normalize(updateInfo);
electronSocket.emit("autoUpdater-update-downloaded" + id, updateInfo);
});
});
@@ -89,6 +100,7 @@ module.exports = (socket) => {
electron_updater_1.autoUpdater
.checkForUpdatesAndNotify()
.then((updateCheckResult) => {
normalize(updateCheckResult?.updateInfo);
electronSocket.emit("autoUpdater-checkForUpdatesAndNotify-completed" + guid, updateCheckResult);
})
.catch((error) => {
@@ -99,6 +111,7 @@ module.exports = (socket) => {
electron_updater_1.autoUpdater
.checkForUpdates()
.then((updateCheckResult) => {
normalize(updateCheckResult?.updateInfo);
electronSocket.emit("autoUpdater-checkForUpdates-completed" + guid, updateCheckResult);
})
.catch((error) => {

File diff suppressed because one or more lines are too long

View File

@@ -3,6 +3,16 @@ import { autoUpdater } from "electron-updater";
let electronSocket: Socket;
function normalize(updateInfo) {
if (typeof updateInfo?.releaseNotes === "string") {
updateInfo.releaseNotes = [{ note: updateInfo.releaseNotes }];
} else if (Array.isArray(updateInfo?.releaseNotes)) {
updateInfo.releaseNotes = updateInfo.releaseNotes.map((entry) =>
typeof entry === "string" ? { note: entry } : entry,
);
}
}
export = (socket: Socket) => {
electronSocket = socket;
@@ -20,12 +30,14 @@ export = (socket: Socket) => {
socket.on("register-autoUpdater-update-available", (id) => {
autoUpdater.on("update-available", (updateInfo) => {
normalize(updateInfo);
electronSocket.emit("autoUpdater-update-available" + id, updateInfo);
});
});
socket.on("register-autoUpdater-update-not-available", (id) => {
autoUpdater.on("update-not-available", (updateInfo) => {
normalize(updateInfo);
electronSocket.emit("autoUpdater-update-not-available" + id, updateInfo);
});
});
@@ -38,6 +50,7 @@ export = (socket: Socket) => {
socket.on("register-autoUpdater-update-downloaded", (id) => {
autoUpdater.on("update-downloaded", (updateInfo) => {
normalize(updateInfo);
electronSocket.emit("autoUpdater-update-downloaded" + id, updateInfo);
});
});
@@ -143,6 +156,7 @@ export = (socket: Socket) => {
autoUpdater
.checkForUpdatesAndNotify()
.then((updateCheckResult) => {
normalize(updateCheckResult?.updateInfo);
electronSocket.emit(
"autoUpdater-checkForUpdatesAndNotify-completed" + guid,
updateCheckResult,
@@ -160,6 +174,7 @@ export = (socket: Socket) => {
autoUpdater
.checkForUpdates()
.then((updateCheckResult) => {
normalize(updateCheckResult?.updateInfo);
electronSocket.emit(
"autoUpdater-checkForUpdates-completed" + guid,
updateCheckResult,

View File

@@ -39,7 +39,6 @@ const windows = (global["browserWindows"] =
global["browserWindows"] || []);
let readyToShowWindowsIds = [];
let window;
let lastOptions;
let electronSocket;
const proxyToCredentialsMap = (global["proxyToCredentialsMap"] = global["proxyToCredentialsMap"] || []);
module.exports = (socket, app) => {
@@ -203,6 +202,18 @@ module.exports = (socket, app) => {
});
});
socket.on("createBrowserWindow", (options, loadUrl) => {
createWindow(options, loadUrl, "BrowserWindowCreated");
});
// Allows the host (main.js) to bring the main window back when the app is activated
// again on macOS after all windows have been closed.
global["recreateMainWindow"] = () => {
if (electron_1.BrowserWindow.getAllWindows().length > 0 || !app["mainWindowOptions"]) {
return false;
}
createWindow(app["mainWindowOptions"], app["mainWindowURL"], "BrowserWindowRecreated");
return true;
};
function createWindow(options, loadUrl, createdEventName) {
if (options.webPreferences &&
!("nodeIntegration" in options.webPreferences)) {
options = {
@@ -226,18 +237,19 @@ module.exports = (socket, app) => {
delete options.isRunningBlazor;
// we dont want to recreate the window when watch is ready.
if (app.commandLine.hasSwitch("watch") &&
app["mainWindowURL"] === loadUrl) {
app["mainWindowURL"] === loadUrl &&
app["mainWindow"] &&
!app["mainWindow"].isDestroyed()) {
window = app["mainWindow"];
if (window) {
window.reload();
window.reload();
synchronizeWindowRegistry();
if (!windows.some((entry) => tryGetWindowId(entry) === window.id)) {
windows.push(window);
electronSocket.emit("BrowserWindowCreated", window.id);
return;
}
electronSocket.emit(createdEventName, window.id);
return;
}
else {
window = new electron_1.BrowserWindow(options);
}
window = new electron_1.BrowserWindow(options);
if (options.proxy) {
window.webContents.session.setProxy({ proxyRules: options.proxy });
}
@@ -252,32 +264,32 @@ module.exports = (socket, app) => {
readyToShowWindowsIds.push(window.id);
}
});
lastOptions = options;
window.on("closed", (sender) => {
for (let index = 0; index < windows.length; index++) {
const windowItem = windows[index];
try {
windowItem.id;
}
catch (error) {
if (error.message === "Object has been destroyed") {
windows.splice(index, 1);
const ids = [];
windows.forEach((x) => ids.push(x.id));
electronSocket.emit("BrowserWindowClosed", ids);
}
}
}
});
app.on("activate", () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (window === null && lastOptions) {
window = new electron_1.BrowserWindow(lastOptions);
}
window.on("closed", () => {
synchronizeWindowRegistry();
emitBrowserWindowClosed();
});
if (loadUrl) {
window.loadURL(loadUrl);
// Append authentication token to initial URL if available
const token = global["authToken"];
if (token) {
try {
const url = new URL(loadUrl);
const isLocal = url.hostname === "localhost" ||
url.hostname === "127.0.0.1" ||
url.hostname === "::1";
if (isLocal) {
url.searchParams.set("token", token);
}
window.loadURL(url.toString());
}
catch {
// Handle invalid URLs or file:// URLs if needed
window.loadURL(loadUrl);
}
}
else {
window.loadURL(loadUrl);
}
}
if (app.commandLine.hasSwitch("clear-cache") &&
app.commandLine.getSwitchValue("clear-cache")) {
@@ -288,10 +300,14 @@ module.exports = (socket, app) => {
if (app["mainWindowURL"] == undefined || app["mainWindowURL"] == "") {
app["mainWindowURL"] = loadUrl;
app["mainWindow"] = window;
app["mainWindowOptions"] = options;
}
else if (app["mainWindowURL"] === loadUrl) {
app["mainWindow"] = window;
}
windows.push(window);
electronSocket.emit("BrowserWindowCreated", window.id);
});
electronSocket.emit(createdEventName, window.id);
}
socket.on("browserWindowDestroy", (id) => {
getWindowById(id).destroy();
});
@@ -683,12 +699,47 @@ module.exports = (socket, app) => {
getWindowById(id).setBrowserView((0, browserView_1.browserViewMediateService)(browserViewId));
});
function getWindowById(id) {
const runtimeWindow = electron_1.BrowserWindow.fromId(id);
if (runtimeWindow) {
return runtimeWindow;
}
synchronizeWindowRegistry();
for (let index = 0; index < windows.length; index++) {
const element = windows[index];
if (element.id === id) {
if (tryGetWindowId(element) === id) {
return element;
}
}
throw new Error(`BrowserWindow with id '${id}' was not found.`);
}
function tryGetWindowId(element) {
try {
return element.id;
}
catch {
return null;
}
}
function synchronizeWindowRegistry() {
const runtimeWindows = electron_1.BrowserWindow.getAllWindows();
const runtimeWindowIds = new Set(runtimeWindows.map((entry) => entry.id));
for (let index = windows.length - 1; index >= 0; index--) {
const windowId = tryGetWindowId(windows[index]);
if (windowId === null || !runtimeWindowIds.has(windowId)) {
windows.splice(index, 1);
}
}
readyToShowWindowsIds = readyToShowWindowsIds.filter((entryId) => runtimeWindowIds.has(entryId));
}
function emitBrowserWindowClosed() {
const ids = [];
for (const entry of windows) {
const windowId = tryGetWindowId(entry);
if (windowId !== null) {
ids.push(windowId);
}
}
electronSocket.emit("BrowserWindowClosed", ids);
}
};
//# sourceMappingURL=browserWindows.js.map

File diff suppressed because one or more lines are too long

View File

@@ -6,10 +6,10 @@ import { browserViewMediateService } from "./browserView";
const windows: Electron.BrowserWindow[] = (global["browserWindows"] =
global["browserWindows"] || []) as Electron.BrowserWindow[];
let readyToShowWindowsIds: number[] = [];
let window;
let lastOptions;
let electronSocket;
const proxyToCredentialsMap: { [proxy: string]: string } = (global[
@@ -216,6 +216,26 @@ export = (socket: Socket, app: Electron.App) => {
});
socket.on("createBrowserWindow", (options, loadUrl) => {
createWindow(options, loadUrl, "BrowserWindowCreated");
});
// Allows the host (main.js) to bring the main window back when the app is activated
// again on macOS after all windows have been closed.
global["recreateMainWindow"] = () => {
if (BrowserWindow.getAllWindows().length > 0 || !app["mainWindowOptions"]) {
return false;
}
createWindow(
app["mainWindowOptions"],
app["mainWindowURL"],
"BrowserWindowRecreated",
);
return true;
};
function createWindow(options, loadUrl, createdEventName: string) {
if (
options.webPreferences &&
!("nodeIntegration" in options.webPreferences)
@@ -249,19 +269,24 @@ export = (socket: Socket, app: Electron.App) => {
// we dont want to recreate the window when watch is ready.
if (
app.commandLine.hasSwitch("watch") &&
app["mainWindowURL"] === loadUrl
app["mainWindowURL"] === loadUrl &&
app["mainWindow"] &&
!app["mainWindow"].isDestroyed()
) {
window = app["mainWindow"];
if (window) {
window.reload();
window.reload();
synchronizeWindowRegistry();
if (!windows.some((entry) => tryGetWindowId(entry) === window.id)) {
windows.push(window);
electronSocket.emit("BrowserWindowCreated", window.id);
return;
}
} else {
window = new BrowserWindow(options);
electronSocket.emit(createdEventName, window.id);
return;
}
window = new BrowserWindow(options);
if (options.proxy) {
window.webContents.session.setProxy({ proxyRules: options.proxy });
}
@@ -280,35 +305,36 @@ export = (socket: Socket, app: Electron.App) => {
}
});
lastOptions = options;
window.on("closed", (sender) => {
for (let index = 0; index < windows.length; index++) {
const windowItem = windows[index];
try {
windowItem.id;
} catch (error) {
if (error.message === "Object has been destroyed") {
windows.splice(index, 1);
const ids = [];
windows.forEach((x) => ids.push(x.id));
electronSocket.emit("BrowserWindowClosed", ids);
}
}
}
});
app.on("activate", () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (window === null && lastOptions) {
window = new BrowserWindow(lastOptions);
}
window.on("closed", () => {
synchronizeWindowRegistry();
emitBrowserWindowClosed();
});
if (loadUrl) {
window.loadURL(loadUrl);
// Append authentication token to initial URL if available
const token = global["authToken"];
if (token) {
try {
const url = new URL(loadUrl);
const isLocal =
url.hostname === "localhost" ||
url.hostname === "127.0.0.1" ||
url.hostname === "::1";
if (isLocal) {
url.searchParams.set("token", token);
}
window.loadURL(url.toString());
} catch {
// Handle invalid URLs or file:// URLs if needed
window.loadURL(loadUrl);
}
} else {
window.loadURL(loadUrl);
}
}
if (
@@ -323,11 +349,14 @@ export = (socket: Socket, app: Electron.App) => {
if (app["mainWindowURL"] == undefined || app["mainWindowURL"] == "") {
app["mainWindowURL"] = loadUrl;
app["mainWindow"] = window;
app["mainWindowOptions"] = options;
} else if (app["mainWindowURL"] === loadUrl) {
app["mainWindow"] = window;
}
windows.push(window);
electronSocket.emit("BrowserWindowCreated", window.id);
});
electronSocket.emit(createdEventName, window.id);
}
socket.on("browserWindowDestroy", (id) => {
getWindowById(id).destroy();
@@ -883,11 +912,57 @@ export = (socket: Socket, app: Electron.App) => {
});
function getWindowById(id: number): Electron.BrowserWindow {
const runtimeWindow = BrowserWindow.fromId(id);
if (runtimeWindow) {
return runtimeWindow;
}
synchronizeWindowRegistry();
for (let index = 0; index < windows.length; index++) {
const element = windows[index];
if (element.id === id) {
if (tryGetWindowId(element) === id) {
return element;
}
}
throw new Error(`BrowserWindow with id '${id}' was not found.`);
}
function tryGetWindowId(element: Electron.BrowserWindow): number | null {
try {
return element.id;
} catch {
return null;
}
}
function synchronizeWindowRegistry(): void {
const runtimeWindows = BrowserWindow.getAllWindows();
const runtimeWindowIds = new Set(runtimeWindows.map((entry) => entry.id));
for (let index = windows.length - 1; index >= 0; index--) {
const windowId = tryGetWindowId(windows[index]);
if (windowId === null || !runtimeWindowIds.has(windowId)) {
windows.splice(index, 1);
}
}
readyToShowWindowsIds = readyToShowWindowsIds.filter((entryId) =>
runtimeWindowIds.has(entryId),
);
}
function emitBrowserWindowClosed(): void {
const ids: number[] = [];
for (const entry of windows) {
const windowId = tryGetWindowId(entry);
if (windowId !== null) {
ids.push(windowId);
}
}
electronSocket.emit("BrowserWindowClosed", ids);
}
};

View File

@@ -111,6 +111,41 @@ module.exports = (socket) => {
electronSocket.emit("webContents-domReady" + id);
});
});
socket.on("register-webContents-zoomChanged", (id) => {
const browserWindow = getWindowById(id);
browserWindow.webContents.removeAllListeners("zoom-changed");
browserWindow.webContents.on("zoom-changed", (_, zoomDirection) => {
electronSocket.emit("webContents-zoomChanged" + id, zoomDirection);
});
});
socket.on("register-webContents-foundInPage", (id) => {
const browserWindow = getWindowById(id);
browserWindow.webContents.removeAllListeners("found-in-page");
browserWindow.webContents.on("found-in-page", (_, result) => {
electronSocket.emit("webContents-foundInPage" + id, result);
});
});
socket.on("register-webContents-audioStateChanged", (id) => {
const browserWindow = getWindowById(id);
browserWindow.webContents.removeAllListeners("audio-state-changed");
browserWindow.webContents.on("audio-state-changed", (event) => {
electronSocket.emit("webContents-audioStateChanged" + id, event.audible);
});
});
socket.on("register-webContents-mediaStartedPlaying", (id) => {
const browserWindow = getWindowById(id);
browserWindow.webContents.removeAllListeners("media-started-playing");
browserWindow.webContents.on("media-started-playing", () => {
electronSocket.emit("webContents-mediaStartedPlaying" + id);
});
});
socket.on("register-webContents-mediaPaused", (id) => {
const browserWindow = getWindowById(id);
browserWindow.webContents.removeAllListeners("media-paused");
browserWindow.webContents.on("media-paused", () => {
electronSocket.emit("webContents-mediaPaused" + id);
});
});
socket.on("webContents-openDevTools", (id, options) => {
if (options) {
getWindowById(id).webContents.openDevTools(options);
@@ -308,6 +343,36 @@ module.exports = (socket) => {
electronSocket.emit("webContents-loadURL-error" + id, error);
});
});
socket.on("webContents-loadFile", (id, filePath, options) => {
const browserWindow = getWindowById(id);
browserWindow.webContents
.loadFile(filePath, options ?? undefined)
.then(() => {
electronSocket.emit("webContents-loadFile-complete" + id);
})
.catch((error) => {
console.error(error);
electronSocket.emit("webContents-loadFile-error" + id, error);
});
});
socket.on("webContents-isLoading", (id) => {
electronSocket.emit("webContents-isLoading-completed", getWindowById(id).webContents.isLoading());
});
socket.on("webContents-isLoadingMainFrame", (id) => {
electronSocket.emit("webContents-isLoadingMainFrame-completed", getWindowById(id).webContents.isLoadingMainFrame());
});
socket.on("webContents-isWaitingForResponse", (id) => {
electronSocket.emit("webContents-isWaitingForResponse-completed", getWindowById(id).webContents.isWaitingForResponse());
});
socket.on("webContents-reload", (id) => {
getWindowById(id).webContents.reload();
});
socket.on("webContents-reloadIgnoringCache", (id) => {
getWindowById(id).webContents.reloadIgnoringCache();
});
socket.on("webContents-stop", (id) => {
getWindowById(id).webContents.stop();
});
socket.on("webContents-insertCSS", (id, isBrowserWindow, path) => {
if (isBrowserWindow) {
const browserWindow = getWindowById(id);
@@ -330,6 +395,14 @@ module.exports = (socket) => {
}
}
});
socket.on("webContents-insertCSSText", async (id, css, cssOrigin) => {
const key = await getWindowById(id).webContents.insertCSS(css, cssOrigin ? { cssOrigin } : undefined);
electronSocket.emit("webContents-insertCSSText-completed" + id, key);
});
socket.on("webContents-removeInsertedCSS", async (id, key) => {
await getWindowById(id).webContents.removeInsertedCSS(key);
electronSocket.emit("webContents-removeInsertedCSS-completed" + id);
});
socket.on("webContents-session-getAllExtensions", (id) => {
const browserWindow = getWindowById(id);
const extensionsList = browserWindow.webContents.session.getAllExtensions();
@@ -403,6 +476,65 @@ module.exports = (socket) => {
socket.on("webContents-setUserAgent", (id, userAgent) => {
getWindowById(id).webContents.setUserAgent(userAgent);
});
socket.on("webContents-undo", (id) => {
getWindowById(id).webContents.undo();
});
socket.on("webContents-redo", (id) => {
getWindowById(id).webContents.redo();
});
socket.on("webContents-cut", (id) => {
getWindowById(id).webContents.cut();
});
socket.on("webContents-copy", (id) => {
getWindowById(id).webContents.copy();
});
socket.on("webContents-copyImageAt", (id, x, y) => {
getWindowById(id).webContents.copyImageAt(x, y);
});
socket.on("webContents-paste", (id) => {
getWindowById(id).webContents.paste();
});
socket.on("webContents-pasteAndMatchStyle", (id) => {
getWindowById(id).webContents.pasteAndMatchStyle();
});
socket.on("webContents-delete", (id) => {
getWindowById(id).webContents.delete();
});
socket.on("webContents-selectAll", (id) => {
getWindowById(id).webContents.selectAll();
});
socket.on("webContents-unselect", (id) => {
getWindowById(id).webContents.unselect();
});
socket.on("webContents-adjustSelection", (id, options) => {
getWindowById(id).webContents.adjustSelection(options ?? {});
});
socket.on("webContents-centerSelection", (id) => {
getWindowById(id).webContents.centerSelection();
});
socket.on("webContents-scrollToTop", (id) => {
getWindowById(id).webContents.scrollToTop();
});
socket.on("webContents-scrollToBottom", (id) => {
getWindowById(id).webContents.scrollToBottom();
});
socket.on("webContents-insertText", async (id, text) => {
await getWindowById(id).webContents.insertText(text);
electronSocket.emit("webContents-insertText-completed" + id);
});
socket.on("webContents-replace", (id, text) => {
getWindowById(id).webContents.replace(text);
});
socket.on("webContents-replaceMisspelling", (id, text) => {
getWindowById(id).webContents.replaceMisspelling(text);
});
socket.on("webContents-findInPage", (id, text, options) => {
const requestId = getWindowById(id).webContents.findInPage(text, options ?? undefined);
electronSocket.emit("webContents-findInPage-completed" + id, requestId);
});
socket.on("webContents-stopFindInPage", (id, action) => {
getWindowById(id).webContents.stopFindInPage(action);
});
function getWindowById(id) {
if (id >= 1000) {
return (0, browserView_1.browserViewMediateService)(id - 1000);

File diff suppressed because one or more lines are too long

View File

@@ -103,6 +103,51 @@ export = (socket: Socket) => {
});
});
socket.on("register-webContents-zoomChanged", (id) => {
const browserWindow = getWindowById(id);
browserWindow.webContents.removeAllListeners("zoom-changed");
browserWindow.webContents.on("zoom-changed", (_, zoomDirection) => {
electronSocket.emit("webContents-zoomChanged" + id, zoomDirection);
});
});
socket.on("register-webContents-foundInPage", (id) => {
const browserWindow = getWindowById(id);
browserWindow.webContents.removeAllListeners("found-in-page");
browserWindow.webContents.on("found-in-page", (_, result) => {
electronSocket.emit("webContents-foundInPage" + id, result);
});
});
socket.on("register-webContents-audioStateChanged", (id) => {
const browserWindow = getWindowById(id);
browserWindow.webContents.removeAllListeners("audio-state-changed");
browserWindow.webContents.on("audio-state-changed", (event) => {
electronSocket.emit("webContents-audioStateChanged" + id, event.audible);
});
});
socket.on("register-webContents-mediaStartedPlaying", (id) => {
const browserWindow = getWindowById(id);
browserWindow.webContents.removeAllListeners("media-started-playing");
browserWindow.webContents.on("media-started-playing", () => {
electronSocket.emit("webContents-mediaStartedPlaying" + id);
});
});
socket.on("register-webContents-mediaPaused", (id) => {
const browserWindow = getWindowById(id);
browserWindow.webContents.removeAllListeners("media-paused");
browserWindow.webContents.on("media-paused", () => {
electronSocket.emit("webContents-mediaPaused" + id);
});
});
socket.on("webContents-openDevTools", (id, options) => {
if (options) {
getWindowById(id).webContents.openDevTools(options);
@@ -409,6 +454,52 @@ export = (socket: Socket) => {
});
});
socket.on("webContents-loadFile", (id, filePath, options) => {
const browserWindow = getWindowById(id);
browserWindow.webContents
.loadFile(filePath, options ?? undefined)
.then(() => {
electronSocket.emit("webContents-loadFile-complete" + id);
})
.catch((error) => {
console.error(error);
electronSocket.emit("webContents-loadFile-error" + id, error);
});
});
socket.on("webContents-isLoading", (id) => {
electronSocket.emit(
"webContents-isLoading-completed",
getWindowById(id).webContents.isLoading(),
);
});
socket.on("webContents-isLoadingMainFrame", (id) => {
electronSocket.emit(
"webContents-isLoadingMainFrame-completed",
getWindowById(id).webContents.isLoadingMainFrame(),
);
});
socket.on("webContents-isWaitingForResponse", (id) => {
electronSocket.emit(
"webContents-isWaitingForResponse-completed",
getWindowById(id).webContents.isWaitingForResponse(),
);
});
socket.on("webContents-reload", (id) => {
getWindowById(id).webContents.reload();
});
socket.on("webContents-reloadIgnoringCache", (id) => {
getWindowById(id).webContents.reloadIgnoringCache();
});
socket.on("webContents-stop", (id) => {
getWindowById(id).webContents.stop();
});
socket.on("webContents-insertCSS", (id, isBrowserWindow, path) => {
if (isBrowserWindow) {
const browserWindow = getWindowById(id);
@@ -431,6 +522,19 @@ export = (socket: Socket) => {
}
});
socket.on("webContents-insertCSSText", async (id, css, cssOrigin) => {
const key = await getWindowById(id).webContents.insertCSS(
css,
cssOrigin ? { cssOrigin } : undefined,
);
electronSocket.emit("webContents-insertCSSText-completed" + id, key);
});
socket.on("webContents-removeInsertedCSS", async (id, key) => {
await getWindowById(id).webContents.removeInsertedCSS(key);
electronSocket.emit("webContents-removeInsertedCSS-completed" + id);
});
socket.on("webContents-session-getAllExtensions", (id) => {
const browserWindow = getWindowById(id);
const extensionsList = browserWindow.webContents.session.getAllExtensions();
@@ -557,6 +661,87 @@ export = (socket: Socket) => {
getWindowById(id).webContents.setUserAgent(userAgent);
});
socket.on("webContents-undo", (id) => {
getWindowById(id).webContents.undo();
});
socket.on("webContents-redo", (id) => {
getWindowById(id).webContents.redo();
});
socket.on("webContents-cut", (id) => {
getWindowById(id).webContents.cut();
});
socket.on("webContents-copy", (id) => {
getWindowById(id).webContents.copy();
});
socket.on("webContents-copyImageAt", (id, x, y) => {
getWindowById(id).webContents.copyImageAt(x, y);
});
socket.on("webContents-paste", (id) => {
getWindowById(id).webContents.paste();
});
socket.on("webContents-pasteAndMatchStyle", (id) => {
getWindowById(id).webContents.pasteAndMatchStyle();
});
socket.on("webContents-delete", (id) => {
getWindowById(id).webContents.delete();
});
socket.on("webContents-selectAll", (id) => {
getWindowById(id).webContents.selectAll();
});
socket.on("webContents-unselect", (id) => {
getWindowById(id).webContents.unselect();
});
socket.on("webContents-adjustSelection", (id, options) => {
getWindowById(id).webContents.adjustSelection(options ?? {});
});
socket.on("webContents-centerSelection", (id) => {
getWindowById(id).webContents.centerSelection();
});
socket.on("webContents-scrollToTop", (id) => {
getWindowById(id).webContents.scrollToTop();
});
socket.on("webContents-scrollToBottom", (id) => {
getWindowById(id).webContents.scrollToBottom();
});
socket.on("webContents-insertText", async (id, text) => {
await getWindowById(id).webContents.insertText(text);
electronSocket.emit("webContents-insertText-completed" + id);
});
socket.on("webContents-replace", (id, text) => {
getWindowById(id).webContents.replace(text);
});
socket.on("webContents-replaceMisspelling", (id, text) => {
getWindowById(id).webContents.replaceMisspelling(text);
});
socket.on("webContents-findInPage", (id, text, options) => {
const requestId = getWindowById(id).webContents.findInPage(
text,
options ?? undefined,
);
electronSocket.emit("webContents-findInPage-completed" + id, requestId);
});
socket.on("webContents-stopFindInPage", (id, action) => {
getWindowById(id).webContents.stopFindInPage(action);
});
function getWindowById(
id: number,
): Electron.BrowserWindow | Electron.BrowserView {

View File

@@ -1,10 +1,14 @@
const { app } = require('electron');
const { BrowserWindow } = require('electron');
const { protocol } = require('electron');
const { createServer } = require('http');
const { randomUUID } = require('crypto');
const { Server } = require('socket.io');
const { platform } = require('os');
const path = require('path');
const fs = require('fs');
const cProcess = require('child_process').spawn;
const portscanner = require('portscanner');
const { imageSize } = require('image-size');
let io, server, browserWindows, ipc, apiProcess, loadURL;
let appApi, menu, dialogApi, notification, tray, webContents;
let globalShortcut, shellApi, screen, clipboard, autoUpdater;
@@ -16,35 +20,20 @@ let nativeTheme;
let dock;
let launchFile;
let launchUrl;
let processApi;
let manifestJsonFileName = 'package.json';
let unpackedelectron = false;
let unpackeddotnet = false;
let dotnetpacked = false;
let electronforcedport;
let electronUrl;
let authToken = randomUUID().split('-').join('');
if (app.commandLine.hasSwitch('manifest')) {
manifestJsonFileName = app.commandLine.getSwitchValue('manifest');
}
console.log('Entry!!!: ');
if (app.commandLine.hasSwitch('unpackedelectron')) {
unpackedelectron = true;
}
else if (app.commandLine.hasSwitch('unpackeddotnet')) {
unpackeddotnet = true;
}
else if (app.commandLine.hasSwitch('dotnetpacked')) {
dotnetpacked = true;
}
if (app.commandLine.hasSwitch('electronforcedport')) {
electronforcedport = app.commandLine.getSwitchValue('electronforcedport');
}
// Store in global for access by browser windows
global.authToken = authToken;
// Custom startup hook: look for custom_main.js and invoke its onStartup(host) if present.
// Runs before any command line switch is evaluated so the hook can still modify them.
// If the hook returns false, abort Electron startup.
try {
const fs = require('fs');
@@ -67,13 +56,35 @@ try {
console.error('Error while executing custom_main.js:', err);
}
if (app.commandLine.hasSwitch('manifest')) {
manifestJsonFileName = app.commandLine.getSwitchValue('manifest');
}
if (app.commandLine.hasSwitch('unpackedelectron')) {
unpackedelectron = true;
}
else if (app.commandLine.hasSwitch('unpackeddotnet')) {
unpackeddotnet = true;
}
else if (app.commandLine.hasSwitch('dotnetpacked')) {
dotnetpacked = true;
}
if (app.commandLine.hasSwitch('electronforcedport')) {
electronforcedport = +app.commandLine.getSwitchValue('electronforcedport');
}
if (app.commandLine.hasSwitch('electronurl')) {
electronUrl = app.commandLine.getSwitchValue('electronurl');
}
const currentPath = __dirname;
let currentBinPath = path.join(currentPath.replace('app.asar', ''), 'bin');
let manifestJsonFilePath = path.join(currentPath, manifestJsonFileName);
// if running unpackedelectron, lets change the path
if (unpackedelectron || unpackeddotnet) {
console.log('unpackedelectron! dir: ' + currentPath);
console.debug('Running in unpackaged mode, dir: ' + currentPath);
manifestJsonFilePath = path.join(currentPath, manifestJsonFileName);
currentBinPath = path.join(currentPath, '../'); // go to project directory
@@ -93,9 +104,44 @@ app.on('will-finish-launching', () => {
const manifestJsonFile = require(manifestJsonFilePath);
// Brings the app back to the foreground: focuses an already existing window or - if
// all windows have been closed (which keeps the app alive on macOS) - recreates the
// main window.
function activateApp() {
const windows = BrowserWindow.getAllWindows().filter((window) => !window.isDestroyed());
if (!windows.length) {
return typeof global.recreateMainWindow === 'function' && global.recreateMainWindow();
}
const target = windows.find((window) => window.isVisible()) || windows[0];
if (target.isMinimized()) {
target.restore();
}
if (!target.isVisible()) {
target.show();
}
target.focus();
if (platform() === 'darwin') {
// On macOS focusing a window does not necessarily bring the app itself to the front
app.focus({ steal: true });
}
return true;
}
if (manifestJsonFile.singleInstance) {
const mainInstance = app.requestSingleInstanceLock();
app.on('second-instance', (events, args = []) => {
if (!app.requestSingleInstanceLock()) {
// Another instance already owns the lock. Exit right away so that neither the
// socket bridge nor the .NET backend process of this instance is started.
app.exit(0);
}
app.on('second-instance', (event, args = []) => {
args.forEach((parameter) => {
const words = parameter.split('=');
@@ -106,24 +152,21 @@ if (manifestJsonFile.singleInstance) {
}
});
const windows = BrowserWindow.getAllWindows();
if (windows.length) {
if (windows[0].isMinimized()) {
windows[0].restore();
}
windows[0].focus();
}
activateApp();
});
if (!mainInstance) {
app.quit();
}
}
// On macOS launching an already running app (or clicking its dock icon) does not
// start a second instance - the 'activate' event is raised instead.
app.on('activate', () => {
activateApp();
});
// Collect user supplied command line args (excluding those handled by Electron host itself)
function getForwardedArgs() {
const skipSwitches = new Set(['unpackedelectron', 'unpackeddotnet', 'dotnetpacked']);
return process.argv.slice(2).filter(arg => {
const sliceIndex = app.isPackaged ? 1 : 2;
return process.argv.slice(sliceIndex).filter(arg => {
if (!arg) return false;
// Node/Electron internal or we already process them
if (arg.startsWith('--manifest')) return false;
@@ -133,6 +176,7 @@ function getForwardedArgs() {
if (cleaned.startsWith('remote-debugging-port')) return false;
// We add /electronPort ourselves later
if (cleaned.startsWith('electronPort=')) return false;
if (cleaned.startsWith('electronHost=')) return false;
if (cleaned.startsWith('electronWebPort=')) return false;
return true;
});
@@ -153,44 +197,38 @@ app.on('ready', () => {
}
if (electronforcedport) {
console.log('Electron Socket IO (forced) Port: ' + electronforcedport);
console.info('Electron Socket IO (forced) Port: ' + electronforcedport);
startSocketApiBridge(electronforcedport);
return;
} else {
console.info('Electron Socket dynamic IO Port');
startSocketApiBridge(0);
}
// Added default port as configurable for port restricted environments.
let defaultElectronPort = 8000;
if (manifestJsonFile.electronPort) {
defaultElectronPort = manifestJsonFile.electronPort;
}
// hostname needs to be localhost, otherwise Windows Firewall will be triggered.
portscanner.findAPortNotInUse(defaultElectronPort, 65535, 'localhost', function (error, port) {
console.log('Electron Socket IO Port: ' + port);
startSocketApiBridge(port);
});
});
app.on('quit', async (event, exitCode) => {
try {
server.close();
server.closeAllConnections();
} catch (e) {
console.error(e);
}
try {
apiProcess?.kill();
} catch (e) {
console.error(e);
}
try {
if (io && typeof io.close === 'function') {
io.close();
if (server) {
try {
server.close();
server.closeAllConnections();
} catch (e) {
console.error(e);
}
}
if (apiProcess) {
try {
apiProcess.kill();
} catch (e) {
console.error(e);
}
}
if (io && io.close) {
try {
io.close();
} catch (e) {
console.error(e);
}
} catch (e) {
console.error(e);
}
});
@@ -246,9 +284,7 @@ function startSplashScreen() {
// it's an image, so we can compute the desired splash screen size
imageSize(imageFile, (error, dimensions) => {
if (error) {
console.log(`load splashscreen error:`);
console.error(error);
console.error(`load splashscreen error:`, error);
throw new Error(error.message);
}
@@ -259,9 +295,8 @@ function startSplashScreen() {
function startSocketApiBridge(port) {
// instead of 'require('socket.io')(port);' we need to use this workaround
// otherwise the Windows Firewall will be triggered
console.log('Electron Socket: starting...');
server = require('http').createServer();
const { Server } = require('socket.io');
console.debug('Electron Socket: starting...');
server = createServer();
let hostHook;
io = new Server({
pingTimeout: 60000, // in ms, default is 5000
@@ -269,14 +304,35 @@ function startSocketApiBridge(port) {
});
io.attach(server);
server.listen(port, 'localhost');
// Never bind to the 'localhost' hostname: it may resolve to ::1 and 127.0.0.1 in any
// order, so server and client can end up on different stacks - which costs a failed
// connection attempt (or a DNS lookup) on every startup.
const hostCandidates = ['127.0.0.1', '::1'];
let hostIndex = 0;
server.on('error', (error) => {
const isUnavailable = error.code === 'EADDRNOTAVAIL' || error.code === 'EAFNOSUPPORT' || error.code === 'EINVAL';
if (isUnavailable && hostIndex + 1 < hostCandidates.length) {
console.warn(`Electron Socket: cannot bind to ${hostCandidates[hostIndex]} (${error.code}), falling back to ${hostCandidates[hostIndex + 1]}.`);
hostIndex++;
server.listen(port, hostCandidates[hostIndex]);
return;
}
console.error('Electron Socket: ' + error.message);
});
server.listen(port, hostCandidates[hostIndex]);
server.on('listening', function () {
console.log('Electron Socket: listening on port %s at %s', server.address().port, server.address().address);
const addr = server.address();
console.info(`Electron Socket: listening on port ${addr.port} at ${addr.address} using ${authToken}`);
// Now that socket connection is established, we can guarantee port will not be open for portscanner
if (unpackedelectron) {
startAspCoreBackendUnpackaged(port);
startAspCoreBackendUnpackaged(addr.port, addr.address);
} else if (!unpackeddotnet && !dotnetpacked) {
startAspCoreBackend(port);
startAspCoreBackend(addr.port, addr.address);
}
});
@@ -286,9 +342,16 @@ function startSocketApiBridge(port) {
// @ts-ignore
io.on('connection', (socket) => {
console.log('Electron Socket: connected!');
console.info('Electron Socket: connected!');
if (authToken && socket.request.headers.authorization !== authToken) {
console.warn('Electron Socket authentication failed!');
socket.disconnect(true);
return;
}
socket.on('disconnect', function (reason) {
console.log('Got disconnect! Reason: ' + reason);
console.debug('Got disconnect! Reason: ' + reason);
try {
////console.log('requireCache');
////console.log(require.cache['electron-host-hook']);
@@ -308,7 +371,7 @@ function startSocketApiBridge(port) {
global['electronsocket'].setMaxListeners(0);
}
console.log('Electron Socket: loading components...');
console.debug('Electron Socket: loading components...');
if (appApi === undefined) appApi = require('./api/app')(socket, app);
if (browserWindows === undefined) browserWindows = require('./api/browserWindows')(socket, app);
@@ -369,11 +432,11 @@ function startSocketApiBridge(port) {
console.error(error.message);
}
console.log('Electron Socket: startup complete.');
console.info('Electron Socket: startup complete.');
});
}
function startAspCoreBackend(electronPort) {
function startAspCoreBackend(electronPort, electronHost) {
startBackend();
function startBackend() {
@@ -382,29 +445,30 @@ function startAspCoreBackend(electronPort) {
const parameters = [
envParam,
`/electronPort=${electronPort}`,
`/electronHost=${electronHost}`,
`/electronPID=${process.pid}`,
`/electronAuthToken=${authToken}`,
// forward user supplied args (avoid duplicate environment)
...forwardedArgs.filter(a => !(envParam && a.startsWith('--environment=')))
].filter(p => p);
let binaryFile = manifestJsonFile.executable;
const os = require('os');
if (os.platform() === 'win32') {
if (platform() === 'win32') {
binaryFile = binaryFile + '.exe';
}
let binFilePath = path.join(currentBinPath, binaryFile);
var options = { cwd: currentBinPath };
console.log('Starting backend with parameters:', parameters.join(' '));
console.debug('Starting backend with parameters:', parameters.join(' '));
apiProcess = cProcess(binFilePath, parameters, options);
apiProcess.stdout.on('data', (data) => {
console.log(`stdout: ${data.toString()}`);
console.debug(`stdout: ${data.toString()}`);
});
}
}
function startAspCoreBackendUnpackaged(electronPort) {
function startAspCoreBackendUnpackaged(electronPort, electronHost) {
startBackend();
function startBackend() {
@@ -413,23 +477,24 @@ function startAspCoreBackendUnpackaged(electronPort) {
const parameters = [
envParam,
`/electronPort=${electronPort}`,
`/electronHost=${electronHost}`,
`/electronPID=${process.pid}`,
`/electronAuthToken=${authToken}`,
...forwardedArgs.filter(a => !(envParam && a.startsWith('--environment=')))
].filter(p => p);
let binaryFile = manifestJsonFile.executable;
const os = require('os');
if (os.platform() === 'win32') {
if (platform() === 'win32') {
binaryFile = binaryFile + '.exe';
}
let binFilePath = path.join(currentBinPath, binaryFile);
var options = { cwd: currentBinPath };
console.log('Starting backend (unpackaged) with parameters:', parameters.join(' '));
console.debug('Starting backend (unpackaged) with parameters:', parameters.join(' '));
apiProcess = cProcess(binFilePath, parameters, options);
apiProcess.stdout.on('data', (data) => {
console.log(`stdout: ${data.toString()}`);
console.debug(`stdout: ${data.toString()}`);
});
}
}

View File

@@ -11,14 +11,13 @@
"dependencies": {
"dasherize": "^2.0.0",
"electron-host-hook": "file:./ElectronHostHook",
"electron-updater": "^6.6.2",
"electron-updater": "^6.8.9",
"image-size": "^1.2.1",
"portscanner": "^2.2.0",
"socket.io": "^4.8.1"
},
"devDependencies": {
"@types/node": "^22.18",
"electron": "^30.0.3",
"electron": "^39.8.10",
"eslint": "^9.39.1",
"typescript": "^5.9.3"
}
@@ -356,6 +355,15 @@
"@types/node": "*"
}
},
"node_modules/@types/ws": {
"version": "8.18.1",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
"integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/yauzl": {
"version": "2.10.3",
"resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.3.tgz",
@@ -442,15 +450,6 @@
"integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
"license": "Python-2.0"
},
"node_modules/async": {
"version": "2.6.4",
"resolved": "https://registry.npmjs.org/async/-/async-2.6.4.tgz",
"integrity": "sha512-mzo5dfJYwAn29PeiJ0zvwTo04zj8HDJj0Mn8TD7sno7q12prdbnasKJHhkm2c1LgrhlJ0teaea8860oxi51mGA==",
"license": "MIT",
"dependencies": {
"lodash": "^4.17.14"
}
},
"node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@@ -477,9 +476,9 @@
"optional": true
},
"node_modules/brace-expansion": {
"version": "1.1.12",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz",
"integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==",
"version": "1.1.16",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.16.tgz",
"integrity": "sha512-IDw48K2/2kRkg9LdJxurvq3lV3aBgq0REY89duEqFRthjlPdXHKMj7EnQOXVckxzgisinf3nHfrcE2FufFLXMw==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -498,9 +497,9 @@
}
},
"node_modules/builder-util-runtime": {
"version": "9.5.1",
"resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.5.1.tgz",
"integrity": "sha512-qt41tMfgHTllhResqM5DcnHyDIWNgzHvuY2jDcYP9iaGpkWxTUzV6GQjDeLnlR1/DtdlcsWQbA7sByMpmJFTLQ==",
"version": "9.7.0",
"resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.7.0.tgz",
"integrity": "sha512-g/kR520giAFYkSXTzcmF3kqQq7wi8F6N6SzeDgZrqTBN+VHdmgWOyTdD1yD7AATDId/yXLvuP34CxW46/BwCdw==",
"license": "MIT",
"dependencies": {
"debug": "^4.3.4",
@@ -763,15 +762,15 @@
"optional": true
},
"node_modules/electron": {
"version": "30.5.1",
"resolved": "https://registry.npmjs.org/electron/-/electron-30.5.1.tgz",
"integrity": "sha512-AhL7+mZ8Lg14iaNfoYTkXQ2qee8mmsQyllKdqxlpv/zrKgfxz6jNVtcRRbQtLxtF8yzcImWdfTQROpYiPumdbw==",
"version": "39.8.10",
"resolved": "https://registry.npmjs.org/electron/-/electron-39.8.10.tgz",
"integrity": "sha512-zbYtGPYUI7PzqLAzkk21Rk6j67WN0hxn0Mq/njErZo1d0HSf33is4f8ICI5fMLy5vYe0JtCtM5sYunNOaochSQ==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
"@electron/get": "^2.0.0",
"@types/node": "^20.9.0",
"@types/node": "^22.7.7",
"extract-zip": "^2.0.1"
},
"bin": {
@@ -786,12 +785,12 @@
"link": true
},
"node_modules/electron-updater": {
"version": "6.8.3",
"resolved": "https://registry.npmjs.org/electron-updater/-/electron-updater-6.8.3.tgz",
"integrity": "sha512-Z6sgw3jgbikWKXei1ENdqFOxBP0WlXg3TtKfz0rgw2vIZFJUyI4pD7ZN7jrkm7EoMK+tcm/qTnPUdqfZukBlBQ==",
"version": "6.8.9",
"resolved": "https://registry.npmjs.org/electron-updater/-/electron-updater-6.8.9.tgz",
"integrity": "sha512-ZhVxM9iGONUpZGI1FxdMRgJjUFXi7AYGVa5PwKlO1tV1/4zDxQmfKpXOHVztKrd6L9rLcFjERvi1Mf2vxyTkig==",
"license": "MIT",
"dependencies": {
"builder-util-runtime": "9.5.1",
"builder-util-runtime": "9.7.0",
"fs-extra": "^10.1.0",
"js-yaml": "^4.1.0",
"lazy-val": "^1.0.5",
@@ -848,16 +847,6 @@
"node": ">= 10.0.0"
}
},
"node_modules/electron/node_modules/@types/node": {
"version": "20.19.33",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.33.tgz",
"integrity": "sha512-Rs1bVAIdBs5gbTIKza/tgpMuG1k3U/UMJLWecIMxNdJFDMzcM5LOiLVRYh3PilWEYDIeUDv7bpiHPLPsbydGcw==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/end-of-stream": {
"version": "1.4.5",
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
@@ -869,20 +858,21 @@
}
},
"node_modules/engine.io": {
"version": "6.6.5",
"resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.6.5.tgz",
"integrity": "sha512-2RZdgEbXmp5+dVbRm0P7HQUImZpICccJy7rN7Tv+SFa55pH+lxnuw6/K1ZxxBfHoYpSkHLAO92oa8O4SwFXA2A==",
"version": "6.6.9",
"resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.6.9.tgz",
"integrity": "sha512-clKkw4C7nJ22mGgoVcCg6V/W/TxdNyIOTr89k2ONZu81qqkddPFDF0LXcbAwhzPD8DjkiRCjzuiO6Y+fkpD4vg==",
"license": "MIT",
"dependencies": {
"@types/cors": "^2.8.12",
"@types/node": ">=10.0.0",
"@types/ws": "^8.5.12",
"accepts": "~1.3.4",
"base64id": "2.0.0",
"cookie": "~0.7.2",
"cors": "~2.8.5",
"debug": "~4.4.1",
"engine.io-parser": "~5.2.1",
"ws": "~8.18.3"
"ws": "~8.21.0"
},
"engines": {
"node": ">=10.2.0"
@@ -1201,9 +1191,9 @@
}
},
"node_modules/flatted": {
"version": "3.3.3",
"resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz",
"integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==",
"version": "3.4.2",
"resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz",
"integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==",
"dev": true,
"license": "ISC"
},
@@ -1487,15 +1477,6 @@
"node": ">=0.10.0"
}
},
"node_modules/is-number-like": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/is-number-like/-/is-number-like-1.0.8.tgz",
"integrity": "sha512-6rZi3ezCyFcn5L71ywzz2bS5b2Igl1En3eTlZlvKjpz1n3IZLAYMbKYAIQgFmEu0GENg92ziU/faEOA/aixjbA==",
"license": "ISC",
"dependencies": {
"lodash.isfinite": "^3.3.2"
}
},
"node_modules/isexe": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
@@ -1504,9 +1485,19 @@
"license": "ISC"
},
"node_modules/js-yaml": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
"integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz",
"integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/puzrin"
},
{
"type": "github",
"url": "https://github.com/sponsors/nodeca"
}
],
"license": "MIT",
"dependencies": {
"argparse": "^2.0.1"
@@ -1600,12 +1591,6 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/lodash": {
"version": "4.17.23",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz",
"integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==",
"license": "MIT"
},
"node_modules/lodash.escaperegexp": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/lodash.escaperegexp/-/lodash.escaperegexp-4.1.2.tgz",
@@ -1619,12 +1604,6 @@
"deprecated": "This package is deprecated. Use require('node:util').isDeepStrictEqual instead.",
"license": "MIT"
},
"node_modules/lodash.isfinite": {
"version": "3.3.2",
"resolved": "https://registry.npmjs.org/lodash.isfinite/-/lodash.isfinite-3.3.2.tgz",
"integrity": "sha512-7FGG40uhC8Mm633uKW1r58aElFlBlxCrg9JfSi3P6aYiWmfiWF0PgMd86ZUsxE5GwWPdHoS2+48bwTh2VPkIQA==",
"license": "MIT"
},
"node_modules/lodash.merge": {
"version": "4.6.2",
"resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz",
@@ -1865,20 +1844,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/portscanner": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/portscanner/-/portscanner-2.2.0.tgz",
"integrity": "sha512-IFroCz/59Lqa2uBvzK3bKDbDDIEaAY8XJ1jFxcLWTqosrsc32//P4VuSB2vZXoHiHqOmx8B5L5hnKOxL/7FlPw==",
"license": "MIT",
"dependencies": {
"async": "^2.6.0",
"is-number-like": "^1.0.3"
},
"engines": {
"node": ">=0.4",
"npm": ">=1.0.0"
}
},
"node_modules/prelude-ls": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
@@ -1992,9 +1957,9 @@
}
},
"node_modules/sax": {
"version": "1.4.4",
"resolved": "https://registry.npmjs.org/sax/-/sax-1.4.4.tgz",
"integrity": "sha512-1n3r/tGXO6b6VXMdFT54SHzT9ytu9yr7TaELowdYpMqY/Ao7EnlQGmAQ1+RatX7Tkkdm6hONI2owqNx2aZj5Sw==",
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz",
"integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==",
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=11.0.0"
@@ -2077,19 +2042,19 @@
}
},
"node_modules/socket.io-adapter": {
"version": "2.5.6",
"resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.6.tgz",
"integrity": "sha512-DkkO/dz7MGln0dHn5bmN3pPy+JmywNICWrJqVWiVOyvXjWQFIv9c2h24JrQLLFJ2aQVQf/Cvl1vblnd4r2apLQ==",
"version": "2.5.8",
"resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.8.tgz",
"integrity": "sha512-6Oy52pbg+kvdCVvjcN+FnY7BvxZ7cIHNScbvztT/It5d0vbwoJoVZmF2gjJmnV0/4WlXRfG15zc45ySk9Ah8bw==",
"license": "MIT",
"dependencies": {
"debug": "~4.4.1",
"ws": "~8.18.3"
"ws": "~8.21.0"
}
},
"node_modules/socket.io-parser": {
"version": "4.2.5",
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.5.tgz",
"integrity": "sha512-bPMmpy/5WWKHea5Y/jYAP6k74A+hvmRCQaJuJB6I/ML5JZq/KfNieUVo/3Mh7SAqn7TyFdIo6wqYHInG1MU1bQ==",
"version": "4.2.7",
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.7.tgz",
"integrity": "sha512-IH/iSeO9T6gz1KkFleGDWkG9N3dl4jXVYUtMhIqH10Md0ttMer8nUNWiP1DKuNrybD2xBrixLJdCC9J6ECoYkg==",
"license": "MIT",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
@@ -2262,9 +2227,9 @@
"license": "ISC"
},
"node_modules/ws": {
"version": "8.18.3",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.3.tgz",
"integrity": "sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==",
"version": "8.21.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
"integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"

View File

@@ -19,13 +19,12 @@
"dasherize": "^2.0.0",
"electron-host-hook": "file:./ElectronHostHook",
"image-size": "^1.2.1",
"portscanner": "^2.2.0",
"electron-updater": "^6.6.2",
"electron-updater": "^6.8.9",
"socket.io": "^4.8.1"
},
"devDependencies": {
"@types/node": "^22.18",
"electron": "^30.0.3",
"electron": "^39.8.10",
"eslint": "^9.39.1",
"typescript": "^5.9.3"
}

View File

@@ -3,6 +3,7 @@
<PropertyGroup>
<!-- When this is enabled, the project will be switched from nuget packages to consuming the ElectronNet orchestration directly -->
<ElectronNetDevMode>true</ElectronNetDevMode>
<IsTest>True</IsTest>
</PropertyGroup>
<Import Project="..\ElectronNET\build\ElectronNET.Core.props" Condition="$(ElectronNetDevMode)" />

View File

@@ -0,0 +1,108 @@
using System.Diagnostics;
namespace ElectronNET.IntegrationTests.Tests;
/// <summary>
/// Tests for the Electron clean targets.
/// Covers GitHub issue #1096: cleaning must not require a restore, so the clean targets
/// must not depend on targets that need the assets file (NETSDK1004).
/// </summary>
public class ElectronCleanTargetsTests
{
private static readonly string CorePropsPath = FindBuildFile("src/ElectronNET/build/ElectronNET.Core.props", "ElectronNET/build/ElectronNET.Core.props");
private static readonly string CoreTargetsPath = FindBuildFile("src/ElectronNET/build/ElectronNET.Core.targets", "ElectronNET/build/ElectronNET.Core.targets");
[Fact]
public async Task ElectronCleanTargets_WithoutRestore_ShouldSucceed()
{
var tempDir = CreateTempProjectDirectory();
try
{
await WriteMinimalCsprojAsync(tempDir);
var (exitCode, output) = await RunDotnetMsBuildAsync(tempDir, "Clean");
output.Should().NotContain("NETSDK1004",
$"cleaning must not require the assets file of a previous restore. Full output:\n{output}");
exitCode.Should().Be(0,
$"cleaning an unrestored project must succeed. Full output:\n{output}");
}
finally
{
Directory.Delete(tempDir, recursive: true);
}
}
private static string FindBuildFile(string relativeFromRepoRoot, string relativeFromSrc)
{
var dir = new DirectoryInfo(AppContext.BaseDirectory);
while (dir != null)
{
var fromRepoRoot = Path.Combine(dir.FullName, relativeFromRepoRoot);
if (File.Exists(fromRepoRoot))
{
return Path.GetFullPath(fromRepoRoot);
}
var fromSrc = Path.Combine(dir.FullName, relativeFromSrc);
if (File.Exists(fromSrc))
{
return Path.GetFullPath(fromSrc);
}
dir = dir.Parent;
}
throw new FileNotFoundException(
$"Could not locate '{relativeFromRepoRoot}' by walking up from '{AppContext.BaseDirectory}'.");
}
private static string CreateTempProjectDirectory()
{
var tempDir = Path.Combine(Path.GetTempPath(), $"electron-net-clean-test-{Guid.NewGuid():N}");
Directory.CreateDirectory(tempDir);
Directory.CreateDirectory(Path.Combine(tempDir, "Properties"));
return tempDir;
}
private static Task WriteMinimalCsprojAsync(string tempDir)
{
var propsPathEscaped = CorePropsPath.Replace("'", "&apos;");
var targetsPathEscaped = CoreTargetsPath.Replace("'", "&apos;");
return File.WriteAllTextAsync(
Path.Combine(tempDir, "TestApp.csproj"),
$$"""
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
</PropertyGroup>
<Import Project="{{propsPathEscaped}}" />
<Import Project="{{targetsPathEscaped}}" />
</Project>
""");
}
private static async Task<(int ExitCode, string Output)> RunDotnetMsBuildAsync(string workingDirectory, string target)
{
// Deliberately without /restore - that is what issue #1096 is about.
var psi = new ProcessStartInfo("dotnet", $"msbuild TestApp.csproj --nologo -v:minimal /t:{target}")
{
WorkingDirectory = workingDirectory,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
using var process = Process.Start(psi)!;
var stdOut = await process.StandardOutput.ReadToEndAsync();
var stdErr = await process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync();
return (process.ExitCode, stdOut + stdErr);
}
}

View File

@@ -0,0 +1,133 @@
using System.Diagnostics;
namespace ElectronNET.IntegrationTests.Tests;
/// <summary>
/// Tests for ElectronNET.Core.targets icon copy behavior.
/// Covers GitHub issue #1047: modern macOS .icon app-icon packages are folders
/// and must be copied recursively, not treated as a single file.
/// </summary>
public class ElectronIconTargetsTests
{
private static readonly string CorePropsPath = FindBuildFile("src/ElectronNET/build/ElectronNET.Core.props", "ElectronNET/build/ElectronNET.Core.props");
private static readonly string CoreTargetsPath = FindBuildFile("src/ElectronNET/build/ElectronNET.Core.targets", "ElectronNET/build/ElectronNET.Core.targets");
[Fact]
public async Task ElectronCoreTargets_ElectronIconDirectory_ShouldBeMappedIntoElectronOutput()
{
var tempDir = CreateTempProjectDirectory();
try
{
var iconPackageDir = Path.Combine(tempDir, "Assets", "MyApp.icon");
Directory.CreateDirectory(Path.Combine(iconPackageDir, "layers"));
await File.WriteAllTextAsync(Path.Combine(iconPackageDir, "manifest.json"), "{}");
await File.WriteAllTextAsync(Path.Combine(iconPackageDir, "layers", "foreground.png"), "not-a-real-png");
await WriteMinimalCsprojAsync(tempDir);
var (exitCode, output) = await RunDotnetMsBuildAsync(tempDir, "DumpElectronIconCopyItems");
var normalizedOutput = NormalizePathSeparators(output);
exitCode.Should().Be(0,
$"MSBuild target evaluation must succeed. Full output:\n{output}");
normalizedOutput.Should().Contain(
".electron/MyApp.icon/manifest.json",
$"the icon package root file must be mapped into .electron/MyApp.icon. Full output:\n{output}");
normalizedOutput.Should().Contain(
".electron/MyApp.icon/layers/foreground.png",
$"nested files in .icon package must preserve structure in .electron output. Full output:\n{output}");
}
finally
{
Directory.Delete(tempDir, recursive: true);
}
}
private static string FindBuildFile(string relativeFromRepoRoot, string relativeFromSrc)
{
var dir = new DirectoryInfo(AppContext.BaseDirectory);
while (dir != null)
{
var fromRepoRoot = Path.Combine(dir.FullName, relativeFromRepoRoot);
if (File.Exists(fromRepoRoot))
{
return Path.GetFullPath(fromRepoRoot);
}
var fromSrc = Path.Combine(dir.FullName, relativeFromSrc);
if (File.Exists(fromSrc))
{
return Path.GetFullPath(fromSrc);
}
dir = dir.Parent;
}
throw new FileNotFoundException(
$"Could not locate '{relativeFromRepoRoot}' by walking up from '{AppContext.BaseDirectory}'.");
}
private static string CreateTempProjectDirectory()
{
var tempDir = Path.Combine(Path.GetTempPath(), $"electron-net-icon-test-{Guid.NewGuid():N}");
Directory.CreateDirectory(tempDir);
Directory.CreateDirectory(Path.Combine(tempDir, "Properties"));
return tempDir;
}
private static Task WriteMinimalCsprojAsync(string tempDir)
{
var propsPathEscaped = CorePropsPath.Replace("'", "&apos;");
var targetsPathEscaped = CoreTargetsPath.Replace("'", "&apos;");
return File.WriteAllTextAsync(
Path.Combine(tempDir, "TestApp.csproj"),
$$"""
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
</PropertyGroup>
<Import Project="{{propsPathEscaped}}" />
<PropertyGroup Label="ElectronNetCommon">
<ElectronIcon>Assets/MyApp.icon</ElectronIcon>
</PropertyGroup>
<Import Project="{{targetsPathEscaped}}" />
<Target Name="DumpElectronIconCopyItems"
DependsOnTargets="ElectronResolvePaths;ElectronGetCopyToOutputDirectoryItems">
<Message Importance="High"
Text="ELECTRON_COPY_ITEMS: @(_ElectronFilesToCopyWithTargetPath->'%(TargetPath)')" />
</Target>
</Project>
""");
}
private static async Task<(int ExitCode, string Output)> RunDotnetMsBuildAsync(string workingDirectory, string target)
{
var psi = new ProcessStartInfo("dotnet", $"msbuild TestApp.csproj --nologo -v:minimal /restore /t:{target}")
{
WorkingDirectory = workingDirectory,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
using var process = Process.Start(psi)!;
var stdOut = await process.StandardOutput.ReadToEndAsync();
var stdErr = await process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync();
return (process.ExitCode, stdOut + stdErr);
}
private static string NormalizePathSeparators(string value)
{
return value.Replace('\\', '/');
}
}

View File

@@ -0,0 +1,298 @@
using System.Diagnostics;
namespace ElectronNET.IntegrationTests.Tests;
/// <summary>
/// Unit tests for ElectronNET.MigrationChecks.targets - no Electron runtime required.
/// Covers GitHub issue #1035: System.IO.File.ReadAllLines is not available as an MSBuild
/// property function on all platforms (e.g. macOS GitHub Actions), causing MSB4185.
/// </summary>
public class MigrationChecksTargetsTests
{
private static readonly string TargetsFilePath = FindTargetsFile();
/// <summary>
/// Walks up the directory tree from <see cref="AppContext.BaseDirectory"/> until it finds
/// the migration checks targets file. This is robust against varying output paths
/// (with or without RID subfolder, debug/release, etc.).
/// </summary>
private static string FindTargetsFile()
{
const string RelativeFromRepoRoot =
"src/ElectronNET/build/ElectronNET.MigrationChecks.targets";
const string RelativeFromSrc =
"ElectronNET/build/ElectronNET.MigrationChecks.targets";
var dir = new DirectoryInfo(AppContext.BaseDirectory);
while (dir != null)
{
var fromRepoRoot = Path.Combine(dir.FullName, RelativeFromRepoRoot);
if (File.Exists(fromRepoRoot))
{
return Path.GetFullPath(fromRepoRoot);
}
var fromSrc = Path.Combine(dir.FullName, RelativeFromSrc);
if (File.Exists(fromSrc))
{
return Path.GetFullPath(fromSrc);
}
dir = dir.Parent;
}
throw new FileNotFoundException(
"Could not locate ElectronNET.MigrationChecks.targets by walking up from " +
$"'{AppContext.BaseDirectory}'.");
}
// -----------------------------------------------------------------------
// Content-level test (RED before fix, GREEN after fix on ALL platforms)
// -----------------------------------------------------------------------
[Fact]
public void MigrationChecksTargets_ShouldNotUseReadAllLines()
{
// The file must exist - if this fails the path constant above is wrong.
File.Exists(TargetsFilePath).Should().BeTrue(
$"targets file must exist at '{TargetsFilePath}'");
var content = File.ReadAllText(TargetsFilePath);
// System.IO.File::ReadAllLines is not in the MSBuild property-function
// whitelist on all platforms (MSB4185 on macOS GitHub Actions, see #1035).
// ReadAllText must be used instead.
content.Should().NotContain(
"::ReadAllLines(",
"because ReadAllLines is not available as an MSBuild property function on all " +
"platforms. Use ReadAllText instead (GitHub issue #1035).");
}
// -----------------------------------------------------------------------
// Functional build test - verifies no MSB4185 at runtime
// (RED on platforms where ReadAllLines is restricted, GREEN after fix)
// -----------------------------------------------------------------------
[Fact]
public async Task MigrationChecksTargets_BuildWithCleanPackageJson_ShouldSucceedWithoutMSB4185()
{
// Positive case: a package.json that does NOT mention electron.
// The migration check must successfully read the file via ReadAllText
// (the code path fixed by issue #1035) without producing MSB4185.
var tempDir = CreateTempProjectDirectory();
try
{
await File.WriteAllTextAsync(
Path.Combine(tempDir, "package.json"),
"""{ "devDependencies": { "vite": "^5.0.0" } }""");
await WriteMinimalCsprojAsync(tempDir);
var (exitCode, output) = await RunDotnetBuildAsync(tempDir);
exitCode.Should().Be(0,
$"the build must succeed when the package.json contains no electron references. " +
$"Full build output:\n{output}");
output.Should().NotContain(
"MSB4185",
$"ReadAllLines must not be used as an MSBuild property function. " +
$"Full build output:\n{output}");
}
finally
{
Directory.Delete(tempDir, recursive: true);
}
}
[Fact]
public async Task MigrationChecksTargets_BuildWithPackageJsonContainingElectron_ShouldEmitELECTRON008WarningWithoutMSB4185()
{
// Negative case: a package.json that DOES contain "electron".
// The migration check must still read the file successfully (no MSB4185)
// and must emit the expected ELECTRON008 warning. ELECTRON008 is a
// <Warning>, not an <Error>, so the build itself still succeeds.
var tempDir = CreateTempProjectDirectory();
try
{
await File.WriteAllTextAsync(
Path.Combine(tempDir, "package.json"),
"""{ "devDependencies": { "electron": "^30.0.0" } }""");
await WriteMinimalCsprojAsync(tempDir);
var (exitCode, output) = await RunDotnetBuildAsync(tempDir);
exitCode.Should().Be(0,
$"ELECTRON008 is a Warning (not an Error) so the build itself must still " +
$"succeed. Full build output:\n{output}");
output.Should().NotContain(
"MSB4185",
$"ReadAllLines must not be used as an MSBuild property function. " +
$"Full build output:\n{output}");
output.Should().Contain(
"ELECTRON008",
$"the migration check must still detect electron references in package.json " +
$"after the ReadAllText migration. Full build output:\n{output}");
}
finally
{
Directory.Delete(tempDir, recursive: true);
}
}
[Fact]
public async Task MigrationChecksTargets_BuildWithRootPackageLockJson_ShouldNotEmitELECTRON001Warning()
{
// A root package.json is validated by ELECTRON008/ELECTRON009 and therefore allowed.
// Its accompanying package-lock.json must not be reported by ELECTRON001.
var tempDir = CreateTempProjectDirectory();
try
{
await File.WriteAllTextAsync(
Path.Combine(tempDir, "package.json"),
"""{ "devDependencies": { "vite": "^5.0.0" } }""");
await File.WriteAllTextAsync(
Path.Combine(tempDir, "package-lock.json"),
"""{ "lockfileVersion": 3 }""");
await WriteMinimalCsprojAsync(tempDir);
var (exitCode, output) = await RunDotnetBuildAsync(tempDir);
exitCode.Should().Be(0, $"Full build output:\n{output}");
output.Should().NotContain(
"ELECTRON001",
$"a root package-lock.json belongs to the allowed root package.json. " +
$"Full build output:\n{output}");
}
finally
{
Directory.Delete(tempDir, recursive: true);
}
}
[Fact]
public async Task MigrationChecksTargets_BuildWithIncompleteHostHookFolder_ShouldEmitELECTRON010AndELECTRON011Warnings()
{
// Host hook TypeScript sources are silently ignored when package.json/tsconfig.json
// are missing, so the migration checks must point that out.
var tempDir = CreateTempProjectDirectory();
try
{
var hookDir = Path.Combine(tempDir, "ElectronHostHook");
Directory.CreateDirectory(hookDir);
await File.WriteAllTextAsync(Path.Combine(hookDir, "index.ts"), "export class HookService {}");
await WriteMinimalCsprojAsync(tempDir);
var (exitCode, output) = await RunDotnetBuildAsync(tempDir);
exitCode.Should().Be(0, $"Full build output:\n{output}");
output.Should().Contain(
"ELECTRON010",
$"the ElectronHostHook folder has TypeScript files but no package.json. " +
$"Full build output:\n{output}");
output.Should().Contain(
"ELECTRON011",
$"the ElectronHostHook folder has TypeScript files but no tsconfig.json. " +
$"Full build output:\n{output}");
}
finally
{
Directory.Delete(tempDir, recursive: true);
}
}
[Fact]
public async Task MigrationChecksTargets_BuildWithConsoleProfileContainingProjectGuid_ShouldEmitELECTRON007Warning()
{
// ProjectGuid is an ASP.NET publish profile property and must be reported for
// non-web projects, just like WebPublishMethod.
var tempDir = CreateTempProjectDirectory();
try
{
var profilesDir = Path.Combine(tempDir, "Properties", "PublishProfiles");
Directory.CreateDirectory(profilesDir);
await File.WriteAllTextAsync(
Path.Combine(profilesDir, "FolderProfile.pubxml"),
"""
<Project>
<PropertyGroup>
<ProjectGuid>00000000-0000-0000-0000-000000000000</ProjectGuid>
</PropertyGroup>
</Project>
""");
await WriteMinimalCsprojAsync(tempDir);
var (exitCode, output) = await RunDotnetBuildAsync(tempDir);
exitCode.Should().Be(0, $"Full build output:\n{output}");
output.Should().Contain(
"ELECTRON007",
$"a console project must not use an ASP.NET publish profile. " +
$"Full build output:\n{output}");
}
finally
{
Directory.Delete(tempDir, recursive: true);
}
}
// -----------------------------------------------------------------------
// Helpers
// -----------------------------------------------------------------------
private static string CreateTempProjectDirectory()
{
var tempDir = Path.Combine(Path.GetTempPath(), $"electron-net-test-{Guid.NewGuid():N}");
Directory.CreateDirectory(tempDir);
return tempDir;
}
private static Task WriteMinimalCsprojAsync(string tempDir)
{
// A minimal csproj that only imports the migration checks targets to keep the
// build fast. Note: MSBuildProjectDirectory is a reserved MSBuild property and
// must not be redefined manually; MSBuild sets it automatically to the folder
// of the csproj (which is tempDir here).
var targetsPathEscaped = TargetsFilePath.Replace("'", "&apos;");
return File.WriteAllTextAsync(
Path.Combine(tempDir, "TestApp.csproj"),
$"""
<Project>
<Import Project="{targetsPathEscaped}" />
<Target Name="Build" DependsOnTargets="ElectronMigrationChecks" />
</Project>
""");
}
private static async Task<(int ExitCode, string Output)> RunDotnetBuildAsync(string workingDirectory)
{
var psi = new ProcessStartInfo("dotnet", "build --nologo -v:minimal")
{
WorkingDirectory = workingDirectory,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
};
using var process = Process.Start(psi)!;
var stdOut = await process.StandardOutput.ReadToEndAsync();
var stdErr = await process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync();
return (process.ExitCode, stdOut + stdErr);
}
}

View File

@@ -0,0 +1,115 @@
namespace ElectronNET.IntegrationTests.Tests
{
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using ElectronNET.API.Entities;
/// <summary>
/// Unit tests for UpdateInfo JSON deserialization.
/// Tests the fix for issue #1039: releaseNotes arrives as string or string[] from electron-builder
/// when FullChangelog is false (default), but the C# model expects ReleaseNoteInfo[].
/// No Electron runtime is required for these tests.
/// </summary>
public class UpdateInfoSerializationTests
{
// camelCase + ignore null — mirrors ElectronJson.Options used in production
private static readonly JsonSerializerOptions Options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
};
// electron-builder sends a plain string when FullChangelog = false (default)
[Fact]
public void Deserialize_WithStringReleaseNotes_ShouldConvertToSingleEntry()
{
var json = """{"version":"1.2.3","releaseNotes":"Some release notes"}""";
var result = JsonSerializer.Deserialize<UpdateInfo>(json, Options);
result.Should().NotBeNull();
result.ReleaseNotes.Should().HaveCount(1);
result.ReleaseNotes[0].Note.Should().Be("Some release notes");
}
// After the (incorrect) TypeScript normalize: string → ["string"] which is an array of strings,
// not an array of ReleaseNoteInfo objects. The C# model must handle this too.
[Fact]
public void Deserialize_WithArrayOfStringReleaseNotes_ShouldConvertToEntries()
{
var json = """{"version":"1.2.3","releaseNotes":["Note A","Note B"]}""";
var result = JsonSerializer.Deserialize<UpdateInfo>(json, Options);
result.Should().NotBeNull();
result.ReleaseNotes.Should().HaveCount(2);
result.ReleaseNotes[0].Note.Should().Be("Note A");
result.ReleaseNotes[1].Note.Should().Be("Note B");
}
// When FullChangelog = true, electron-builder sends proper objects; this must keep working.
[Fact]
public void Deserialize_WithProperReleaseNoteObjects_ShouldDeserializeNormally()
{
var json = """{"version":"1.2.3","releaseNotes":[{"version":"1.2.3","note":"Proper note"}]}""";
var result = JsonSerializer.Deserialize<UpdateInfo>(json, Options);
result.Should().NotBeNull();
result.ReleaseNotes.Should().HaveCount(1);
result.ReleaseNotes[0].Version.Should().Be("1.2.3");
result.ReleaseNotes[0].Note.Should().Be("Proper note");
}
// Null releaseNotes should result in an empty array (matching the default value).
[Fact]
public void Deserialize_WithNullReleaseNotes_ShouldReturnEmptyArray()
{
var json = """{"version":"1.2.3","releaseNotes":null}""";
var result = JsonSerializer.Deserialize<UpdateInfo>(json, Options);
result.Should().NotBeNull();
result.ReleaseNotes.Should().NotBeNull();
result.ReleaseNotes.Should().BeEmpty();
}
// Absent releaseNotes field should keep the default empty array.
[Fact]
public void Deserialize_WithMissingReleaseNotes_ShouldReturnEmptyArray()
{
var json = """{"version":"1.2.3"}""";
var result = JsonSerializer.Deserialize<UpdateInfo>(json, Options);
result.Should().NotBeNull();
result.ReleaseNotes.Should().NotBeNull();
result.ReleaseNotes.Should().BeEmpty();
}
// Empty array must serialize as [] not null, so round-trips and downstream
// consumers don't receive unexpected null for a non-null array value.
[Fact]
public void Serialize_WithEmptyReleaseNotes_ShouldProduceEmptyArray()
{
var updateInfo = new UpdateInfo { Version = "1.2.3", ReleaseNotes = Array.Empty<ReleaseNoteInfo>() };
var json = JsonSerializer.Serialize(updateInfo, Options);
json.Should().Contain("\"releaseNotes\":[]");
}
// Null value: with DefaultIgnoreCondition.WhenWritingNull the property is
// omitted entirely at the serializer level (before Write() is called).
[Fact]
public void Serialize_WithNullReleaseNotes_ShouldOmitProperty()
{
var updateInfo = new UpdateInfo { Version = "1.2.3", ReleaseNotes = null };
var json = JsonSerializer.Serialize(updateInfo, Options);
json.Should().NotContain("releaseNotes");
}
}
}

View File

@@ -108,13 +108,19 @@ namespace ElectronNET.IntegrationTests.Tests
await Task.Delay(500.ms());
var ok = await window.WebContents.GetZoomLevelAsync();
ok.Should().Be(0);
ok.Should().Be(0.0);
window.WebContents.SetZoomLevel(2);
await Task.Delay(500.ms());
ok = await window.WebContents.GetZoomLevelAsync();
ok.Should().Be(2);
ok.Should().Be(2.0);
window.WebContents.SetZoomLevel(0.5);
await Task.Delay(500.ms());
ok = await window.WebContents.GetZoomLevelAsync();
ok.Should().BeApproximately(0.5, 0.001);
}
finally
{
@@ -193,5 +199,94 @@ namespace ElectronNET.IntegrationTests.Tests
}
}
[IntegrationFact]
public async Task InsertAndRemoveCSS_check()
{
var wc = this.MainWindow.WebContents;
await wc.LoadURLAsync("data:text/html,<html><body><p>CSS Test</p></body></html>");
var key = await wc.InsertCSSAsync("body { background-color: rgb(255, 0, 0); }");
key.Should().NotBeNullOrEmpty();
var color = await wc.ExecuteJavaScriptAsync<string>("getComputedStyle(document.body).backgroundColor");
color.Should().Be("rgb(255, 0, 0)");
await wc.RemoveInsertedCSSAsync(key);
color = await wc.ExecuteJavaScriptAsync<string>("getComputedStyle(document.body).backgroundColor");
color.Should().NotBe("rgb(255, 0, 0)");
}
[IntegrationFact]
public async Task EditCommands_check()
{
var wc = this.MainWindow.WebContents;
await wc.LoadURLAsync("data:text/html,<html><body><input id='in' autofocus /></body></html>");
await Task.Delay(500.ms());
await wc.InsertTextAsync("Electron.NET");
await Task.Delay(500.ms());
var value = await wc.ExecuteJavaScriptAsync<string>("document.getElementById('in').value");
value.Should().Be("Electron.NET");
wc.SelectAll();
wc.Delete();
await Task.Delay(500.ms());
value = await wc.ExecuteJavaScriptAsync<string>("document.getElementById('in').value");
value.Should().BeEmpty();
}
[IntegrationFact]
public async Task FindInPage_check()
{
var wc = this.MainWindow.WebContents;
await wc.LoadURLAsync("data:text/html,<html><body><p>needle in a haystack</p></body></html>");
await Task.Delay(500.ms());
var tcs = new TaskCompletionSource<FoundInPageResult>();
void OnFound(FoundInPageResult result) => tcs.TrySetResult(result);
wc.OnFoundInPage += OnFound;
try
{
var requestId = await wc.FindInPageAsync("needle");
requestId.Should().BeGreaterThan(0);
var completed = await Task.WhenAny(tcs.Task, Task.Delay(5.seconds()));
completed.Should().Be(tcs.Task);
var result = await tcs.Task;
result.RequestId.Should().Be(requestId);
result.Matches.Should().BeGreaterThan(0);
}
finally
{
wc.OnFoundInPage -= OnFound;
wc.StopFindInPage(StopFindInPageAction.ClearSelection);
}
}
[IntegrationFact]
public async Task Reload_and_loading_state_check()
{
var wc = this.MainWindow.WebContents;
await wc.LoadURLAsync("data:text/html,<html><body><h1>Reload Test</h1></body></html>");
await Task.Delay(500.ms());
(await wc.IsLoadingAsync()).Should().BeFalse();
(await wc.IsLoadingMainFrameAsync()).Should().BeFalse();
(await wc.IsWaitingForResponseAsync()).Should().BeFalse();
wc.Reload();
await Task.Delay(1.seconds());
var title = await wc.ExecuteJavaScriptAsync<string>("document.querySelector('h1').textContent");
title.Should().Be("Reload Test");
}
}
}

View File

@@ -0,0 +1,55 @@
namespace ElectronNET.IntegrationTests.Tests;
/// <summary>
/// Regression checks for BrowserWindow lifecycle cleanup in WindowManager.
/// Covers GitHub issue #1008.
/// </summary>
public class WindowManagerLifecycleTests
{
private static readonly string WindowManagerFilePath = FindWindowManagerFile();
[Fact]
public void WindowManager_ShouldUsePersistentBrowserWindowClosedSubscription()
{
File.Exists(WindowManagerFilePath).Should().BeTrue(
$"WindowManager source must exist at '{WindowManagerFilePath}'.");
var content = File.ReadAllText(WindowManagerFilePath);
content.Should().Contain(
"Socket.On<int[]>(\"BrowserWindowClosed\"",
"closed-window cleanup must be wired for every close event, not just the first one.");
content.Should().NotContain(
"Socket.Once<int[]>(\"BrowserWindowClosed\"",
"a one-shot subscription causes stale BrowserWindow references after subsequent closes (issue #1008).");
}
private static string FindWindowManagerFile()
{
const string RelativeFromRepoRoot = "src/ElectronNET.API/API/WindowManager.cs";
const string RelativeFromSrc = "ElectronNET.API/API/WindowManager.cs";
var dir = new DirectoryInfo(AppContext.BaseDirectory);
while (dir != null)
{
var fromRepoRoot = Path.Combine(dir.FullName, RelativeFromRepoRoot);
if (File.Exists(fromRepoRoot))
{
return Path.GetFullPath(fromRepoRoot);
}
var fromSrc = Path.Combine(dir.FullName, RelativeFromSrc);
if (File.Exists(fromSrc))
{
return Path.GetFullPath(fromSrc);
}
dir = dir.Parent;
}
throw new FileNotFoundException(
"Could not locate WindowManager.cs by walking up from " +
$"'{AppContext.BaseDirectory}'.");
}
}

View File

@@ -21,6 +21,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "!Config", "!Config", "{02EA
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ElectronNET.AspNet", "ElectronNET.AspNet\ElectronNET.AspNet.csproj", "{DD10D21A-D131-1D9C-33F9-406046E0C5B0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ElectronNET.Templates", "ElectronNET.Templates\ElectronNET.Templates.csproj", "{3F2A1D64-9C71-4E1B-9A2D-5C7B0E4F8A11}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{1BB6F634-2831-4496-83A6-BC6761DCEC8D}"
EndProject
Global
@@ -45,6 +47,10 @@ Global
{DD10D21A-D131-1D9C-33F9-406046E0C5B0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DD10D21A-D131-1D9C-33F9-406046E0C5B0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DD10D21A-D131-1D9C-33F9-406046E0C5B0}.Release|Any CPU.Build.0 = Release|Any CPU
{3F2A1D64-9C71-4E1B-9A2D-5C7B0E4F8A11}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3F2A1D64-9C71-4E1B-9A2D-5C7B0E4F8A11}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3F2A1D64-9C71-4E1B-9A2D-5C7B0E4F8A11}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3F2A1D64-9C71-4E1B-9A2D-5C7B0E4F8A11}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -54,6 +60,7 @@ Global
{829FC339-4785-4229-ABA5-53ADB544DA00} = {1BB6F634-2831-4496-83A6-BC6761DCEC8D}
{8860606D-6847-F22A-5AED-DF4E0984DD24} = {1BB6F634-2831-4496-83A6-BC6761DCEC8D}
{DD10D21A-D131-1D9C-33F9-406046E0C5B0} = {1BB6F634-2831-4496-83A6-BC6761DCEC8D}
{3F2A1D64-9C71-4E1B-9A2D-5C7B0E4F8A11} = {1BB6F634-2831-4496-83A6-BC6761DCEC8D}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {81A62E71-9E04-4EFE-AD5C-23165375F8EF}

View File

@@ -0,0 +1,23 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<base href="/" />
<ResourcePreloader />
<link rel="stylesheet" href="@Assets["lib/bootstrap/dist/css/bootstrap.min.css"]" />
<link rel="stylesheet" href="@Assets["app.css"]" />
<link rel="stylesheet" href="@Assets["electronnet-samples-authmiddleware.styles.css"]" />
<ImportMap />
<link rel="icon" type="image/png" href="favicon.png" />
<HeadOutlet />
</head>
<body>
<Routes />
<ReconnectModal />
<script src="@Assets["_framework/blazor.web.js"]"></script>
</body>
</html>

View File

@@ -0,0 +1,23 @@
@inherits LayoutComponentBase
<div class="page">
<div class="sidebar">
<NavMenu />
</div>
<main>
<div class="top-row px-4">
<a href="https://learn.microsoft.com/aspnet/core/" target="_blank">About</a>
</div>
<article class="content px-4">
@Body
</article>
</main>
</div>
<div id="blazor-error-ui" data-nosnippet>
An unhandled error has occurred.
<a href="." class="reload">Reload</a>
<span class="dismiss">🗙</span>
</div>

View File

@@ -0,0 +1,98 @@
.page {
position: relative;
display: flex;
flex-direction: column;
}
main {
flex: 1;
}
.sidebar {
background-image: linear-gradient(180deg, rgb(5, 39, 103) 0%, #3a0647 70%);
}
.top-row {
background-color: #f7f7f7;
border-bottom: 1px solid #d6d5d5;
justify-content: flex-end;
height: 3.5rem;
display: flex;
align-items: center;
}
.top-row ::deep a, .top-row ::deep .btn-link {
white-space: nowrap;
margin-left: 1.5rem;
text-decoration: none;
}
.top-row ::deep a:hover, .top-row ::deep .btn-link:hover {
text-decoration: underline;
}
.top-row ::deep a:first-child {
overflow: hidden;
text-overflow: ellipsis;
}
@media (max-width: 640.98px) {
.top-row {
justify-content: space-between;
}
.top-row ::deep a, .top-row ::deep .btn-link {
margin-left: 0;
}
}
@media (min-width: 641px) {
.page {
flex-direction: row;
}
.sidebar {
width: 250px;
height: 100vh;
position: sticky;
top: 0;
}
.top-row {
position: sticky;
top: 0;
z-index: 1;
}
.top-row.auth ::deep a:first-child {
flex: 1;
text-align: right;
width: 0;
}
.top-row, article {
padding-left: 2rem !important;
padding-right: 1.5rem !important;
}
}
#blazor-error-ui {
color-scheme: light only;
background: lightyellow;
bottom: 0;
box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2);
box-sizing: border-box;
display: none;
left: 0;
padding: 0.6rem 1.25rem 0.7rem 1.25rem;
position: fixed;
width: 100%;
z-index: 1000;
}
#blazor-error-ui .dismiss {
cursor: pointer;
position: absolute;
right: 0.75rem;
top: 0.5rem;
}

View File

@@ -0,0 +1,30 @@
<div class="top-row ps-3 navbar navbar-dark">
<div class="container-fluid">
<a class="navbar-brand" href="">ElectronNET.Samples.AuthMiddleware</a>
</div>
</div>
<input type="checkbox" title="Navigation menu" class="navbar-toggler" />
<div class="nav-scrollable" onclick="document.querySelector('.navbar-toggler').click()">
<nav class="nav flex-column">
<div class="nav-item px-3">
<NavLink class="nav-link" href="" Match="NavLinkMatch.All">
<span class="bi bi-house-door-fill-nav-menu" aria-hidden="true"></span> Home
</NavLink>
</div>
<div class="nav-item px-3">
<NavLink class="nav-link" href="counter">
<span class="bi bi-plus-square-fill-nav-menu" aria-hidden="true"></span> Counter
</NavLink>
</div>
<div class="nav-item px-3">
<NavLink class="nav-link" href="weather">
<span class="bi bi-list-nested-nav-menu" aria-hidden="true"></span> Weather
</NavLink>
</div>
</nav>
</div>

View File

@@ -0,0 +1,105 @@
.navbar-toggler {
appearance: none;
cursor: pointer;
width: 3.5rem;
height: 2.5rem;
color: white;
position: absolute;
top: 0.5rem;
right: 1rem;
border: 1px solid rgba(255, 255, 255, 0.1);
background: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%28255, 255, 255, 0.55%29' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e") no-repeat center/1.75rem rgba(255, 255, 255, 0.1);
}
.navbar-toggler:checked {
background-color: rgba(255, 255, 255, 0.5);
}
.top-row {
min-height: 3.5rem;
background-color: rgba(0,0,0,0.4);
}
.navbar-brand {
font-size: 1.1rem;
}
.bi {
display: inline-block;
position: relative;
width: 1.25rem;
height: 1.25rem;
margin-right: 0.75rem;
top: -1px;
background-size: cover;
}
.bi-house-door-fill-nav-menu {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-house-door-fill' viewBox='0 0 16 16'%3E%3Cpath d='M6.5 14.5v-3.505c0-.245.25-.495.5-.495h2c.25 0 .5.25.5.5v3.5a.5.5 0 0 0 .5.5h4a.5.5 0 0 0 .5-.5v-7a.5.5 0 0 0-.146-.354L13 5.793V2.5a.5.5 0 0 0-.5-.5h-1a.5.5 0 0 0-.5.5v1.293L8.354 1.146a.5.5 0 0 0-.708 0l-6 6A.5.5 0 0 0 1.5 7.5v7a.5.5 0 0 0 .5.5h4a.5.5 0 0 0 .5-.5Z'/%3E%3C/svg%3E");
}
.bi-plus-square-fill-nav-menu {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-plus-square-fill' viewBox='0 0 16 16'%3E%3Cpath d='M2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2zm6.5 4.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3a.5.5 0 0 1 1 0z'/%3E%3C/svg%3E");
}
.bi-list-nested-nav-menu {
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='white' class='bi bi-list-nested' viewBox='0 0 16 16'%3E%3Cpath fill-rule='evenodd' d='M4.5 11.5A.5.5 0 0 1 5 11h10a.5.5 0 0 1 0 1H5a.5.5 0 0 1-.5-.5zm-2-4A.5.5 0 0 1 3 7h10a.5.5 0 0 1 0 1H3a.5.5 0 0 1-.5-.5zm-2-4A.5.5 0 0 1 1 3h10a.5.5 0 0 1 0 1H1a.5.5 0 0 1-.5-.5z'/%3E%3C/svg%3E");
}
.nav-item {
font-size: 0.9rem;
padding-bottom: 0.5rem;
}
.nav-item:first-of-type {
padding-top: 1rem;
}
.nav-item:last-of-type {
padding-bottom: 1rem;
}
.nav-item ::deep .nav-link {
color: #d7d7d7;
background: none;
border: none;
border-radius: 4px;
height: 3rem;
display: flex;
align-items: center;
line-height: 3rem;
width: 100%;
}
.nav-item ::deep a.active {
background-color: rgba(255,255,255,0.37);
color: white;
}
.nav-item ::deep .nav-link:hover {
background-color: rgba(255,255,255,0.1);
color: white;
}
.nav-scrollable {
display: none;
}
.navbar-toggler:checked ~ .nav-scrollable {
display: block;
}
@media (min-width: 641px) {
.navbar-toggler {
display: none;
}
.nav-scrollable {
/* Never collapse the sidebar for wide screens */
display: block;
/* Allow sidebar to scroll for tall menus */
height: calc(100vh - 3.5rem);
overflow-y: auto;
}
}

View File

@@ -0,0 +1,31 @@
<script type="module" src="@Assets["Components/Layout/ReconnectModal.razor.js"]"></script>
<dialog id="components-reconnect-modal" data-nosnippet>
<div class="components-reconnect-container">
<div class="components-rejoining-animation" aria-hidden="true">
<div></div>
<div></div>
</div>
<p class="components-reconnect-first-attempt-visible">
Rejoining the server...
</p>
<p class="components-reconnect-repeated-attempt-visible">
Rejoin failed... trying again in <span id="components-seconds-to-next-attempt"></span> seconds.
</p>
<p class="components-reconnect-failed-visible">
Failed to rejoin.<br />Please retry or reload the page.
</p>
<button id="components-reconnect-button" class="components-reconnect-failed-visible">
Retry
</button>
<p class="components-pause-visible">
The session has been paused by the server.
</p>
<button id="components-resume-button" class="components-pause-visible">
Resume
</button>
<p class="components-resume-failed-visible">
Failed to resume the session.<br />Please reload the page.
</p>
</div>
</dialog>

View File

@@ -0,0 +1,157 @@
.components-reconnect-first-attempt-visible,
.components-reconnect-repeated-attempt-visible,
.components-reconnect-failed-visible,
.components-pause-visible,
.components-resume-failed-visible,
.components-rejoining-animation {
display: none;
}
#components-reconnect-modal.components-reconnect-show .components-reconnect-first-attempt-visible,
#components-reconnect-modal.components-reconnect-show .components-rejoining-animation,
#components-reconnect-modal.components-reconnect-paused .components-pause-visible,
#components-reconnect-modal.components-reconnect-resume-failed .components-resume-failed-visible,
#components-reconnect-modal.components-reconnect-retrying,
#components-reconnect-modal.components-reconnect-retrying .components-reconnect-repeated-attempt-visible,
#components-reconnect-modal.components-reconnect-retrying .components-rejoining-animation,
#components-reconnect-modal.components-reconnect-failed,
#components-reconnect-modal.components-reconnect-failed .components-reconnect-failed-visible {
display: block;
}
#components-reconnect-modal {
background-color: white;
width: 20rem;
margin: 20vh auto;
padding: 2rem;
border: 0;
border-radius: 0.5rem;
box-shadow: 0 3px 6px 2px rgba(0, 0, 0, 0.3);
opacity: 0;
transition: display 0.5s allow-discrete, overlay 0.5s allow-discrete;
animation: components-reconnect-modal-fadeOutOpacity 0.5s both;
&[open]
{
animation: components-reconnect-modal-slideUp 1.5s cubic-bezier(.05, .89, .25, 1.02) 0.3s, components-reconnect-modal-fadeInOpacity 0.5s ease-in-out 0.3s;
animation-fill-mode: both;
}
}
#components-reconnect-modal::backdrop {
background-color: rgba(0, 0, 0, 0.4);
animation: components-reconnect-modal-fadeInOpacity 0.5s ease-in-out;
opacity: 1;
}
@keyframes components-reconnect-modal-slideUp {
0% {
transform: translateY(30px) scale(0.95);
}
100% {
transform: translateY(0);
}
}
@keyframes components-reconnect-modal-fadeInOpacity {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@keyframes components-reconnect-modal-fadeOutOpacity {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
.components-reconnect-container {
display: flex;
flex-direction: column;
align-items: center;
gap: 1rem;
}
#components-reconnect-modal p {
margin: 0;
text-align: center;
}
#components-reconnect-modal button {
border: 0;
background-color: #6b9ed2;
color: white;
padding: 4px 24px;
border-radius: 4px;
}
#components-reconnect-modal button:hover {
background-color: #3b6ea2;
}
#components-reconnect-modal button:active {
background-color: #6b9ed2;
}
.components-rejoining-animation {
position: relative;
width: 80px;
height: 80px;
}
.components-rejoining-animation div {
position: absolute;
border: 3px solid #0087ff;
opacity: 1;
border-radius: 50%;
animation: components-rejoining-animation 1.5s cubic-bezier(0, 0.2, 0.8, 1) infinite;
}
.components-rejoining-animation div:nth-child(2) {
animation-delay: -0.5s;
}
@keyframes components-rejoining-animation {
0% {
top: 40px;
left: 40px;
width: 0;
height: 0;
opacity: 0;
}
4.9% {
top: 40px;
left: 40px;
width: 0;
height: 0;
opacity: 0;
}
5% {
top: 40px;
left: 40px;
width: 0;
height: 0;
opacity: 1;
}
100% {
top: 0px;
left: 0px;
width: 80px;
height: 80px;
opacity: 0;
}
}

View File

@@ -0,0 +1,63 @@
// Set up event handlers
const reconnectModal = document.getElementById("components-reconnect-modal");
reconnectModal.addEventListener("components-reconnect-state-changed", handleReconnectStateChanged);
const retryButton = document.getElementById("components-reconnect-button");
retryButton.addEventListener("click", retry);
const resumeButton = document.getElementById("components-resume-button");
resumeButton.addEventListener("click", resume);
function handleReconnectStateChanged(event) {
if (event.detail.state === "show") {
reconnectModal.showModal();
} else if (event.detail.state === "hide") {
reconnectModal.close();
} else if (event.detail.state === "failed") {
document.addEventListener("visibilitychange", retryWhenDocumentBecomesVisible);
} else if (event.detail.state === "rejected") {
location.reload();
}
}
async function retry() {
document.removeEventListener("visibilitychange", retryWhenDocumentBecomesVisible);
try {
// Reconnect will asynchronously return:
// - true to mean success
// - false to mean we reached the server, but it rejected the connection (e.g., unknown circuit ID)
// - exception to mean we didn't reach the server (this can be sync or async)
const successful = await Blazor.reconnect();
if (!successful) {
// We have been able to reach the server, but the circuit is no longer available.
// We'll reload the page so the user can continue using the app as quickly as possible.
const resumeSuccessful = await Blazor.resumeCircuit();
if (!resumeSuccessful) {
location.reload();
} else {
reconnectModal.close();
}
}
} catch (err) {
// We got an exception, server is currently unavailable
document.addEventListener("visibilitychange", retryWhenDocumentBecomesVisible);
}
}
async function resume() {
try {
const successful = await Blazor.resumeCircuit();
if (!successful) {
location.reload();
}
} catch {
location.reload();
}
}
async function retryWhenDocumentBecomesVisible() {
if (document.visibilityState === "visible") {
await retry();
}
}

View File

@@ -0,0 +1,19 @@
@page "/counter"
@rendermode InteractiveServer
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}

View File

@@ -0,0 +1,36 @@
@page "/Error"
@using System.Diagnostics
<PageTitle>Error</PageTitle>
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
@if (ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@RequestId</code>
</p>
}
<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>
@code{
[CascadingParameter]
private HttpContext? HttpContext { get; set; }
private string? RequestId { get; set; }
private bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
protected override void OnInitialized() =>
RequestId = Activity.Current?.Id ?? HttpContext?.TraceIdentifier;
}

View File

@@ -0,0 +1,7 @@
@page "/"
<PageTitle>Home</PageTitle>
<h1>Hello, world!</h1>
Welcome to your new app.

View File

@@ -0,0 +1,5 @@
@page "/not-found"
@layout MainLayout
<h3>Not Found</h3>
<p>Sorry, the content you are looking for does not exist.</p>

View File

@@ -0,0 +1,64 @@
@page "/weather"
@attribute [StreamRendering]
<PageTitle>Weather</PageTitle>
<h1>Weather</h1>
<p>This component demonstrates showing data.</p>
@if (forecasts == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Date</th>
<th aria-label="Temperature in Celsius">Temp. (C)</th>
<th aria-label="Temperature in Fahrenheit">Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
}
@code {
private WeatherForecast[]? forecasts;
protected override async Task OnInitializedAsync()
{
// Simulate asynchronous loading to demonstrate streaming rendering
await Task.Delay(500);
var startDate = DateOnly.FromDateTime(DateTime.Now);
var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" };
forecasts = Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = startDate.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = summaries[Random.Shared.Next(summaries.Length)]
}).ToArray();
}
private class WeatherForecast
{
public DateOnly Date { get; set; }
public int TemperatureC { get; set; }
public string? Summary { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
}

View File

@@ -0,0 +1,6 @@
<Router AppAssembly="typeof(Program).Assembly" NotFoundPage="typeof(Pages.NotFound)">
<Found Context="routeData">
<RouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" />
<FocusOnNavigate RouteData="routeData" Selector="h1" />
</Found>
</Router>

View File

@@ -0,0 +1,11 @@
@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using static Microsoft.AspNetCore.Components.Web.RenderMode
@using Microsoft.AspNetCore.Components.Web.Virtualization
@using Microsoft.JSInterop
@using ElectronNET.Samples.AuthMiddleware
@using ElectronNET.Samples.AuthMiddleware.Components
@using ElectronNET.Samples.AuthMiddleware.Components.Layout

View File

@@ -0,0 +1,38 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<BlazorDisableThrowNavigationException>true</BlazorDisableThrowNavigationException>
<!-- Enable Electron.NET Dev Mode to use local packages -->
<ElectronNetDevMode>true</ElectronNetDevMode>
</PropertyGroup>
<Import Project="..\ElectronNET\build\ElectronNET.Core.props" Condition="$(ElectronNetDevMode)" />
<PropertyGroup Label="ElectronNetCommon">
<Title>Electron.NET Auth Middleware Sample</Title>
<Version>1.0.0</Version>
<Product>com.electronnet.auth-middleware-sample</Product>
<Description>Sample Blazor Server application using Electron.NET with Auth Middleware</Description>
<Company>Electron.NET</Company>
<Copyright>Copyright © 2026, Electron.NET</Copyright>
<ElectronVersion>30.4.0</ElectronVersion>
<License>MIT</License>
<ElectronSingleInstance>true</ElectronSingleInstance>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\ElectronNET.API\ElectronNET.API.csproj" Condition="$(ElectronNetDevMode)" />
<ProjectReference Include="..\ElectronNET.AspNet\ElectronNET.AspNet.csproj" Condition="$(ElectronNetDevMode)" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="ElectronNET.Core" Version="0.4.0" Condition="'$(ElectronNetDevMode)' != 'true'" />
<PackageReference Include="ElectronNET.Core.AspNet" Version="0.4.0" Condition="'$(ElectronNetDevMode)' != 'true'" />
</ItemGroup>
<Import Project="..\ElectronNET\build\ElectronNET.Core.targets" Condition="$(ElectronNetDevMode)" />
</Project>

View File

@@ -0,0 +1,24 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.2.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ElectronNET.Samples.AuthMiddleware", "ElectronNET.Samples.AuthMiddleware.csproj", "{1A87C5B5-16EE-5DA0-33B4-17DA71675A87}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1A87C5B5-16EE-5DA0-33B4-17DA71675A87}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1A87C5B5-16EE-5DA0-33B4-17DA71675A87}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1A87C5B5-16EE-5DA0-33B4-17DA71675A87}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1A87C5B5-16EE-5DA0-33B4-17DA71675A87}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {5892D89B-BD0D-43B9-9064-0CBAC9A0FF60}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,92 @@
using ElectronNET.API;
using ElectronNET.API.Entities;
using ElectronNET.AspNet.Middleware;
using ElectronNET.AspNet.Services;
var watch = new System.Diagnostics.Stopwatch();
watch.Start();
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
// Add CORS for SignalR
builder.Services.AddCors(options =>
{
options.AddPolicy("ElectronPolicy", policy =>
{
policy.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
// Register Electron authentication service as singleton
builder.Services.AddSingleton<IElectronAuthenticationService, ElectronAuthenticationService>();
builder.Services.AddElectron();
// Configure Electron.NET with SignalR mode
// Note: Callback is registered now but executes after app starts
IServiceProvider? serviceProvider = null;
builder.WebHost.UseElectron(args, async () =>
{
if (serviceProvider is null)
{
throw new InvalidOperationException("ServiceProvider not initialized. This callback should only execute after app.Build().");
}
var options = new BrowserWindowOptions
{
Show = false,
Width = 1200,
Height = 800,
IsRunningBlazor = true,
};
// Log startup time using ILogger - serviceProvider is captured after app.Build()
var logger = serviceProvider.GetRequiredService<ILoggerFactory>().CreateLogger("Electron.Startup");
logger.LogInformation("App startup time until Electron launch: {ElapsedMilliseconds} ms", watch.ElapsedMilliseconds);
if (OperatingSystem.IsWindows() || OperatingSystem.IsLinux())
options.AutoHideMenuBar = true;
var browserWindow = await Electron.WindowManager.CreateWindowAsync(options);
browserWindow.OnReadyToShow += () => browserWindow.Show();
});
var app = builder.Build();
serviceProvider = app.Services; // Capture for use in Electron callback above
// Register authentication middleware FIRST (before routing, static files, etc.)
app.UseMiddleware<ElectronAuthenticationMiddleware>();
// Enable routing
app.UseRouting();
// Enable CORS
app.UseCors("ElectronPolicy");
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
}
// Serve static files (CSS, JS, images, etc.)
app.UseStaticFiles();
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
// UseAntiforgery must be after UseRouting
app.UseAntiforgery();
app.MapStaticAssets();
app.MapRazorComponents<ElectronNET.Samples.AuthMiddleware.Components.App>()
.AddInteractiveServerRenderMode();
app.Run();

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<Project>
<PropertyGroup>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<DeleteExistingFiles>true</DeleteExistingFiles>
<PublishProvider>FileSystem</PublishProvider>
<PublishUrl>publish\$(Configuration)\$(TargetFramework)\$(RuntimeIdentifier)\</PublishUrl>
<WebPublishMethod>FileSystem</WebPublishMethod>
<_TargetId>Folder</_TargetId>
<TargetFramework>net10.0</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<ProjectGuid>48eff821-2f4d-60cc-aa44-be0f1d6e5f35</ProjectGuid>
<SelfContained>true</SelfContained>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,19 @@
{
"$schema": "https://raw.githubusercontent.com/electron-userland/electron-builder/refs/heads/master/packages/app-builder-lib/scheme.json",
"compression": "maximum",
"linux": {
"target": [
"tar.xz"
],
"executableArgs": [ "--no-sandbox" ],
"artifactName": "${name}-${arch}-${version}.${ext}"
},
"win": {
"target": [
{
"target": "portable",
"arch": "x64"
}
]
}
}

Some files were not shown because too many files have changed in this diff Show More