2026-11-12 09:32:23 +01:00
using System.Diagnostics ;
using System.IO.Compression ;
using System.Reflection ;
using System.Security.Cryptography ;
using System.Text.Json ;
using Microsoft.Web.WebView2.Core ;
using Microsoft.Web.WebView2.WinForms ;
namespace ProjectDashboard ;
static class Program
{
2026-11-12 21:18:02 +01:00
// --background: start only the server and the tray icon (Windows autostart)
2026-11-12 09:32:23 +01:00
[STAThread]
2026-11-12 21:18:02 +01:00
static void Main ( string [ ] args )
2026-11-12 09:32:23 +01:00
{
2026-11-12 21:18:02 +01:00
// one dashboard per port: a second start brings the running one to the front
var name = $"ProjectDashboard-{MainForm.Port}" ;
using var mutex = new Mutex ( true , name , out var first ) ;
if ( ! first )
{
try { EventWaitHandle . OpenExisting ( name + "-show" ) . Set ( ) ; } catch { }
return ;
}
using var show = new EventWaitHandle ( false , EventResetMode . AutoReset , name + "-show" ) ;
2026-11-12 09:32:23 +01:00
ApplicationConfiguration . Initialize ( ) ;
2026-11-12 21:18:02 +01:00
Application . Run ( new MainForm ( args . Contains ( "--background" ) , show ) ) ;
GC . KeepAlive ( mutex ) ;
2026-11-12 09:32:23 +01:00
}
}
// One window: makes sure the Node server runs, then shows
// http://127.0.0.1:4848 in WebView2. A server that is already running
// (second window, start-dashboard.bat) is reused and left alone.
//
// Two modes:
// source - server.js lies next to the exe (Michi's _Tools\ProjectDashboard):
// system Node, data in the app's .cache folder.
// portable - the exe carries everything as embedded payload.zip (node.exe +
// dashboard files) and unpacks it once to %LOCALAPPDATA%\ProjectDashboard\app\<hash>.
sealed class MainForm : Form
{
// DASHBOARD_PORT (also read by server.js) allows a second instance, e.g. for tests
2026-11-12 21:18:02 +01:00
internal static readonly int Port = int . TryParse ( Environment . GetEnvironmentVariable ( "DASHBOARD_PORT" ) , out var p ) ? p : 4848 ;
2026-11-12 09:32:23 +01:00
static readonly string BaseUrl = $"http://127.0.0.1:{Port}/" ;
// DASHBOARD_HOME moves everything (window state, WebView2, unpacked app, data) - used for tests
static readonly string DataDir = Environment . GetEnvironmentVariable ( "DASHBOARD_HOME" ) is { Length : > 0 } home
? Path . GetFullPath ( home )
: Path . Combine ( Environment . GetFolderPath ( Environment . SpecialFolder . LocalApplicationData ) , "ProjectDashboard" ) ;
const string WebView2Download = "https://go.microsoft.com/fwlink/p/?LinkId=2124703" ;
string appDir = AppContext . BaseDirectory ;
bool portable ;
readonly WebView2 web = new ( ) { Dock = DockStyle . Fill , Visible = false } ;
readonly Label status = new ( )
{
Dock = DockStyle . Fill ,
TextAlign = ContentAlignment . MiddleCenter ,
Font = new Font ( "Segoe UI" , 12f ) ,
ForeColor = Color . FromArgb ( 107 , 113 , 131 ) ,
} ;
Process ? server ; // only set when this window started the server
StreamWriter ? serverLog ;
2026-11-12 21:18:02 +01:00
// tray: closing the window keeps the dashboard (and the automatic backup) running
readonly NotifyIcon tray = new ( ) { Text = "Projekt-Dashboard" } ;
readonly System . Windows . Forms . Timer poll = new ( ) { Interval = 20000 } ;
AppPrefs prefs = AppPrefs . Load ( ) ;
bool startHidden ; // --background: the first Show() is skipped
bool exiting ; // "Beenden" in the tray menu: really close
string? lastAutoAt ; // last automatic backup result seen (notifications)
string? lastPhase ;
bool polledOnce ;
public MainForm ( bool background = false , EventWaitHandle ? showSignal = null )
2026-11-12 09:32:23 +01:00
{
Text = "Projekte" ;
Icon = Icon . ExtractAssociatedIcon ( Application . ExecutablePath ) ;
MinimumSize = new Size ( 900 , 560 ) ;
RestoreWindow ( ) ;
2026-11-12 21:18:02 +01:00
startHidden = background ;
SetupTray ( ) ;
if ( showSignal ! = null )
{
new Thread ( ( ) = > { while ( showSignal . WaitOne ( ) ) { try { BeginInvoke ( ( ) = > ShowFromTray ( ) ) ; } catch { } } } ) { IsBackground = true } . Start ( ) ;
}
2026-11-12 09:32:23 +01:00
FormClosing + = ( _ , e ) = >
{
2026-11-12 21:18:02 +01:00
if ( ! exiting & & prefs . Tray & & e . CloseReason = = CloseReason . UserClosing )
{
e . Cancel = true ;
SaveWindow ( ) ;
Hide ( ) ;
if ( ! prefs . HintShown )
{
tray . ShowBalloonTip ( 5000 , "Projekt-Dashboard läuft weiter" ,
"Im Hintergrund – das automatische Backup läuft weiter. Rechtsklick auf das Symbol → Beenden." , ToolTipIcon . Info ) ;
prefs . HintShown = true ;
prefs . Save ( ) ;
}
return ;
}
2026-11-12 09:32:23 +01:00
if ( server ! = null & & BackupRunning ( ) & &
MessageBox . Show ( this , "Das Backup läuft noch.\n\nBeim Schließen wird es abgebrochen (bereits kopierte Dateien bleiben). Trotzdem schließen?" ,
"Projekte" , MessageBoxButtons . YesNo , MessageBoxIcon . Warning ) ! = DialogResult . Yes )
{
e . Cancel = true ;
2026-11-12 21:18:02 +01:00
exiting = false ;
2026-11-12 09:32:23 +01:00
return ;
}
2026-11-12 21:18:02 +01:00
if ( Visible ) SaveWindow ( ) ;
2026-11-12 09:32:23 +01:00
} ;
BackColor = Color . FromArgb ( 245 , 246 , 250 ) ;
status . Text = "Starte Dashboard …" ;
Controls . Add ( web ) ;
Controls . Add ( status ) ;
Shown + = async ( _ , _ ) = > await StartAsync ( ) ;
2026-11-12 21:18:02 +01:00
FormClosed + = ( _ , _ ) = > { poll . Stop ( ) ; tray . Visible = false ; tray . Dispose ( ) ; StopServer ( ) ; } ;
2026-11-12 09:32:23 +01:00
}
2026-11-12 21:18:02 +01:00
// --background: the window is not shown at start; the server starts anyway
protected override void SetVisibleCore ( bool value )
{
if ( startHidden )
{
startHidden = false ;
value = false ;
if ( ! IsHandleCreated ) CreateHandle ( ) ;
BeginInvoke ( async ( ) = >
{
try { await EnsureServerAsync ( ) ; }
catch ( Exception ex ) { tray . ShowBalloonTip ( 8000 , "Projekt-Dashboard" , "Konnte nicht starten: " + ex . Message , ToolTipIcon . Error ) ; }
} ) ;
}
base . SetVisibleCore ( value ) ;
}
void SetupTray ( )
{
tray . Icon = Icon ;
var menu = new ContextMenuStrip ( ) ;
menu . Items . Add ( "Öffnen" , null , ( _ , _ ) = > ShowFromTray ( ) ) ;
menu . Items . Add ( "Backup …" , null , ( _ , _ ) = > ShowFromTray ( "backup" ) ) ;
menu . Items . Add ( new ToolStripSeparator ( ) ) ;
menu . Items . Add ( "Beenden" , null , ( _ , _ ) = > { exiting = true ; Close ( ) ; } ) ;
tray . ContextMenuStrip = menu ;
tray . DoubleClick + = ( _ , _ ) = > ShowFromTray ( ) ;
tray . BalloonTipClicked + = ( _ , _ ) = > ShowFromTray ( ) ;
tray . Visible = true ;
poll . Tick + = async ( _ , _ ) = > await PollBackup ( ) ;
poll . Start ( ) ;
}
// Brings the window back (from the tray, or for a second start of the exe).
void ShowFromTray ( string? hash = null )
{
if ( ! Visible ) Show ( ) ; // the first Show() also starts the web view (Shown event)
if ( WindowState = = FormWindowState . Minimized ) WindowState = FormWindowState . Normal ;
Activate ( ) ;
BringToFront ( ) ;
if ( hash = = "backup" )
{
if ( web . CoreWebView2 ! = null ) _ = web . CoreWebView2 . ExecuteScriptAsync ( "typeof openBackup === 'function' && openBackup()" ) ;
else pendingHash = "#backup" ;
}
}
string pendingHash = "" ;
// While the window is hidden: a balloon when a backup finished or failed.
async Task PollBackup ( )
2026-11-12 09:32:23 +01:00
{
try
{
2026-11-12 21:18:02 +01:00
using var http = new HttpClient { Timeout = TimeSpan . FromSeconds ( 3 ) } ;
using var doc = JsonDocument . Parse ( await http . GetStringAsync ( BaseUrl + "api/backup" ) ) ;
var r = doc . RootElement ;
var phase = r . TryGetProperty ( "phase" , out var ph ) ? ph . GetString ( ) : null ;
var auto = r . TryGetProperty ( "auto" , out var au ) & & au . ValueKind = = JsonValueKind . True ;
string? at = null ; bool ok = true ; string detail = "" ;
if ( r . TryGetProperty ( "schedule" , out var sc ) & & sc . TryGetProperty ( "lastResult" , out var lr ) & & lr . ValueKind = = JsonValueKind . Object )
{
at = lr . TryGetProperty ( "at" , out var a ) ? a . GetString ( ) : null ;
ok = lr . TryGetProperty ( "ok" , out var o ) & & o . ValueKind = = JsonValueKind . True ;
if ( lr . TryGetProperty ( "targets" , out var ts ) & & ts . ValueKind = = JsonValueKind . Array )
detail = string . Join ( ", " , ts . EnumerateArray ( ) . Select ( t = >
( t . TryGetProperty ( "name" , out var n ) ? n . GetString ( ) : "" ) +
( t . TryGetProperty ( "error" , out var er ) & & er . ValueKind = = JsonValueKind . String ? ": " + er . GetString ( ) : "" ) ) ) ;
}
if ( polledOnce & & ! Visible )
{
if ( at ! = null & & at ! = lastAutoAt )
tray . ShowBalloonTip ( 6000 , ok ? "Automatisches Backup fertig" : "Automatisches Backup fehlgeschlagen" ,
detail . Length > 0 ? detail : ( ok ? "Alle Projekte gesichert." : "Details im Dashboard." ) , ok ? ToolTipIcon . Info : ToolTipIcon . Warning ) ;
else if ( ! auto & & lastPhase is "checking" or "copying" & & phase is "done" or "error" )
tray . ShowBalloonTip ( 6000 , phase = = "done" ? "Backup fertig" : "Backup fehlgeschlagen" ,
phase = = "done" ? "Alles gesichert." : ( r . TryGetProperty ( "error" , out var e ) ? e . GetString ( ) ? ? "" : "" ) , phase = = "done" ? ToolTipIcon . Info : ToolTipIcon . Warning ) ;
}
lastAutoAt = at ;
lastPhase = phase ;
polledOnce = true ;
}
catch { }
}
// Starts the Node server unless one is already running (also used by --background).
async Task EnsureServerAsync ( )
{
Directory . CreateDirectory ( DataDir ) ;
if ( ! await IsServerUp ( ) )
2026-11-12 09:32:23 +01:00
{
string node ;
if ( File . Exists ( Path . Combine ( appDir , "server.js" ) ) )
{
node = FindNode ( ) ? ? throw new Exception ( "Node.js nicht gefunden. Bitte von nodejs.org installieren." ) ;
if ( ! Directory . Exists ( Path . Combine ( appDir , "node_modules" ) ) )
{
status . Text = "Installiere einmalig die Abhängigkeiten (npm install) …" ;
await RunHidden ( "cmd.exe" , "/c npm install --no-audit --no-fund" , Path . GetDirectoryName ( node ) ! ) ;
}
}
else
{
status . Text = "Richte das Dashboard ein …" ;
appDir = await Task . Run ( UnpackPayload ) ;
portable = true ;
node = Path . Combine ( appDir , "node" , "node.exe" ) ;
}
StartServer ( node ) ;
status . Text = "Starte Server …" ;
var until = DateTime . Now . AddSeconds ( 25 ) ;
while ( ! await IsServerUp ( ) )
{
if ( server is { HasExited : true } ) throw new Exception ( $"Server ist abgestürzt. Details:\n{Path.Combine(DataDir, " server . log ")}" ) ;
if ( DateTime . Now > until ) throw new Exception ( $"Server antwortet nicht (Port {Port} belegt?)." ) ;
await Task . Delay ( 300 ) ;
}
}
2026-11-12 21:18:02 +01:00
}
2026-11-12 09:32:23 +01:00
2026-11-12 21:18:02 +01:00
async Task StartAsync ( )
{
try
{
await EnsureServerAsync ( ) ;
2026-11-12 09:32:23 +01:00
var env = await CoreWebView2Environment . CreateAsync ( null , Path . Combine ( DataDir , "WebView2" ) ) ;
await web . EnsureCoreWebView2Async ( env ) ;
var core = web . CoreWebView2 ;
core . Settings . IsStatusBarEnabled = false ;
core . Settings . AreDevToolsEnabled = true ;
// Anything outside the dashboard opens in the normal browser.
core . NewWindowRequested + = ( _ , e ) = > { e . Handled = true ; OpenExternal ( e . Uri ) ; } ;
core . NavigationStarting + = ( _ , e ) = >
{
if ( ! e . Uri . StartsWith ( BaseUrl , StringComparison . OrdinalIgnoreCase ) ) { e . Cancel = true ; OpenExternal ( e . Uri ) ; }
} ;
core . DocumentTitleChanged + = ( _ , _ ) = > Text = core . DocumentTitle ;
core . WebMessageReceived + = OnWebMessage ;
if ( savedZoom is > 0.3 and < 3 ) web . ZoomFactor = savedZoom ;
2026-11-12 21:18:02 +01:00
web . Source = new Uri ( BaseUrl + pendingHash ) ;
pendingHash = "" ;
2026-11-12 09:32:23 +01:00
web . Visible = true ;
status . Visible = false ;
}
catch ( WebView2RuntimeNotFoundException )
{
ShowError ( "Für das Fenster fehlt die „Microsoft Edge WebView2 Runtime“.\n\nHier klicken, um sie herunterzuladen und zu installieren,\ndanach das Dashboard neu starten." ) ;
status . Cursor = Cursors . Hand ;
status . Click + = ( _ , _ ) = > OpenExternal ( WebView2Download ) ;
}
catch ( Exception ex )
{
ShowError ( "Dashboard konnte nicht starten:\n\n" + ex . Message ) ;
}
}
void ShowError ( string text )
{
status . Text = text ;
status . ForeColor = Color . FromArgb ( 220 , 38 , 38 ) ;
status . Visible = true ;
web . Visible = false ;
}
// The page asks for a folder dialog ("Durchsuchen…" in the settings):
// { type: "pickFolder", id, title, initial } → { type: "folderPicked", id, path }
// or for a file dialog (program to start in "Aktionen"):
// { type: "pickFile", id, title, initial } → { type: "filePicked", id, path }
void OnWebMessage ( object? sender , CoreWebView2WebMessageReceivedEventArgs e )
{
if ( ! e . Source . StartsWith ( BaseUrl , StringComparison . OrdinalIgnoreCase ) ) return ;
try
{
using var doc = JsonDocument . Parse ( e . WebMessageAsJson ) ;
var m = doc . RootElement ;
if ( m . ValueKind ! = JsonValueKind . Object ) return ;
var type = m . GetProperty ( "type" ) . GetString ( ) ;
2026-11-12 21:18:02 +01:00
// window options from Einstellungen → Allgemein → Fenster
if ( type = = "getAppSettings" | | type = = "appSettings" )
{
if ( type = = "appSettings" )
{
if ( m . TryGetProperty ( "tray" , out var tr ) & & tr . ValueKind is JsonValueKind . True or JsonValueKind . False ) prefs . Tray = tr . GetBoolean ( ) ;
if ( m . TryGetProperty ( "autostart" , out var au ) & & au . ValueKind is JsonValueKind . True or JsonValueKind . False ) AppPrefs . SetAutostart ( au . GetBoolean ( ) ) ;
prefs . Save ( ) ;
}
web . CoreWebView2 ? . PostWebMessageAsJson ( JsonSerializer . Serialize ( new { type = "appSettings" , tray = prefs . Tray , autostart = AppPrefs . Autostart ( ) } ) ) ;
return ;
}
2026-11-12 09:32:23 +01:00
if ( type ! = "pickFolder" & & type ! = "pickFile" ) return ;
var id = m . GetProperty ( "id" ) . GetString ( ) ? ? "" ;
var title = m . TryGetProperty ( "title" , out var t ) ? t . GetString ( ) : null ;
var initial = m . TryGetProperty ( "initial" , out var i ) ? i . GetString ( ) : null ;
if ( type = = "pickFile" )
{
BeginInvoke ( ( ) = >
{
using var fd = new OpenFileDialog
{
Title = title ? ? "Datei wählen" ,
Filter = "Programme und Seiten (*.exe;*.html;*.htm;*.bat;*.cmd;*.lnk)|*.exe;*.html;*.htm;*.bat;*.cmd;*.lnk|Alle Dateien (*.*)|*.*" ,
CheckFileExists = true ,
DereferenceLinks = false ,
} ;
if ( ! string . IsNullOrWhiteSpace ( initial ) & & Directory . Exists ( initial ) ) fd . InitialDirectory = initial ;
var file = fd . ShowDialog ( this ) = = DialogResult . OK ? fd . FileName : "" ;
web . CoreWebView2 ? . PostWebMessageAsJson ( JsonSerializer . Serialize ( new { type = "filePicked" , id , path = file } ) ) ;
} ) ;
return ;
}
BeginInvoke ( ( ) = >
{
using var dlg = new FolderBrowserDialog
{
Description = title ? ? "Ordner wählen" ,
UseDescriptionForTitle = true ,
ShowNewFolderButton = true ,
} ;
if ( ! string . IsNullOrWhiteSpace ( initial ) & & Directory . Exists ( initial ) ) dlg . InitialDirectory = initial ;
var path = dlg . ShowDialog ( this ) = = DialogResult . OK ? dlg . SelectedPath : "" ;
web . CoreWebView2 ? . PostWebMessageAsJson ( JsonSerializer . Serialize ( new { type = "folderPicked" , id , path } ) ) ;
} ) ;
}
catch { }
}
// Unpacks the embedded payload.zip once per version to <DataDir>\app\<hash>
// and removes older versions. Returns the app folder.
string UnpackPayload ( )
{
var asm = Assembly . GetExecutingAssembly ( ) ;
using var res = asm . GetManifestResourceStream ( "payload.zip" )
? ? throw new Exception ( "Diese exe enthält kein Dashboard-Paket (server.js fehlt daneben)." ) ;
string hash ;
using ( var sha = SHA256 . Create ( ) ) hash = Convert . ToHexString ( sha . ComputeHash ( res ) ) [ . . 12 ] . ToLowerInvariant ( ) ;
var appsRoot = Path . Combine ( DataDir , "app" ) ;
var target = Path . Combine ( appsRoot , hash ) ;
if ( File . Exists ( Path . Combine ( target , ".ok" ) ) ) return target ;
Directory . CreateDirectory ( appsRoot ) ;
var tmp = target + ".tmp" ;
if ( Directory . Exists ( tmp ) ) Directory . Delete ( tmp , true ) ;
res . Position = 0 ;
using ( var zip = new ZipArchive ( res , ZipArchiveMode . Read ) ) zip . ExtractToDirectory ( tmp ) ;
File . WriteAllText ( Path . Combine ( tmp , ".ok" ) , DateTime . Now . ToString ( "s" ) ) ;
if ( Directory . Exists ( target ) ) Directory . Delete ( target , true ) ;
Directory . Move ( tmp , target ) ;
foreach ( var old in Directory . GetDirectories ( appsRoot ) )
{
if ( ! string . Equals ( old , target , StringComparison . OrdinalIgnoreCase ) )
try { Directory . Delete ( old , true ) ; } catch { } // may be in use by another window
}
return target ;
}
// Window size/position/zoom are remembered in %LOCALAPPDATA%\ProjectDashboard\window.txt
// ("x y w h maximized zoom"). First start: maximized.
static readonly string WindowFile = Path . Combine ( DataDir , "window.txt" ) ;
double savedZoom = 1.0 ;
void RestoreWindow ( )
{
StartPosition = FormStartPosition . CenterScreen ;
Size = new Size ( 1500 , 950 ) ;
WindowState = FormWindowState . Maximized ;
try
{
var v = File . ReadAllText ( WindowFile ) . Split ( ' ' ) ;
var inv = System . Globalization . CultureInfo . InvariantCulture ;
var rect = new Rectangle ( int . Parse ( v [ 0 ] ) , int . Parse ( v [ 1 ] ) , int . Parse ( v [ 2 ] ) , int . Parse ( v [ 3 ] ) ) ;
savedZoom = double . Parse ( v [ 5 ] , inv ) ;
// only restore a position that is still on a connected screen
if ( Screen . AllScreens . Any ( s = > s . WorkingArea . IntersectsWith ( rect ) ) & & rect . Width > = MinimumSize . Width )
{
StartPosition = FormStartPosition . Manual ;
Bounds = rect ;
}
WindowState = v [ 4 ] = = "1" ? FormWindowState . Maximized : FormWindowState . Normal ;
}
catch { }
}
void SaveWindow ( )
{
try
{
var b = WindowState = = FormWindowState . Normal ? Bounds : RestoreBounds ;
var zoom = web . CoreWebView2 ! = null ? web . ZoomFactor : savedZoom ;
Directory . CreateDirectory ( DataDir ) ;
File . WriteAllText ( WindowFile , string . Join ( ' ' , b . X , b . Y , b . Width , b . Height ,
WindowState = = FormWindowState . Maximized ? "1" : "0" ,
zoom . ToString ( System . Globalization . CultureInfo . InvariantCulture ) ) ) ;
}
catch { }
}
static bool BackupRunning ( )
{
try
{
using var http = new HttpClient { Timeout = TimeSpan . FromSeconds ( 1 ) } ;
var json = http . GetStringAsync ( BaseUrl + "api/backup" ) . GetAwaiter ( ) . GetResult ( ) ;
return json . Contains ( "\"phase\":\"copying\"" ) | | json . Contains ( "\"phase\":\"checking\"" ) ;
}
catch { return false ; }
}
static async Task < bool > IsServerUp ( )
{
try
{
using var http = new HttpClient { Timeout = TimeSpan . FromSeconds ( 1.5 ) } ;
var res = await http . GetAsync ( BaseUrl + "api/scan" ) ;
return res . IsSuccessStatusCode ;
}
catch { return false ; }
}
string? FindNode ( )
{
foreach ( var dir in ( Environment . GetEnvironmentVariable ( "PATH" ) ? ? "" ) . Split ( ';' , StringSplitOptions . RemoveEmptyEntries ) )
{
try
{
var p = Path . Combine ( dir . Trim ( '"' ) , "node.exe" ) ;
if ( File . Exists ( p ) ) return p ;
}
catch { }
}
var std = Path . Combine ( Environment . GetFolderPath ( Environment . SpecialFolder . ProgramFiles ) , "nodejs" , "node.exe" ) ;
return File . Exists ( std ) ? std : null ;
}
void StartServer ( string node )
{
serverLog = new StreamWriter ( Path . Combine ( DataDir , "server.log" ) , append : false ) { AutoFlush = true } ;
var psi = new ProcessStartInfo ( node , "server.js" )
{
WorkingDirectory = appDir ,
UseShellExecute = false ,
CreateNoWindow = true ,
RedirectStandardOutput = true ,
RedirectStandardError = true ,
} ;
// npm/git/code started by the server must be found
psi . Environment [ "PATH" ] = Path . GetDirectoryName ( node ) + ";" + Environment . GetEnvironmentVariable ( "PATH" ) ;
// portable: settings, cache and logs live next to the window state, not in the unpacked app
if ( portable ) psi . Environment [ "DASHBOARD_DATA" ] = Path . Combine ( DataDir , "data" ) ;
server = Process . Start ( psi ) ? ? throw new Exception ( "Node konnte nicht gestartet werden." ) ;
server . OutputDataReceived + = ( _ , e ) = > { if ( e . Data ! = null ) lock ( serverLog ) serverLog . WriteLine ( e . Data ) ; } ;
server . ErrorDataReceived + = ( _ , e ) = > { if ( e . Data ! = null ) lock ( serverLog ) serverLog . WriteLine ( "ERR " + e . Data ) ; } ;
server . BeginOutputReadLine ( ) ;
server . BeginErrorReadLine ( ) ;
}
async Task RunHidden ( string exe , string args , string extraPath )
{
var psi = new ProcessStartInfo ( exe , args ) { WorkingDirectory = appDir , UseShellExecute = false , CreateNoWindow = true } ;
psi . Environment [ "PATH" ] = extraPath + ";" + Environment . GetEnvironmentVariable ( "PATH" ) ;
using var p = Process . Start ( psi ) ! ;
await p . WaitForExitAsync ( ) ;
if ( p . ExitCode ! = 0 ) throw new Exception ( "npm install ist fehlgeschlagen." ) ;
}
// Only node itself is stopped: programs it launched (Unity, consoles, ...)
// were started detached and keep running.
void StopServer ( )
{
if ( server is { HasExited : false } )
{
// a running backup (robocopy, child of node) is stopped cleanly first
try
{
using var http = new HttpClient { Timeout = TimeSpan . FromSeconds ( 2 ) } ;
using var req = new HttpRequestMessage ( HttpMethod . Post , BaseUrl + "api/backup/cancel" ) ;
req . Headers . Add ( "Origin" , BaseUrl . TrimEnd ( '/' ) ) ;
http . Send ( req ) ;
}
catch { }
}
try { if ( server is { HasExited : false } ) server . Kill ( entireProcessTree : false ) ; } catch { }
serverLog ? . Dispose ( ) ;
}
static void OpenExternal ( string uri )
{
try { Process . Start ( new ProcessStartInfo ( uri ) { UseShellExecute = true } ) ; } catch { }
}
2026-11-12 21:18:02 +01:00
internal static string Home = > DataDir ;
}
// Window options (only the desktop app can do these): <DataDir>\app.json.
// Autostart lives in the registry (HKCU ...\Run); a test home (DASHBOARD_HOME)
// uses its own value name so it never touches the real one.
sealed class AppPrefs
{
public bool Tray { get ; set ; } = true ;
public bool HintShown { get ; set ; }
static string File_ = > Path . Combine ( MainForm . Home , "app.json" ) ;
const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run" ;
static string RunValue = > Environment . GetEnvironmentVariable ( "DASHBOARD_HOME" ) is { Length : > 0 } ? "ProjectDashboard-Test" : "ProjectDashboard" ;
public static AppPrefs Load ( )
{
try { return JsonSerializer . Deserialize < AppPrefs > ( File . ReadAllText ( File_ ) ) ? ? new AppPrefs ( ) ; } catch { return new AppPrefs ( ) ; }
}
public void Save ( )
{
try { Directory . CreateDirectory ( MainForm . Home ) ; File . WriteAllText ( File_ , JsonSerializer . Serialize ( this ) ) ; } catch { }
}
public static bool Autostart ( )
{
try { using var k = Microsoft . Win32 . Registry . CurrentUser . OpenSubKey ( RunKey ) ; return k ? . GetValue ( RunValue ) is string ; } catch { return false ; }
}
public static void SetAutostart ( bool on )
{
try
{
using var k = Microsoft . Win32 . Registry . CurrentUser . CreateSubKey ( RunKey ) ;
if ( on ) k . SetValue ( RunValue , $"\" { Application . ExecutablePath } \ " --background" ) ;
else k . DeleteValue ( RunValue , false ) ;
}
catch { }
}
2026-11-12 09:32:23 +01:00
}