Compare commits

...

11 Commits

Author SHA1 Message Date
duffyduck 88635c04f8 Release v0.0.0.30 2026-06-08 13:53:34 +02:00
duffyduck 6b025a24f0 Add autostart management (per-user / all-users) in settings
Setup setzt den Autostart weiterhin fuer alle Benutzer (HKLM); die
Task-Beschreibung im Installer stellt das jetzt klar.

In den Einstellungen neuer Abschnitt "Autostart":
- "Nur fuer diesen Benutzer" -> HKCU\...\Run
- "Fuer alle Benutzer" -> HKLM\...\Run, nur mit Admin-Rechten aenderbar
  (so laesst sich der vom Setup gesetzte All-User-Autostart auch entfernen).

Neuer AutostartManager kapselt Lesen/Setzen/Entfernen beider Run-Eintraege
und die Admin-Pruefung. Single-Instance-Mutex verhindert weiterhin einen
Doppelstart, falls beide Eintraege gesetzt sind.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 13:52:34 +02:00
duffyduck 641267081a Add log auto-clear setting (retention in days, 0 = off)
Neue Einstellung "Protokoll auto-leeren - Eintraege aelter als (Tage)".
0 = aus (alle Eintraege bleiben), >0 entfernt aeltere Eintraege.

- UserSettings.LogRetentionDays (Standard 0).
- Logger.PruneOlderThan(days): parst den Zeitstempel-Prefix je Zeile und
  entfernt zu alte; Zeilen ohne Zeitstempel bleiben erhalten.
- Ausgefuehrt beim Start, vor jedem Sync (Coordinator), beim Oeffnen des
  Protokolls und beim Speichern der Einstellungen.
- SettingsForm: NumericUpDown (0-3650).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 13:47:10 +02:00
duffyduck 0336530742 Unify manual and automatic sync via SyncCoordinator
Der manuelle "Synchronisieren"-Button (SyncProgressForm) lief ueber eine eigene
Engine und umging die clientuebergreifende Lock-Datei, den lokalen Guard und
einen Teil des Protokolls. Jetzt teilen sich beide Pfade einen SyncCoordinator.

- Neuer SyncCoordinator kapselt: prozessweiten Re-Entrancy-Guard (statisch, so
  koennen manueller + automatischer Sync nicht mehr gleichzeitig laufen),
  Lock-Datei (mit Warte-Status), Konflikt-Notizen anderer Arbeitsplaetze,
  Protokoll (Start/Ergebnis/Aenderungen/Konflikte/Fehler) und das Verteilen
  eigener Konflikt-Notizen. runEngine wird vom Aufrufer uebergeben, damit das
  Threading pro Pfad erhalten bleibt (UI-Thread vs. Task.Run).
- MainForm.RunSync und SyncProgressForm.RunSync nutzen den Coordinator; UI
  (Tray-Meldung vs. Fenster) bleibt jeweils beim Aufrufer.
- Lock/Notiz/Guard-Logik aus MainForm entfernt (jetzt zentral).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 13:43:03 +02:00
duffyduck 75c0c1126e Log what changed; add notification on/off settings
Protokoll:
- SyncResult.Changes erfasst jede tatsaechliche Aenderung (erstellt/aktualisiert/
  geloescht/verknuepft/zusammengefuehrt je Kontakt) per Action()-Helfer.
- Beide Sync-Pfade (Auto/Tray via RunSync UND manueller Sync via
  SyncProgressForm) schreiben Start, Ergebnis, Aenderungen, Konflikte und Fehler
  ins persistente Protokoll.

Benachrichtigungen:
- UserSettings: NotificationsEnabled (allgemein) + NotifyWarningsErrors
  (Konflikte/Fehler), beide in der Einstellungen-Maske als Haken.
- MainForm.Balloon() zeigt Tray-Meldungen nur, wenn der passende Haken aktiv
  ist; Zusammenfassung gilt als Warnung, wenn Fehler/Konflikte auftraten.
- Protokoll wird unabhaengig von den Benachrichtigungs-Einstellungen geschrieben.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 13:35:55 +02:00
duffyduck 96c34e542f Release v0.0.0.29 2026-06-08 13:18:35 +02:00
duffyduck 23223fe0be Add persistent log file and "Protokoll" viewer button
Tray-Meldungen verschwinden - daher ein dauerhaftes Protokoll.

- Logger: threadsicheres Datei-Log in %AppData%\StarfaceOutlookSync\sync.log
  mit Rotation bei 2 MB.
- MainForm protokolliert Sync-Start, Ergebnis, Konflikte (lokal + von anderen
  Arbeitsplaetzen), Fehler und uebersprungene Laeufe (Sperre).
- Neuer Button "Protokoll" oeffnet LogViewerForm (Aktualisieren/Leeren/Ordner
  oeffnen, scrollt ans Ende).
- README/CHANGELOG aktualisiert.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 13:17:53 +02:00
duffyduck b8a7fda7bf Release v0.0.0.28 2026-06-08 13:02:51 +02:00
duffyduck 257b6fb33d Only notify clients actually affected by a conflict
Bisher bekam jeder Arbeitsplatz, der den Konflikt-Kontakt im Adressbuch hat,
den Hinweis - auch wenn er den Wert gar nicht selbst gepflegt hat.

Jetzt zeigt ein Client eine fremde Konflikt-Notiz nur, wenn er den Kontakt hat
UND sein eigener Feldwert vom uebernommenen (Gewinner-)Wert abweicht. Die
Pruefung laeuft VOR dem Sync (gegen den eigenen Mapping-Snapshot), bevor der
Sync den Stand auf den Gewinner-Wert angleicht.

- FieldConflict/ConflictNotice: stabiler FieldKey zusaetzlich zum Anzeige-Label.
- ContactMerger: GetValue/ValuesEqual per FieldKey (telefon-normalisiert).
- ConflictNotifier.GetPending: Filter "eigener Wert != Gewinner-Wert", bekommt
  StarfaceId -> eigener Kontaktstand.
- MainForm zeigt die Hinweise jetzt vor dem Sync und liefert den eigenen Stand
  aus den Mapping-Snapshots.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 13:01:02 +02:00
duffyduck cf2970a41a Add cross-client conflict notifications (step 3)
Wird ein echter Feld-Konflikt aufgeloest, erfahren jetzt auch die ANDEREN
Arbeitsplaetze davon - nicht nur der aufloesende Client.

- ConflictNotice-Modell + ConflictNotifier: schreibt pro Konflikt eine Notiz
  in <shared>/conflicts/ (nach StarfaceId), liest beim Sync ungesehene Notizen
  zu eigenen Kontakten, zeigt sie als Tray-Hinweis und merkt sich gezeigte
  lokal (seen-conflicts.json). Veraltete Notizen (>7 Tage) werden aufgeraeumt.
- MainForm: schreibt nach einem Sync mit Konflikten die Notizen und zeigt
  ausstehende Notizen anderer Clients (gefiltert auf eigene gemappte
  StarfaceIds). AcquireCrossClientLock nimmt jetzt das gemeinsame Verzeichnis
  als Parameter.
- README/CHANGELOG aktualisiert.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 12:54:01 +02:00
duffyduck 5a0203e49e Document multi-client sync lock in README
Beschreibt Lock-Datei starface-sync.lock: atomares Anlegen (CreateNew),
nur waehrend des Syncs vorhanden, Inhalt (Host/User/Zeit/PID), Warte- und
Absturz-Verhalten, sowie den Hinweis auf bidirektionalen Modus im Mehrplatz.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 12:47:28 +02:00
18 changed files with 1015 additions and 139 deletions
+41
View File
@@ -38,6 +38,40 @@ Versionsschema ist `x.x.x.x` (siehe `release.sh`).
### Hinzugefuegt ### Hinzugefuegt
- **Autostart-Verwaltung in den Einstellungen.** Neuer Abschnitt "Autostart" mit
zwei Optionen: "Nur fuer diesen Benutzer" (HKCU) und "Fuer alle Benutzer"
(HKLM). Die Option fuer alle Benutzer ist nur mit Admin-Rechten aenderbar -
darueber laesst sich auch der vom Setup gesetzte Autostart fuer alle wieder
entfernen. Das Setup setzt den Autostart weiterhin fuer alle Benutzer (HKLM),
der Hinweis im Installer wurde entsprechend klargestellt.
- **Protokoll automatisch leeren (Einstellung).** Neuer Wert "Protokoll
auto-leeren - Eintraege aelter als (Tage)". Bei 0 (Standard) bleibt alles
erhalten; bei >0 werden aeltere Eintraege automatisch entfernt (beim Start,
vor jedem Sync, beim Oeffnen des Protokolls und beim Speichern der
Einstellungen).
- **Protokoll zeigt jetzt, WAS geaendert wurde.** Pro Sync werden die einzelnen
Aktionen (erstellt / aktualisiert / geloescht / verknuepft / zusammengefuehrt je
Kontakt) ins Protokoll geschrieben - sowohl beim manuellen Sync (Fenster) als
auch bei Auto-/Tray-Sync.
- **Benachrichtigungen schaltbar (Einstellungen).** Zwei unabhaengige Haken:
"Tray-Benachrichtigungen (allgemein)" fuer Info-Meldungen (Sync laeuft/fertig)
und "Benachrichtigungen bei Warnungen/Fehlern" fuer Konflikte und Fehler. So
kann man z.B. nur noch bei Konflikten/Fehlern benachrichtigt werden - oder gar
nicht. Das Protokoll wird unabhaengig davon immer geschrieben.
- **Protokoll (Logdatei) + "Protokoll"-Button.** Syncs, Ergebnisse, Konflikte
(lokal und von anderen Arbeitsplaetzen) und Fehler werden dauerhaft in
`%AppData%\StarfaceOutlookSync\sync.log` festgehalten - so ist auch nach dem
Verschwinden einer Tray-Meldung nachvollziehbar, wer/was/wann. Im Hauptfenster
oeffnet der Button "Protokoll" einen Betrachter (Aktualisieren/Leeren/Ordner
oeffnen). Die Datei rotiert bei 2 MB.
- **Clientuebergreifende Konflikt-Hinweise (Mehrplatz).** Wird ein echter
Feld-Konflikt aufgeloest, legt der Client eine Notiz im gemeinsamen Verzeichnis
(`conflicts/`) ab - zugeordnet nach Kontakt (StarfaceId). Ein anderer
Arbeitsplatz zeigt die Meldung beim naechsten Sync nur an, wenn er den Kontakt
selbst hat UND sein eigener Feldwert vom uebernommenen Wert abweicht - so wird
der ueberschriebene Arbeitsplatz gewarnt, waehrend bereits aktuelle Clients
nicht benachrichtigt werden. Bereits gezeigte Notizen merkt sich jeder Client
lokal; alte Notizen werden nach 7 Tagen aufgeraeumt.
- **Clientuebergreifende Sync-Sperre (Mehrplatz).** In den Einstellungen laesst - **Clientuebergreifende Sync-Sperre (Mehrplatz).** In den Einstellungen laesst
sich ein gemeinsames Verzeichnis (Netzlaufwerk/UNC) hinterlegen. Synct ein sich ein gemeinsames Verzeichnis (Netzlaufwerk/UNC) hinterlegen. Synct ein
Arbeitsplatz, legt er dort eine Lock-Datei an (atomar via `CreateNew`); andere Arbeitsplatz, legt er dort eine Lock-Datei an (atomar via `CreateNew`); andere
@@ -56,6 +90,13 @@ Versionsschema ist `x.x.x.x` (siehe `release.sh`).
### Geaendert ### Geaendert
- **Manueller und automatischer Sync vereinheitlicht.** Beide Pfade laufen jetzt
ueber einen gemeinsamen `SyncCoordinator` und nutzen damit dieselben Schutz-
und Komfortfunktionen: lokaler Re-Entrancy-Schutz (prozessweit - auch manuell
vs. automatisch koennen nicht mehr gleichzeitig laufen), clientuebergreifende
Lock-Datei, Konflikt-Notizen anderer Arbeitsplaetze und vollstaendiges
Protokoll. Vorher umging der manuelle "Synchronisieren"-Button (Fenster) die
Lock-Datei und einen Teil des Protokolls.
- **Doppelte Syncs verhindert (lokal).** Der Schutz gegen gleichzeitig laufende - **Doppelte Syncs verhindert (lokal).** Der Schutz gegen gleichzeitig laufende
Syncs (manuell + Auto-Sync-Timer) ist jetzt atomar (`Interlocked`) statt eines Syncs (manuell + Auto-Sync-Timer) ist jetzt atomar (`Interlocked`) statt eines
nicht-atomaren `volatile bool`, bei dem beide in einem Zeitfenster nicht-atomaren `volatile bool`, bei dem beide in einem Zeitfenster
+49
View File
@@ -260,11 +260,60 @@ StarfaceOutlookSync.exe
Alle Daten werden lokal pro Benutzer gespeichert: Alle Daten werden lokal pro Benutzer gespeichert:
- `%AppData%\StarfaceOutlookSync\profiles.json` - Sync-Profile mit Zugangsdaten - `%AppData%\StarfaceOutlookSync\profiles.json` - Sync-Profile mit Zugangsdaten
- `%AppData%\StarfaceOutlookSync\mappings\` - Kontakt-Zuordnungen pro Profil - `%AppData%\StarfaceOutlookSync\mappings\` - Kontakt-Zuordnungen pro Profil
- `%AppData%\StarfaceOutlookSync\sync.log` - Protokoll (Syncs, Konflikte, Fehler);
im Hauptfenster ueber den Button **Protokoll** einsehbar
### SSL-Zertifikate ### SSL-Zertifikate
Self-signed Zertifikate der Starface werden automatisch akzeptiert. Es ist kein manueller Zertifikat-Import erforderlich. Self-signed Zertifikate der Starface werden automatisch akzeptiert. Es ist kein manueller Zertifikat-Import erforderlich.
### Mehrplatz-Betrieb / Sync-Sperre
Mehrere Arbeitsplaetze koennen dasselbe Starface-Adressbuch pflegen. Damit sich
gleichzeitig laufende Syncs nicht ins Gehege kommen (Dubletten, ueberschriebene
Aenderungen), gibt es zwei Schutzebenen:
**1. Lokal (immer aktiv):** Auf einem PC kann nie mehr als ein Sync gleichzeitig
laufen. Startet der Auto-Sync-Timer, waehrend ein manueller Sync laeuft (oder
umgekehrt), wird der zweite Lauf uebersprungen. Atomar per `Interlocked`.
**2. Clientuebergreifend (optional):** In den Einstellungen kann ein
**gemeinsames Verzeichnis** (Netzlaufwerk oder UNC-Pfad wie
`\\server\freigabe\sync`) hinterlegt werden. Funktionsweise:
- Beim Start eines Syncs legt der Client dort die Datei **`starface-sync.lock`**
an - **atomar** ueber `FileMode.CreateNew`: das Anlegen schlaegt fehl, wenn
die Datei bereits existiert. Damit kann immer nur ein Client gleichzeitig die
Sperre halten.
- Die Datei wird waehrend des gesamten Syncs **offen gehalten** und am Ende
wieder **geloescht**. Sie existiert also nur, solange tatsaechlich gerade
synchronisiert wird (bei kleinen Adressbuechern nur sehr kurz).
- Inhalt der Datei: `Rechnername | Benutzer | UTC-Zeitstempel | Prozess-ID` -
damit man sieht, wer gerade synct.
- Findet ein anderer Client die Sperre vor, **wartet** er (Abfrage alle 3
Sekunden, bis zu 2 Minuten) und synct erst danach. Wird die Sperre nicht frei,
wird der Lauf uebersprungen und beim naechsten Intervall erneut versucht.
- **Absturzsicher:** Stuerzt ein Client mitten im Sync ab, gibt Windows das
Datei-Handle frei. Die verwaiste Lock-Datei gilt nach 15 Minuten als veraltet
und wird vom naechsten Client uebernommen. Lebt der Halter noch, scheitert das
Loeschen am offenen Handle - die Sperre bleibt also korrekt bestehen.
- Ist **kein** Verzeichnis konfiguriert oder es ist nicht erreichbar, laeuft der
Sync ohne diese Sperre weiter (die lokale Sperre bleibt aktiv).
**Konflikt-Hinweise:** Wird im bidirektionalen Modus ein echter Feld-Konflikt
aufgeloest (dasselbe Feld auf beiden Seiten unterschiedlich geaendert, Outlook
gewinnt), legt der Client eine Notiz im Unterordner `conflicts/` des gemeinsamen
Verzeichnisses ab - zugeordnet ueber die StarfaceId des Kontakts. Beim naechsten
Sync zeigt ein anderer Arbeitsplatz die Meldung als Tray-Hinweis - aber **nur,
wenn er den Kontakt selbst hat UND sein eigener Feldwert vom uebernommenen Wert
abweicht** (so erfaehrt der ueberschriebene Arbeitsplatz davon, waehrend Clients,
die den Wert ohnehin schon haben, nicht benachrichtigt werden). Gezeigte Notizen
merkt sich jeder Client lokal, veraltete Notizen werden nach 7 Tagen entfernt.
> Hinweis: Im Mehrplatz-Betrieb sollte die **bidirektionale** Sync-Richtung
> verwendet werden. Die Ein-Richtungs-Modi ("Ersetzen") wuerden die von anderen
> Arbeitsplaetzen gepflegten Kontakte loeschen.
## Lizenz ## Lizenz
Proprietaer - Alle Rechte vorbehalten. Proprietaer - Alle Rechte vorbehalten.
+2 -2
View File
@@ -2,7 +2,7 @@
; Erfordert Inno Setup 6.x (https://jrsoftware.org/isinfo.php) ; Erfordert Inno Setup 6.x (https://jrsoftware.org/isinfo.php)
#define MyAppName "Starface Outlook Sync" #define MyAppName "Starface Outlook Sync"
#define MyAppVersion "0.0.0.27" #define MyAppVersion "0.0.0.30"
#define MyAppPublisher "HackerSoft - Hacker-Net Telekommunikation" #define MyAppPublisher "HackerSoft - Hacker-Net Telekommunikation"
#define MyAppURL "https://www.hacker-net.de" #define MyAppURL "https://www.hacker-net.de"
#define MyAppExeName "StarfaceOutlookSync.exe" #define MyAppExeName "StarfaceOutlookSync.exe"
@@ -32,7 +32,7 @@ Name: "german"; MessagesFile: "compiler:Languages\German.isl"
[Tasks] [Tasks]
Name: "desktopicon"; Description: "Desktop-Verknuepfung erstellen"; GroupDescription: "Zusaetzliche Optionen:" Name: "desktopicon"; Description: "Desktop-Verknuepfung erstellen"; GroupDescription: "Zusaetzliche Optionen:"
Name: "autostart"; Description: "Bei Windows-Anmeldung automatisch starten"; GroupDescription: "Zusaetzliche Optionen:"; Flags: checkedonce Name: "autostart"; Description: "Bei Windows-Anmeldung automatisch starten (fuer ALLE Benutzer; einzelne Benutzer spaeter in den Einstellungen)"; GroupDescription: "Zusaetzliche Optionen:"; Flags: checkedonce
[Files] [Files]
; Hauptanwendung - Pfad anpassen nach Build ; Hauptanwendung - Pfad anpassen nach Build
@@ -0,0 +1,26 @@
namespace StarfaceOutlookSync.Models
{
/// <summary>
/// Hinweis ueber einen aufgeloesten Feld-Konflikt, der im gemeinsamen
/// Verzeichnis abgelegt wird, damit auch andere Arbeitsplaetze (die denselben
/// Kontakt pflegen) erfahren, dass ein Wert ueberschrieben wurde.
/// </summary>
public class ConflictNotice
{
public string Id { get; set; } = "";
public string ByHost { get; set; } = "";
public string ByUser { get; set; } = "";
public string TimestampUtc { get; set; } = "";
public string StarfaceId { get; set; } = "";
public string ContactName { get; set; } = "";
public string Field { get; set; } = "";
public string FieldKey { get; set; } = "";
public string OutlookValue { get; set; } = "";
public string StarfaceValue { get; set; } = "";
public string Winner { get; set; } = "";
public override string ToString() =>
$"{ContactName}: Feld '{Field}' geaendert an Arbeitsplatz {ByHost} " +
$"(Outlook: '{OutlookValue}' / Starface: '{StarfaceValue}') -> {Winner} uebernommen";
}
}
@@ -73,6 +73,10 @@ namespace StarfaceOutlookSync.Models
public int Errors { get; set; } public int Errors { get; set; }
public System.Collections.Generic.List<string> ErrorMessages { get; set; } = new System.Collections.Generic.List<string>(); public System.Collections.Generic.List<string> ErrorMessages { get; set; } = new System.Collections.Generic.List<string>();
// Was konkret veraendert wurde (erstellt/aktualisiert/geloescht je Kontakt),
// fuer das Protokoll.
public System.Collections.Generic.List<string> Changes { get; set; } = new System.Collections.Generic.List<string>();
// Echte Feld-Konflikte (dasselbe Feld auf beiden Seiten geaendert), die // Echte Feld-Konflikte (dasselbe Feld auf beiden Seiten geaendert), die
// ueber die Vorrang-Regel aufgeloest wurden. Fuer Benutzer-Hinweise. // ueber die Vorrang-Regel aufgeloest wurden. Fuer Benutzer-Hinweise.
public System.Collections.Generic.List<FieldConflict> Conflicts { get; set; } = new System.Collections.Generic.List<FieldConflict>(); public System.Collections.Generic.List<FieldConflict> Conflicts { get; set; } = new System.Collections.Generic.List<FieldConflict>();
@@ -82,7 +86,8 @@ namespace StarfaceOutlookSync.Models
{ {
public string StarfaceId { get; set; } = ""; public string StarfaceId { get; set; } = "";
public string ContactName { get; set; } = ""; public string ContactName { get; set; } = "";
public string Field { get; set; } = ""; public string Field { get; set; } = ""; // Anzeige-Label, z.B. "E-Mail"
public string FieldKey { get; set; } = ""; // stabiler Schluessel, z.B. "Email"
public string OutlookValue { get; set; } = ""; public string OutlookValue { get; set; } = "";
public string StarfaceValue { get; set; } = ""; public string StarfaceValue { get; set; } = "";
public string Winner { get; set; } = ""; // "Outlook" oder "Starface" public string Winner { get; set; } = ""; // "Outlook" oder "Starface"
@@ -11,6 +11,15 @@ namespace StarfaceOutlookSync.Models
public bool SyncOnStart { get; set; } = false; public bool SyncOnStart { get; set; } = false;
public bool AutoAcceptOutlookPrompt { get; set; } = false; public bool AutoAcceptOutlookPrompt { get; set; } = false;
// Tray-Benachrichtigungen. Allgemein = Info-Meldungen (Sync laeuft/fertig).
// WarnungenFehler = nur Konflikte und Fehler. Beide unabhaengig schaltbar.
public bool NotificationsEnabled { get; set; } = true;
public bool NotifyWarningsErrors { get; set; } = true;
// Protokoll-Eintraege aelter als X Tage automatisch entfernen. 0 = aus
// (alle Eintraege bleiben erhalten).
public int LogRetentionDays { get; set; } = 0;
// Gemeinsames Verzeichnis (Netzlaufwerk/UNC) fuer die clientuebergreifende // Gemeinsames Verzeichnis (Netzlaufwerk/UNC) fuer die clientuebergreifende
// Sync-Sperre. Leer = keine Sperre (nur lokaler Schutz). Verhindert, dass // Sync-Sperre. Leer = keine Sperre (nur lokaler Schutz). Verhindert, dass
// mehrere Arbeitsplaetze gleichzeitig dasselbe Adressbuch synchronisieren. // mehrere Arbeitsplaetze gleichzeitig dasselbe Adressbuch synchronisieren.
@@ -0,0 +1,76 @@
using System;
using System.Diagnostics;
using System.Security.Principal;
using Microsoft.Win32;
namespace StarfaceOutlookSync.Services
{
/// <summary>
/// Verwaltet den Windows-Autostart ueber die Run-Schluessel:
/// - pro Benutzer -> HKCU\...\Run
/// - alle Benutzer -> HKLM\...\Run (nur mit Admin-Rechten aenderbar)
/// Das Setup setzt den Autostart fuer alle Benutzer (HKLM); hierueber laesst
/// er sich nachtraeglich umstellen oder entfernen.
/// </summary>
public static class AutostartManager
{
private const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
private const string ValueName = "StarfaceOutlookSync";
private static string ExePath()
{
try
{
var p = Process.GetCurrentProcess().MainModule?.FileName;
if (!string.IsNullOrEmpty(p)) return p;
}
catch { }
return System.Reflection.Assembly.GetEntryAssembly()?.Location ?? "";
}
public static bool IsAdmin()
{
try
{
using (var id = WindowsIdentity.GetCurrent())
return new WindowsPrincipal(id).IsInRole(WindowsBuiltInRole.Administrator);
}
catch { return false; }
}
public static bool GetUserAutostart() => HasValue(Registry.CurrentUser);
public static bool GetMachineAutostart() => HasValue(Registry.LocalMachine);
public static void SetUserAutostart(bool enabled) => SetValue(Registry.CurrentUser, enabled);
/// <summary>Setzt/entfernt den Autostart fuer alle Benutzer. Braucht Admin-Rechte. Gibt Erfolg zurueck.</summary>
public static bool SetMachineAutostart(bool enabled) => SetValue(Registry.LocalMachine, enabled);
private static bool HasValue(RegistryKey root)
{
try
{
using (var k = root.OpenSubKey(RunKey, false))
return k?.GetValue(ValueName) != null;
}
catch { return false; }
}
private static bool SetValue(RegistryKey root, bool enabled)
{
try
{
using (var k = root.CreateSubKey(RunKey))
{
if (k == null) return false;
if (enabled)
k.SetValue(ValueName, "\"" + ExePath() + "\"", RegistryValueKind.String);
else if (k.GetValue(ValueName) != null)
k.DeleteValue(ValueName, false);
}
return true;
}
catch { return false; }
}
}
}
@@ -0,0 +1,178 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using StarfaceOutlookSync.Models;
namespace StarfaceOutlookSync.Services
{
/// <summary>
/// Verteilt Konflikt-Hinweise ueber das gemeinsame Verzeichnis an alle
/// Arbeitsplaetze. Wer einen echten Feld-Konflikt aufloest, legt eine Notiz
/// ab; andere Clients zeigen beim naechsten Sync die Notizen zu Kontakten,
/// die sie selbst gemappt haben (per StarfaceId). Bereits gezeigte Notizen
/// merkt sich jeder Client lokal, damit sie nicht doppelt erscheinen.
/// </summary>
public class ConflictNotifier
{
private static readonly TimeSpan Ttl = TimeSpan.FromDays(7);
private readonly string _seenFile;
public ConflictNotifier()
{
var dir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"StarfaceOutlookSync");
try { Directory.CreateDirectory(dir); } catch { }
_seenFile = Path.Combine(dir, "seen-conflicts.json");
}
private static string ConflictsDir(string sharedDir) => Path.Combine(sharedDir, "conflicts");
/// <summary>Legt fuer jeden Konflikt eine Notiz im gemeinsamen Verzeichnis ab.</summary>
public void Write(string sharedDir, IEnumerable<FieldConflict> conflicts)
{
if (string.IsNullOrWhiteSpace(sharedDir)) return;
var list = conflicts?.ToList();
if (list == null || list.Count == 0) return;
try
{
var dir = ConflictsDir(sharedDir);
Directory.CreateDirectory(dir);
var host = Environment.MachineName;
var user = Environment.UserName;
var ts = DateTime.UtcNow.ToString("o");
foreach (var c in list)
{
var notice = new ConflictNotice
{
Id = Guid.NewGuid().ToString("N"),
ByHost = host,
ByUser = user,
TimestampUtc = ts,
StarfaceId = c.StarfaceId,
ContactName = c.ContactName,
Field = c.Field,
FieldKey = c.FieldKey,
OutlookValue = c.OutlookValue,
StarfaceValue = c.StarfaceValue,
Winner = c.Winner
};
try
{
File.WriteAllText(Path.Combine(dir, notice.Id + ".json"),
JsonConvert.SerializeObject(notice, Formatting.Indented));
}
catch { }
}
}
catch { }
}
/// <summary>
/// Liefert ungesehene Konflikt-Notizen, die Kontakte dieses Clients
/// betreffen und nicht von ihm selbst stammen. Es werden nur die Notizen
/// zurueckgegeben, bei denen der EIGENE aktuelle Feldwert vom uebernommenen
/// (Gewinner-)Wert abweicht - wer den Wert ohnehin schon hat, wird nicht
/// benachrichtigt. myContacts bildet StarfaceId -> eigener Kontaktstand ab.
/// Markiert verarbeitete Notizen als gesehen und raeumt veraltete auf.
/// </summary>
public List<ConflictNotice> GetPending(string sharedDir, IDictionary<string, UnifiedContact> myContacts)
{
var result = new List<ConflictNotice>();
if (string.IsNullOrWhiteSpace(sharedDir)) return result;
var dir = ConflictsDir(sharedDir);
string[] files;
try
{
if (!Directory.Exists(dir)) return result;
files = Directory.GetFiles(dir, "*.json");
}
catch { return result; }
var seen = LoadSeen();
var host = Environment.MachineName;
var existingIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var f in files)
{
ConflictNotice n = null;
try { n = JsonConvert.DeserializeObject<ConflictNotice>(File.ReadAllText(f)); }
catch { }
if (n == null || string.IsNullOrEmpty(n.Id)) continue;
// Veraltete Notizen entfernen.
if (DateTime.TryParse(n.TimestampUtc, out var ts)
&& DateTime.UtcNow - ts.ToUniversalTime() > Ttl)
{
try { File.Delete(f); } catch { }
continue;
}
existingIds.Add(n.Id);
if (seen.Contains(n.Id)) continue; // schon gezeigt
if (string.Equals(n.ByHost, host, StringComparison.OrdinalIgnoreCase))
{
seen.Add(n.Id); // selbst erzeugt -> nicht erneut anzeigen
continue;
}
// Habe ich diesen Kontakt ueberhaupt?
UnifiedContact mine = null;
bool haveContact = !string.IsNullOrEmpty(n.StarfaceId)
&& myContacts != null
&& myContacts.TryGetValue(n.StarfaceId, out mine);
if (!haveContact)
continue; // betrifft mich nicht (kein seen -> evtl. spaeter relevant)
// Bin ich wirklich betroffen? Nur wenn mein aktueller Feldwert vom
// uebernommenen Wert abweicht. Wer den Gewinner-Wert schon hat, wird
// nicht benachrichtigt.
if (mine != null && !string.IsNullOrEmpty(n.FieldKey))
{
var winnerValue = string.Equals(n.Winner, "Outlook", StringComparison.OrdinalIgnoreCase)
? n.OutlookValue : n.StarfaceValue;
var myValue = ContactMerger.GetValue(mine, n.FieldKey);
if (ContactMerger.ValuesEqual(n.FieldKey, myValue, winnerValue))
{
seen.Add(n.Id); // nicht betroffen -> als erledigt merken
continue;
}
}
result.Add(n);
seen.Add(n.Id);
}
// Gesehen-Liste auf noch vorhandene Notizen eindampfen.
seen.IntersectWith(existingIds);
SaveSeen(seen);
return result;
}
private HashSet<string> LoadSeen()
{
try
{
if (File.Exists(_seenFile))
return new HashSet<string>(
JsonConvert.DeserializeObject<List<string>>(File.ReadAllText(_seenFile)) ?? new List<string>(),
StringComparer.OrdinalIgnoreCase);
}
catch { }
return new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
private void SaveSeen(HashSet<string> seen)
{
try { File.WriteAllText(_seenFile, JsonConvert.SerializeObject(seen.ToList())); }
catch { }
}
}
}
@@ -15,6 +15,7 @@ namespace StarfaceOutlookSync.Services
{ {
private class FieldDef private class FieldDef
{ {
public string Key;
public string Label; public string Label;
public Func<UnifiedContact, string> Get; public Func<UnifiedContact, string> Get;
public Action<UnifiedContact, string> Set; public Action<UnifiedContact, string> Set;
@@ -23,28 +24,43 @@ namespace StarfaceOutlookSync.Services
private static readonly FieldDef[] Fields = new[] private static readonly FieldDef[] Fields = new[]
{ {
new FieldDef { Label = "Vorname", Get = c => c.FirstName, Set = (c, v) => c.FirstName = v }, new FieldDef { Key = "FirstName", Label = "Vorname", Get = c => c.FirstName, Set = (c, v) => c.FirstName = v },
new FieldDef { Label = "Nachname", Get = c => c.LastName, Set = (c, v) => c.LastName = v }, new FieldDef { Key = "LastName", Label = "Nachname", Get = c => c.LastName, Set = (c, v) => c.LastName = v },
new FieldDef { Label = "Firma", Get = c => c.Company, Set = (c, v) => c.Company = v }, new FieldDef { Key = "Company", Label = "Firma", Get = c => c.Company, Set = (c, v) => c.Company = v },
new FieldDef { Label = "Position", Get = c => c.JobTitle, Set = (c, v) => c.JobTitle = v }, new FieldDef { Key = "JobTitle", Label = "Position", Get = c => c.JobTitle, Set = (c, v) => c.JobTitle = v },
new FieldDef { Label = "E-Mail", Get = c => c.Email, Set = (c, v) => c.Email = v }, new FieldDef { Key = "Email", Label = "E-Mail", Get = c => c.Email, Set = (c, v) => c.Email = v },
new FieldDef { Label = "E-Mail 2", Get = c => c.EmailSecondary, Set = (c, v) => c.EmailSecondary = v }, new FieldDef { Key = "EmailSecondary", Label = "E-Mail 2", Get = c => c.EmailSecondary, Set = (c, v) => c.EmailSecondary = v },
new FieldDef { Label = "Telefon", Get = c => c.PhoneWork, Set = (c, v) => c.PhoneWork = v, IsPhone = true }, new FieldDef { Key = "PhoneWork", Label = "Telefon", Get = c => c.PhoneWork, Set = (c, v) => c.PhoneWork = v, IsPhone = true },
new FieldDef { Label = "Mobil", Get = c => c.PhoneMobile, Set = (c, v) => c.PhoneMobile = v, IsPhone = true }, new FieldDef { Key = "PhoneMobile", Label = "Mobil", Get = c => c.PhoneMobile, Set = (c, v) => c.PhoneMobile = v, IsPhone = true },
new FieldDef { Label = "Telefon privat", Get = c => c.PhoneHome, Set = (c, v) => c.PhoneHome = v, IsPhone = true }, new FieldDef { Key = "PhoneHome", Label = "Telefon privat", Get = c => c.PhoneHome, Set = (c, v) => c.PhoneHome = v, IsPhone = true },
new FieldDef { Label = "Fax", Get = c => c.Fax, Set = (c, v) => c.Fax = v, IsPhone = true }, new FieldDef { Key = "Fax", Label = "Fax", Get = c => c.Fax, Set = (c, v) => c.Fax = v, IsPhone = true },
new FieldDef { Label = "Strasse", Get = c => c.Street, Set = (c, v) => c.Street = v }, new FieldDef { Key = "Street", Label = "Strasse", Get = c => c.Street, Set = (c, v) => c.Street = v },
new FieldDef { Label = "Ort", Get = c => c.City, Set = (c, v) => c.City = v }, new FieldDef { Key = "City", Label = "Ort", Get = c => c.City, Set = (c, v) => c.City = v },
new FieldDef { Label = "PLZ", Get = c => c.PostalCode, Set = (c, v) => c.PostalCode = v }, new FieldDef { Key = "PostalCode", Label = "PLZ", Get = c => c.PostalCode, Set = (c, v) => c.PostalCode = v },
new FieldDef { Label = "Bundesland", Get = c => c.State, Set = (c, v) => c.State = v }, new FieldDef { Key = "State", Label = "Bundesland", Get = c => c.State, Set = (c, v) => c.State = v },
new FieldDef { Label = "Land", Get = c => c.Country, Set = (c, v) => c.Country = v }, new FieldDef { Key = "Country", Label = "Land", Get = c => c.Country, Set = (c, v) => c.Country = v },
new FieldDef { Label = "Webseite", Get = c => c.Website, Set = (c, v) => c.Website = v }, new FieldDef { Key = "Website", Label = "Webseite", Get = c => c.Website, Set = (c, v) => c.Website = v },
new FieldDef { Label = "Notizen", Get = c => c.Notes, Set = (c, v) => c.Notes = v }, new FieldDef { Key = "Notes", Label = "Notizen", Get = c => c.Notes, Set = (c, v) => c.Notes = v },
new FieldDef { Label = "Anrede", Get = c => c.Salutation, Set = (c, v) => c.Salutation = v }, new FieldDef { Key = "Salutation", Label = "Anrede", Get = c => c.Salutation, Set = (c, v) => c.Salutation = v },
new FieldDef { Label = "Titel", Get = c => c.Title, Set = (c, v) => c.Title = v }, new FieldDef { Key = "Title", Label = "Titel", Get = c => c.Title, Set = (c, v) => c.Title = v },
new FieldDef { Label = "Geburtstag", Get = c => c.Birthday, Set = (c, v) => c.Birthday = v }, new FieldDef { Key = "Birthday", Label = "Geburtstag", Get = c => c.Birthday, Set = (c, v) => c.Birthday = v },
}; };
/// <summary>Liest den Wert eines Feldes per stabilem Schluessel.</summary>
public static string GetValue(UnifiedContact c, string key)
{
if (c == null || string.IsNullOrEmpty(key)) return "";
var f = Fields.FirstOrDefault(x => x.Key == key);
return f == null ? "" : (f.Get(c) ?? "");
}
/// <summary>Vergleicht zwei Feldwerte (telefon-normalisiert je nach Feld).</summary>
public static bool ValuesEqual(string key, string a, string b)
{
var f = Fields.FirstOrDefault(x => x.Key == key);
return Equal(a ?? "", b ?? "", f?.IsPhone ?? false);
}
/// <summary> /// <summary>
/// Fuehrt den Outlook- und Starface-Stand gegen ihre jeweilige Baseline /// Fuehrt den Outlook- und Starface-Stand gegen ihre jeweilige Baseline
/// zusammen. outlookWins entscheidet bei echten Feld-Konflikten. /// zusammen. outlookWins entscheidet bei echten Feld-Konflikten.
@@ -95,6 +111,7 @@ namespace StarfaceOutlookSync.Services
StarfaceId = starface.StarfaceId, StarfaceId = starface.StarfaceId,
ContactName = outlook.DisplayName, ContactName = outlook.DisplayName,
Field = f.Label, Field = f.Label,
FieldKey = f.Key,
OutlookValue = olv, OutlookValue = olv,
StarfaceValue = sfv, StarfaceValue = sfv,
Winner = outlookWins ? "Outlook" : "Starface" Winner = outlookWins ? "Outlook" : "Starface"
+124
View File
@@ -0,0 +1,124 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace StarfaceOutlookSync.Services
{
/// <summary>
/// Einfaches, threadsicheres Datei-Protokoll. Haelt fest, was bei Syncs
/// passiert (Ergebnisse, Konflikte, Fehler) - dauerhaft nachlesbar, auch
/// nachdem eine Tray-Meldung verschwunden ist.
/// </summary>
public static class Logger
{
private static readonly object _lock = new object();
private const long MaxBytes = 2 * 1024 * 1024; // 2 MB, dann Rotation
public static string LogFilePath { get; } = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"StarfaceOutlookSync", "sync.log");
public static void Log(string message)
{
try
{
lock (_lock)
{
Directory.CreateDirectory(Path.GetDirectoryName(LogFilePath));
Rotate();
var line = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}{Environment.NewLine}";
File.AppendAllText(LogFilePath, line, Encoding.UTF8);
}
}
catch { }
}
private static void Rotate()
{
try
{
var fi = new FileInfo(LogFilePath);
if (fi.Exists && fi.Length > MaxBytes)
{
var bak = LogFilePath + ".1";
if (File.Exists(bak)) File.Delete(bak);
File.Move(LogFilePath, bak);
}
}
catch { }
}
public static string ReadAll()
{
try
{
lock (_lock)
{
if (!File.Exists(LogFilePath)) return "";
using (var fs = new FileStream(LogFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var sr = new StreamReader(fs, Encoding.UTF8))
return sr.ReadToEnd();
}
}
catch { return ""; }
}
/// <summary>
/// Entfernt Protokoll-Eintraege, die aelter als <paramref name="days"/>
/// Tage sind. days &lt;= 0 -> nichts tun (alle Eintraege bleiben).
/// </summary>
public static void PruneOlderThan(int days)
{
if (days <= 0) return;
try
{
lock (_lock)
{
if (!File.Exists(LogFilePath)) return;
var cutoff = DateTime.Now.AddDays(-days);
var lines = File.ReadAllLines(LogFilePath, Encoding.UTF8);
var kept = new List<string>(lines.Length);
foreach (var line in lines)
{
// Eintraege ohne erkennbaren Zeitstempel (z.B. Fortsetzungs-
// zeilen) bleiben erhalten; nur datierte Alt-Eintraege fliegen raus.
if (TryParseLineDate(line, out var dt) && dt < cutoff)
continue;
kept.Add(line);
}
if (kept.Count != lines.Length)
File.WriteAllLines(LogFilePath, kept, Encoding.UTF8);
}
}
catch { }
}
private static bool TryParseLineDate(string line, out DateTime dt)
{
dt = default;
// Format: "[yyyy-MM-dd HH:mm:ss] ..."
if (line != null && line.Length >= 21 && line[0] == '[' && line[20] == ']')
{
return DateTime.TryParseExact(line.Substring(1, 19), "yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);
}
return false;
}
public static void Clear()
{
try
{
lock (_lock)
{
if (File.Exists(LogFilePath)) File.Delete(LogFilePath);
var bak = LogFilePath + ".1";
if (File.Exists(bak)) File.Delete(bak);
}
}
catch { }
}
}
}
@@ -0,0 +1,163 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using StarfaceOutlookSync.Models;
namespace StarfaceOutlookSync.Services
{
/// <summary>
/// Gemeinsame Orchestrierung fuer JEDEN Sync-Lauf - egal ob automatisch
/// (Tray/Timer) oder manuell (Fortschrittsfenster). Sorgt einheitlich fuer:
/// - lokalen Re-Entrancy-Schutz (prozessweit, statisch),
/// - clientuebergreifende Lock-Datei,
/// - Anzeige/Logging von Konflikt-Notizen anderer Arbeitsplaetze,
/// - Protokollierung (Start, Ergebnis, Aenderungen, Konflikte, Fehler),
/// - Verteilen eigener Konflikt-Notizen.
/// Die eigentliche UI (Tray-Meldung vs. Fenster) bleibt beim Aufrufer.
/// </summary>
public class SyncCoordinator
{
// Prozessweit: nie zwei Syncs gleichzeitig - auch nicht manuell + automatisch.
private static int _running = 0;
private readonly ProfileManager _profileManager = new ProfileManager();
private readonly ConflictNotifier _notifier = new ConflictNotifier();
public class SyncOutcome
{
public bool Skipped;
public string SkipReason = "";
public SyncResult Result;
public Exception Error;
public List<ConflictNotice> RemoteNotices = new List<ConflictNotice>();
}
/// <summary>
/// Fuehrt einen Sync koordiniert aus. runEngine kapselt den eigentlichen
/// Engine-Aufruf (inkl. ggf. Task.Run/Progress-Anbindung des Aufrufers),
/// damit das Threading-Verhalten pro Pfad erhalten bleibt. status erhaelt
/// Fortschrittstexte (Warten auf Sperre, Synchronisiere ...).
/// </summary>
public async Task<SyncOutcome> RunAsync(SyncProfile profile,
Func<Task<SyncResult>> runEngine, Action<string> status)
{
var outcome = new SyncOutcome();
if (Interlocked.CompareExchange(ref _running, 1, 0) != 0)
{
outcome.Skipped = true;
outcome.SkipReason = "Sync laeuft bereits, bitte warten...";
return outcome;
}
SyncLock crossLock = null;
var settings = UserSettings.Load();
Logger.PruneOlderThan(settings.LogRetentionDays);
var sharedDir = settings.SharedDirectory;
try
{
crossLock = await AcquireCrossClientLock(sharedDir, status);
if (crossLock == null)
{
outcome.Skipped = true;
outcome.SkipReason = "Anderer Arbeitsplatz synchronisiert gerade - uebersprungen.";
Logger.Log($"Sync '{profile.Name}' uebersprungen: anderer Arbeitsplatz synct gerade.");
return outcome;
}
// Konflikt-Hinweise anderer Arbeitsplaetze ermitteln, BEVOR der Sync
// den eigenen Stand auf den Gewinner-Wert angleicht.
try
{
outcome.RemoteNotices = _notifier.GetPending(sharedDir, MyContactsByStarfaceId());
foreach (var n in outcome.RemoteNotices)
Logger.Log($" KONFLIKT (anderer Arbeitsplatz): {n}");
}
catch { }
Logger.Log($"Sync gestartet: '{profile.Name}' (Richtung: {profile.SyncDirection})");
status?.Invoke($"Synchronisiere '{profile.Name}'...");
SyncResult result;
try
{
result = await runEngine();
}
catch (Exception ex)
{
outcome.Error = ex;
Logger.Log($"Sync FEHLER '{profile.Name}': {ex.Message}");
return outcome;
}
outcome.Result = result;
var msg = $"{profile.Name}: {result.Created} erstellt, {result.Updated} aktualisiert"
+ (result.Errors > 0 ? $", {result.Errors} Fehler" : "")
+ (result.Conflicts.Count > 0 ? $", {result.Conflicts.Count} Konflikt(e)" : "");
Logger.Log($"Sync fertig: {msg}");
foreach (var ch in result.Changes) Logger.Log($" {ch}");
foreach (var em in result.ErrorMessages) Logger.Log($" Fehler: {em}");
foreach (var c in result.Conflicts) Logger.Log($" KONFLIKT: {c}");
// Andere Arbeitsplaetze ueber eigene Konflikte informieren.
if (result.Conflicts.Count > 0)
_notifier.Write(sharedDir, result.Conflicts);
return outcome;
}
finally
{
crossLock?.Dispose();
Interlocked.Exchange(ref _running, 0);
}
}
private async Task<SyncLock> AcquireCrossClientLock(string dir, Action<string> status)
{
if (string.IsNullOrWhiteSpace(dir))
return SyncLock.NoOp();
try
{
// Legt das Verzeichnis bei Bedarf an (idempotent). Funktioniert mit
// UNC-Pfaden (\\server\freigabe\...) - kein Netzlaufwerk noetig.
Directory.CreateDirectory(dir);
}
catch
{
status?.Invoke("Gemeinsames Verzeichnis nicht erreichbar - synce ohne Sperre.");
return SyncLock.NoOp();
}
var deadline = DateTime.UtcNow.AddMinutes(2);
int attempt = 0;
while (true)
{
var l = SyncLock.TryAcquire(dir, out var heldBy);
if (l != null) return l;
if (DateTime.UtcNow >= deadline) return null;
attempt++;
status?.Invoke($"Warte auf anderen Arbeitsplatz ({heldBy ?? "unbekannt"})... ({attempt})");
await Task.Delay(3000);
}
}
private Dictionary<string, UnifiedContact> MyContactsByStarfaceId()
{
var map = new Dictionary<string, UnifiedContact>(StringComparer.OrdinalIgnoreCase);
try
{
foreach (var p in _profileManager.GetProfiles())
foreach (var m in _profileManager.GetMappings(p.Id))
if (!string.IsNullOrEmpty(m.StarfaceId) && !map.ContainsKey(m.StarfaceId))
map[m.StarfaceId] = m.LastOutlook;
}
catch { }
return map;
}
}
}
+24 -17
View File
@@ -15,6 +15,13 @@ namespace StarfaceOutlookSync.Services
private void Log(string message) => OnProgress?.Invoke(message); private void Log(string message) => OnProgress?.Invoke(message);
/// <summary>Protokolliert eine tatsaechliche Aenderung (fuer Live-Log UND SyncResult.Changes).</summary>
private void Action(SyncResult result, string message)
{
Log(" " + message);
result?.Changes.Add(message);
}
/// <summary> /// <summary>
/// Setzt die Baseline eines Mappings auf den uebergebenen Stand beider /// Setzt die Baseline eines Mappings auf den uebergebenen Stand beider
/// Seiten (Snapshot + Hash). Der Snapshot wird fuer das Feld-Merge bei /// Seiten (Snapshot + Hash). Der Snapshot wird fuer das Feld-Merge bei
@@ -184,7 +191,7 @@ namespace StarfaceOutlookSync.Services
if (await starface.DeleteContactAsync(mapping.StarfaceId)) if (await starface.DeleteContactAsync(mapping.StarfaceId))
{ {
result.Updated++; result.Updated++;
Log($" Geloescht (OL->SF): {sc.DisplayName}"); Action(result, $"Geloescht (OL->SF): {sc.DisplayName}");
} }
continue; continue;
} }
@@ -202,7 +209,7 @@ namespace StarfaceOutlookSync.Services
if (await starface.DeleteContactAsync(mapping.StarfaceId)) if (await starface.DeleteContactAsync(mapping.StarfaceId))
{ {
result.Updated++; result.Updated++;
Log($" Geloescht (OL->SF): {sc.DisplayName}"); Action(result, $"Geloescht (OL->SF): {sc.DisplayName}");
} }
continue; continue;
} }
@@ -245,7 +252,7 @@ namespace StarfaceOutlookSync.Services
if (_outlookService.DeleteContact(oc.OutlookEntryId)) if (_outlookService.DeleteContact(oc.OutlookEntryId))
{ {
result.Updated++; result.Updated++;
Log($" Geloescht (SF->OL): {oc.DisplayName}"); Action(result, $"Geloescht (SF->OL): {oc.DisplayName}");
} }
continue; continue;
} }
@@ -263,7 +270,7 @@ namespace StarfaceOutlookSync.Services
if (_outlookService.DeleteContact(oc.OutlookEntryId)) if (_outlookService.DeleteContact(oc.OutlookEntryId))
{ {
result.Updated++; result.Updated++;
Log($" Geloescht (SF->OL): {oc.DisplayName}"); Action(result, $"Geloescht (SF->OL): {oc.DisplayName}");
} }
continue; continue;
} }
@@ -322,7 +329,7 @@ namespace StarfaceOutlookSync.Services
{ {
SetBaseline(mapping, oc, updated); SetBaseline(mapping, oc, updated);
result.Updated++; result.Updated++;
Log($" Aktualisiert (OL->SF): {oc.DisplayName}"); Action(result, $"Aktualisiert (OL->SF): {oc.DisplayName}");
} }
} }
else if (sfChanged && !olChanged && (profile.SyncDirection == SyncDirection.Both || profile.SyncDirection == SyncDirection.StarfaceToOutlook)) else if (sfChanged && !olChanged && (profile.SyncDirection == SyncDirection.Both || profile.SyncDirection == SyncDirection.StarfaceToOutlook))
@@ -333,7 +340,7 @@ namespace StarfaceOutlookSync.Services
{ {
SetBaseline(mapping, updated, sc); SetBaseline(mapping, updated, sc);
result.Updated++; result.Updated++;
Log($" Aktualisiert (SF->OL): {sc.DisplayName}"); Action(result, $"Aktualisiert (SF->OL): {sc.DisplayName}");
} }
} }
else if (olChanged && sfChanged) else if (olChanged && sfChanged)
@@ -366,9 +373,9 @@ namespace StarfaceOutlookSync.Services
mapping.LastSyncHash = ""; mapping.LastSyncHash = "";
result.Updated++; result.Updated++;
foreach (var cf in conflicts) result.Conflicts.Add(cf); foreach (var cf in conflicts) result.Conflicts.Add(cf);
Log(conflicts.Count > 0 Action(result, conflicts.Count > 0
? $" Beidseitig geaendert, zusammengefuehrt ({conflicts.Count} Feld-Konflikt(e), Outlook gewinnt): {oc.DisplayName}" ? $"Beidseitig geaendert, zusammengefuehrt ({conflicts.Count} Feld-Konflikt(e), Outlook gewinnt): {oc.DisplayName}"
: $" Beidseitig geaendert, zusammengefuehrt: {oc.DisplayName}"); : $"Beidseitig geaendert, zusammengefuehrt: {oc.DisplayName}");
} }
} }
else if (profile.SyncDirection != SyncDirection.StarfaceToOutlook) else if (profile.SyncDirection != SyncDirection.StarfaceToOutlook)
@@ -380,7 +387,7 @@ namespace StarfaceOutlookSync.Services
{ {
SetBaseline(mapping, oc, updated); SetBaseline(mapping, oc, updated);
result.Updated++; result.Updated++;
Log($" Konflikt (OL gewinnt): {oc.DisplayName}"); Action(result, $"Konflikt (OL gewinnt): {oc.DisplayName}");
} }
} }
else else
@@ -390,7 +397,7 @@ namespace StarfaceOutlookSync.Services
{ {
SetBaseline(mapping, updated, sc); SetBaseline(mapping, updated, sc);
result.Updated++; result.Updated++;
Log($" Konflikt (SF gewinnt): {sc.DisplayName}"); Action(result, $"Konflikt (SF gewinnt): {sc.DisplayName}");
} }
} }
} }
@@ -441,7 +448,7 @@ namespace StarfaceOutlookSync.Services
processedStarfaceIds.Add(match.StarfaceId); processedStarfaceIds.Add(match.StarfaceId);
unmappedStarface.Remove(match); unmappedStarface.Remove(match);
result.Updated++; result.Updated++;
Log($" Verknuepft (OL->SF): {oc.DisplayName}"); Action(result, $"Verknuepft (OL->SF): {oc.DisplayName}");
} }
} }
else else
@@ -462,7 +469,7 @@ namespace StarfaceOutlookSync.Services
LastStarfaceHash = created.GetHash() LastStarfaceHash = created.GetHash()
}); });
result.Created++; result.Created++;
Log($" Erstellt (OL->SF): {oc.DisplayName}"); Action(result, $"Erstellt (OL->SF): {oc.DisplayName}");
} }
else else
{ {
@@ -521,7 +528,7 @@ namespace StarfaceOutlookSync.Services
processedOutlookIds.Add(match.OutlookEntryId); processedOutlookIds.Add(match.OutlookEntryId);
unmappedOutlook.Remove(match); unmappedOutlook.Remove(match);
result.Updated++; result.Updated++;
Log($" Verknuepft (SF->OL): {sc.DisplayName}"); Action(result, $"Verknuepft (SF->OL): {sc.DisplayName}");
} }
} }
else else
@@ -541,7 +548,7 @@ namespace StarfaceOutlookSync.Services
LastOutlookHash = created.GetHash() LastOutlookHash = created.GetHash()
}); });
result.Created++; result.Created++;
Log($" Erstellt (SF->OL): {sc.DisplayName}"); Action(result, $"Erstellt (SF->OL): {sc.DisplayName}");
} }
} }
} }
@@ -581,7 +588,7 @@ namespace StarfaceOutlookSync.Services
if (await starface.DeleteContactAsync(sc.StarfaceId)) if (await starface.DeleteContactAsync(sc.StarfaceId))
{ {
result.Updated++; result.Updated++;
Log($" Geloescht (nur in Starface): {sc.DisplayName}"); Action(result, $"Geloescht (nur in Starface): {sc.DisplayName}");
} }
} }
catch (Exception ex) catch (Exception ex)
@@ -612,7 +619,7 @@ namespace StarfaceOutlookSync.Services
if (_outlookService.DeleteContact(oc.OutlookEntryId)) if (_outlookService.DeleteContact(oc.OutlookEntryId))
{ {
result.Updated++; result.Updated++;
Log($" Geloescht (nur in Outlook): {oc.DisplayName}"); Action(result, $"Geloescht (nur in Outlook): {oc.DisplayName}");
} }
} }
catch (Exception ex) catch (Exception ex)
@@ -7,9 +7,9 @@
<AssemblyTitle>Starface Outlook Sync</AssemblyTitle> <AssemblyTitle>Starface Outlook Sync</AssemblyTitle>
<Company>HackerSoft - Hacker-Net Telekommunikation</Company> <Company>HackerSoft - Hacker-Net Telekommunikation</Company>
<Product>Starface Outlook Sync</Product> <Product>Starface Outlook Sync</Product>
<Version>0.0.0.27</Version> <Version>0.0.0.30</Version>
<AssemblyVersion>0.0.0.27</AssemblyVersion> <AssemblyVersion>0.0.0.30</AssemblyVersion>
<FileVersion>0.0.0.27</FileVersion> <FileVersion>0.0.0.30</FileVersion>
<Description>Synchronisiert Outlook-Kontakte mit Starface Telefonanlage</Description> <Description>Synchronisiert Outlook-Kontakte mit Starface Telefonanlage</Description>
<Copyright>Stefan Hacker - HackerSoft</Copyright> <Copyright>Stefan Hacker - HackerSoft</Copyright>
<RuntimeIdentifier>win-x64</RuntimeIdentifier> <RuntimeIdentifier>win-x64</RuntimeIdentifier>
+1 -1
View File
@@ -27,7 +27,7 @@ namespace StarfaceOutlookSync.UI
var lblVersion = new Label var lblVersion = new Label
{ {
Text = "Version 0.0.0.27", Text = "Version 0.0.0.30",
Left = 0, Top = 56, Width = 340, Height = 20, Left = 0, Top = 56, Width = 340, Height = 20,
TextAlign = ContentAlignment.MiddleCenter, TextAlign = ContentAlignment.MiddleCenter,
ForeColor = Color.Gray ForeColor = Color.Gray
@@ -0,0 +1,92 @@
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using StarfaceOutlookSync.Models;
using StarfaceOutlookSync.Services;
namespace StarfaceOutlookSync.UI
{
/// <summary>Zeigt das Sync-Protokoll an (read-only) mit Aktualisieren/Leeren.</summary>
public class LogViewerForm : Form
{
private TextBox _txt;
private Button _btnClose;
private Panel _panel;
public LogViewerForm()
{
Text = "Protokoll";
Size = new Size(720, 500);
StartPosition = FormStartPosition.CenterParent;
Font = new Font("Segoe UI", 9);
_txt = new TextBox
{
Multiline = true,
ReadOnly = true,
ScrollBars = ScrollBars.Both,
WordWrap = false,
Dock = DockStyle.Fill,
BackColor = Color.White,
Font = new Font("Consolas", 9)
};
_panel = new Panel { Dock = DockStyle.Bottom, Height = 44 };
var btnRefresh = new Button { Text = "Aktualisieren", Left = 10, Top = 8, Width = 100, Height = 28 };
btnRefresh.Click += (s, e) => LoadLog();
var btnClear = new Button { Text = "Leeren", Left = 118, Top = 8, Width = 80, Height = 28 };
btnClear.Click += (s, e) =>
{
if (MessageBox.Show("Protokoll wirklich leeren?", "Protokoll",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
Logger.Clear();
LoadLog();
}
};
var btnFolder = new Button { Text = "Ordner oeffnen", Left = 206, Top = 8, Width = 120, Height = 28 };
btnFolder.Click += (s, e) => OpenFolder();
_btnClose = new Button
{
Text = "Schliessen", Top = 8, Width = 100, Height = 28,
Anchor = AnchorStyles.Top | AnchorStyles.Right
};
_btnClose.Click += (s, e) => Close();
_panel.Controls.AddRange(new Control[] { btnRefresh, btnClear, btnFolder, _btnClose });
Controls.Add(_txt);
Controls.Add(_panel);
Load += (s, e) =>
{
_btnClose.Left = _panel.ClientSize.Width - _btnClose.Width - 10;
LoadLog();
};
}
private void LoadLog()
{
Logger.PruneOlderThan(UserSettings.Load().LogRetentionDays);
_txt.Text = Logger.ReadAll();
_txt.SelectionStart = _txt.TextLength;
_txt.ScrollToCaret();
}
private void OpenFolder()
{
try
{
var dir = Path.GetDirectoryName(Logger.LogFilePath);
Process.Start(new ProcessStartInfo { FileName = dir, UseShellExecute = true });
}
catch { }
}
}
}
+67 -72
View File
@@ -2,7 +2,6 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Timers; using System.Timers;
using System.Windows.Forms; using System.Windows.Forms;
@@ -16,16 +15,18 @@ namespace StarfaceOutlookSync.UI
{ {
private readonly ProfileManager _profileManager = new ProfileManager(); private readonly ProfileManager _profileManager = new ProfileManager();
private readonly SyncEngine _syncEngine = new SyncEngine(); private readonly SyncEngine _syncEngine = new SyncEngine();
private readonly SyncCoordinator _coordinator = new SyncCoordinator();
private NotifyIcon _trayIcon; private NotifyIcon _trayIcon;
private ContextMenuStrip _trayMenu; private ContextMenuStrip _trayMenu;
private ListView _profileList; private ListView _profileList;
private Button _btnNew, _btnEdit, _btnDelete, _btnSync, _btnReset, _btnSettings, _btnInfo; private Button _btnNew, _btnEdit, _btnDelete, _btnSync, _btnReset, _btnSettings, _btnLog, _btnInfo;
private StatusStrip _statusBar; private StatusStrip _statusBar;
private ToolStripStatusLabel _statusLabel; private ToolStripStatusLabel _statusLabel;
private Timer _autoSyncTimer; private Timer _autoSyncTimer;
// 0 = frei, 1 = Sync laeuft. Per Interlocked atomar geschaltet, damit
// ein manueller Sync und der Auto-Sync-Timer nicht gleichzeitig starten. // Aktive Benachrichtigungs-Einstellung (pro Sync-Lauf gesetzt).
private int _syncRunning = 0; private bool _notifyGeneral = true;
private bool _notifyWarn = true;
public MainForm() public MainForm()
{ {
@@ -38,6 +39,9 @@ namespace StarfaceOutlookSync.UI
var settings = UserSettings.Load(); var settings = UserSettings.Load();
settings.ApplyOutlookSecuritySetting(); settings.ApplyOutlookSecuritySetting();
// Protokoll bei Bedarf auf das eingestellte Alter eindampfen.
Logger.PruneOlderThan(settings.LogRetentionDays);
if (settings.StartMinimized) if (settings.StartMinimized)
{ {
WindowState = FormWindowState.Minimized; WindowState = FormWindowState.Minimized;
@@ -128,10 +132,13 @@ namespace StarfaceOutlookSync.UI
_btnSettings = new Button { Text = "Einstellungen", Width = 95, Height = 30 }; _btnSettings = new Button { Text = "Einstellungen", Width = 95, Height = 30 };
_btnSettings.Click += (s, e) => ShowSettings(); _btnSettings.Click += (s, e) => ShowSettings();
_btnLog = new Button { Text = "Protokoll", Width = 80, Height = 30 };
_btnLog.Click += (s, e) => ShowLog();
_btnInfo = new Button { Text = "Info", Width = 50, Height = 30 }; _btnInfo = new Button { Text = "Info", Width = 50, Height = 30 };
_btnInfo.Click += (s, e) => ShowAbout(); _btnInfo.Click += (s, e) => ShowAbout();
buttonPanel.Controls.AddRange(new Control[] { _btnNew, _btnEdit, _btnDelete, _btnSync, _btnReset, _btnSettings, _btnInfo }); buttonPanel.Controls.AddRange(new Control[] { _btnNew, _btnEdit, _btnDelete, _btnSync, _btnReset, _btnSettings, _btnLog, _btnInfo });
// Statusbar // Statusbar
_statusBar = new StatusStrip(); _statusBar = new StatusStrip();
@@ -340,103 +347,83 @@ namespace StarfaceOutlookSync.UI
private async Task RunSync(SyncProfile profile) private async Task RunSync(SyncProfile profile)
{ {
// Atomar pruefen-und-setzen: verhindert, dass manueller Sync und var settings = UserSettings.Load();
// Auto-Sync-Timer gleichzeitig denselben/einen Sync starten. _notifyGeneral = settings.NotificationsEnabled;
if (Interlocked.CompareExchange(ref _syncRunning, 1, 0) != 0) _notifyWarn = settings.NotifyWarningsErrors;
{
SetStatus("Sync laeuft bereits, bitte warten...");
return;
}
SyncLock crossLock = null;
try try
{ {
// Clientuebergreifende Sperre (falls gemeinsames Verzeichnis konfiguriert). // Lokaler Guard, Lock-Datei, Konflikt-Notizen und Protokoll laufen
crossLock = await AcquireCrossClientLock(); // zentral im Coordinator (gemeinsam mit dem manuellen Sync-Pfad).
if (crossLock == null) var outcome = await _coordinator.RunAsync(
profile,
runEngine: () => _syncEngine.SyncProfileAsync(profile),
status: SetStatus);
if (outcome.Skipped)
{ {
SetStatus("Anderer Arbeitsplatz synchronisiert gerade - uebersprungen."); SetStatus(outcome.SkipReason);
return; return;
} }
SetStatus($"Synchronisiere '{profile.Name}'..."); // Konflikt-Hinweise anderer Arbeitsplaetze als Tray-Meldung (falls aktiv).
_trayIcon.ShowBalloonTip(2000, "Starface Sync", ShowRemoteNoticesTray(outcome.RemoteNotices);
$"Synchronisiere '{profile.Name}'...", ToolTipIcon.Info);
var result = await _syncEngine.SyncProfileAsync(profile); if (outcome.Error != null)
{
Balloon(3000, "Starface Sync Fehler", outcome.Error.Message, ToolTipIcon.Error, warn: true);
SetStatus($"Fehler: {outcome.Error.Message}");
return;
}
var result = outcome.Result;
var msg = $"{profile.Name}: {result.Created} erstellt, {result.Updated} aktualisiert"; var msg = $"{profile.Name}: {result.Created} erstellt, {result.Updated} aktualisiert";
if (result.Errors > 0) msg += $", {result.Errors} Fehler"; if (result.Errors > 0) msg += $", {result.Errors} Fehler";
if (result.Conflicts.Count > 0) msg += $", {result.Conflicts.Count} Konflikt(e)"; if (result.Conflicts.Count > 0) msg += $", {result.Conflicts.Count} Konflikt(e)";
_trayIcon.ShowBalloonTip(3000, "Starface Sync", msg, // Zusammenfassung als Warnung werten, wenn Fehler/Konflikte auftraten.
result.Errors > 0 ? ToolTipIcon.Warning : ToolTipIcon.Info); bool noteworthy = result.Errors > 0 || result.Conflicts.Count > 0;
Balloon(3000, "Starface Sync", msg,
result.Errors > 0 ? ToolTipIcon.Warning : ToolTipIcon.Info, warn: noteworthy);
// Echte Feld-Konflikte gesondert melden, damit der Benutzer weiss, // Echte Feld-Konflikte gesondert melden (eigener Wert wurde ueberschrieben).
// dass ein Wert ueberschrieben wurde.
if (result.Conflicts.Count > 0) if (result.Conflicts.Count > 0)
{ {
var detail = string.Join("\n", result.Conflicts.Take(5).Select(c => c.ToString())); var detail = string.Join("\n", result.Conflicts.Take(5).Select(c => c.ToString()));
if (result.Conflicts.Count > 5) if (result.Conflicts.Count > 5)
detail += $"\n... und {result.Conflicts.Count - 5} weitere"; detail += $"\n... und {result.Conflicts.Count - 5} weitere";
_trayIcon.ShowBalloonTip(10000, Balloon(10000, $"Konflikt bei {result.Conflicts.Count} Kontakt(en)", detail, ToolTipIcon.Warning, warn: true);
$"Konflikt bei {result.Conflicts.Count} Kontakt(en)", detail, ToolTipIcon.Warning);
} }
SetStatus(msg); SetStatus(msg);
} }
catch (Exception ex) catch (Exception ex)
{ {
_trayIcon.ShowBalloonTip(3000, "Starface Sync Fehler", Balloon(3000, "Starface Sync Fehler", ex.Message, ToolTipIcon.Error, warn: true);
ex.Message, ToolTipIcon.Error);
SetStatus($"Fehler: {ex.Message}"); SetStatus($"Fehler: {ex.Message}");
} Logger.Log($"Sync FEHLER '{profile.Name}': {ex.Message}");
finally
{
crossLock?.Dispose();
Interlocked.Exchange(ref _syncRunning, 0);
} }
} }
/// <summary> /// <summary>Zeigt Konflikt-Hinweise anderer Arbeitsplaetze als Tray-Meldung.</summary>
/// Holt die clientuebergreifende Lock-Datei aus dem konfigurierten private void ShowRemoteNoticesTray(System.Collections.Generic.List<ConflictNotice> notices)
/// gemeinsamen Verzeichnis. Wartet bis zu 2 Minuten, falls ein anderer
/// Arbeitsplatz gerade synct. Gibt null zurueck, wenn die Sperre nicht
/// erlangt werden konnte (-> diesen Lauf ueberspringen).
/// Ist kein Verzeichnis konfiguriert oder es ist nicht erreichbar, wird
/// ohne clientuebergreifende Sperre fortgefahren (lokaler Schutz bleibt).
/// </summary>
private async Task<SyncLock> AcquireCrossClientLock()
{ {
var dir = UserSettings.Load().SharedDirectory; if (notices == null || notices.Count == 0) return;
if (string.IsNullOrWhiteSpace(dir)) var detail = string.Join("\n", notices.Take(5).Select(p => p.ToString()));
return SyncLock.NoOp(); if (notices.Count > 5)
detail += $"\n... und {notices.Count - 5} weitere";
Balloon(10000, $"Konflikt an anderem Arbeitsplatz ({notices.Count})", detail, ToolTipIcon.Warning, warn: true);
}
try /// <summary>
{ /// Zeigt eine Tray-Meldung - aber nur, wenn die passende Benachrichtigungs-
// Legt das Verzeichnis bei Bedarf an (idempotent). Funktioniert mit /// Einstellung aktiv ist. warn=true -> Warnungen/Fehler (Konflikte, Fehler),
// UNC-Pfaden (\\server\freigabe\...) - kein Netzlaufwerk noetig. /// warn=false -> allgemeine Info-Meldungen.
System.IO.Directory.CreateDirectory(dir); /// </summary>
} private void Balloon(int ms, string title, string text, ToolTipIcon icon, bool warn)
catch {
{ bool allow = warn ? _notifyWarn : _notifyGeneral;
SetStatus("Gemeinsames Verzeichnis nicht erreichbar - synce ohne Sperre."); if (allow) _trayIcon.ShowBalloonTip(ms, title, text, icon);
return SyncLock.NoOp();
}
var deadline = DateTime.UtcNow.AddMinutes(2);
int attempt = 0;
while (true)
{
var l = SyncLock.TryAcquire(dir, out var heldBy);
if (l != null) return l;
if (DateTime.UtcNow >= deadline) return null;
attempt++;
SetStatus($"Warte auf anderen Arbeitsplatz ({heldBy ?? "unbekannt"})... ({attempt})");
await Task.Delay(3000);
}
} }
private void SetStatus(string text) private void SetStatus(string text)
@@ -463,6 +450,14 @@ namespace StarfaceOutlookSync.UI
} }
} }
private void ShowLog()
{
using (var log = new LogViewerForm())
{
log.ShowDialog(this);
}
}
private void ExitApplication() private void ExitApplication()
{ {
_autoSyncTimer?.Stop(); _autoSyncTimer?.Stop();
+81 -8
View File
@@ -1,12 +1,16 @@
using System.Drawing; using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
using StarfaceOutlookSync.Models; using StarfaceOutlookSync.Models;
using StarfaceOutlookSync.Services;
namespace StarfaceOutlookSync.UI namespace StarfaceOutlookSync.UI
{ {
public class SettingsForm : Form public class SettingsForm : Form
{ {
private CheckBox _chkStartMinimized, _chkSyncOnStart, _chkAutoAcceptOutlook; private CheckBox _chkStartMinimized, _chkSyncOnStart, _chkAutoAcceptOutlook;
private CheckBox _chkNotifGeneral, _chkNotifWarn;
private CheckBox _chkAutostartUser, _chkAutostartAll;
private NumericUpDown _numLogRetention;
private TextBox _txtSharedDir; private TextBox _txtSharedDir;
private Button _btnBrowseShared; private Button _btnBrowseShared;
private Button _btnSave, _btnCancel; private Button _btnSave, _btnCancel;
@@ -61,21 +65,47 @@ namespace StarfaceOutlookSync.UI
Font = new Font("Segoe UI", 8) Font = new Font("Segoe UI", 8)
}; };
_chkNotifGeneral = new CheckBox
{
Text = "Tray-Benachrichtigungen (allgemein)",
Left = 20, Top = 144, AutoSize = true,
Checked = _settings.NotificationsEnabled
};
_chkNotifWarn = new CheckBox
{
Text = "Benachrichtigungen bei Warnungen/Fehlern (Konflikte, Fehler)",
Left = 20, Top = 170, AutoSize = true,
Checked = _settings.NotifyWarningsErrors
};
var lblLogRetention = new Label
{
Text = "Protokoll auto-leeren - Eintraege aelter als (Tage, 0 = aus):",
Left = 20, Top = 204, AutoSize = true
};
_numLogRetention = new NumericUpDown
{
Left = 305, Top = 200, Width = 55, Minimum = 0, Maximum = 3650,
Value = System.Math.Max(0, System.Math.Min(3650, _settings.LogRetentionDays))
};
var lblShared = new Label var lblShared = new Label
{ {
Text = "Gemeinsames Verzeichnis fuer Sync-Sperre (Mehrplatz, optional):", Text = "Gemeinsames Verzeichnis fuer Sync-Sperre (Mehrplatz, optional):",
Left = 20, Top = 150, AutoSize = true Left = 20, Top = 240, AutoSize = true
}; };
_txtSharedDir = new TextBox _txtSharedDir = new TextBox
{ {
Left = 20, Top = 172, Width = 250, Left = 20, Top = 262, Width = 250,
Text = _settings.SharedDirectory Text = _settings.SharedDirectory
}; };
_btnBrowseShared = new Button _btnBrowseShared = new Button
{ {
Text = "...", Left = 274, Top = 171, Width = 36, Height = 24 Text = "...", Left = 274, Top = 261, Width = 36, Height = 24
}; };
_btnBrowseShared.Click += (s, e) => BrowseSharedDir(); _btnBrowseShared.Click += (s, e) => BrowseSharedDir();
@@ -83,26 +113,52 @@ namespace StarfaceOutlookSync.UI
{ {
Text = "Netzlaufwerk/UNC, das alle Arbeitsplaetze erreichen. Leer = keine\n" + Text = "Netzlaufwerk/UNC, das alle Arbeitsplaetze erreichen. Leer = keine\n" +
"clientuebergreifende Sperre (nur Schutz auf diesem PC).", "clientuebergreifende Sperre (nur Schutz auf diesem PC).",
Left = 20, Top = 198, Width = 330, Height = 32, Left = 20, Top = 288, Width = 330, Height = 32,
ForeColor = Color.Gray, Font = new Font("Segoe UI", 8) ForeColor = Color.Gray, Font = new Font("Segoe UI", 8)
}; };
// === Autostart ===
bool isAdmin = AutostartManager.IsAdmin();
var lblAutostart = new Label
{
Text = "Autostart (bei Windows-Anmeldung starten)",
Left = 12, Top = 332, AutoSize = true, Font = new Font("Segoe UI", 10, FontStyle.Bold)
};
_chkAutostartUser = new CheckBox
{
Text = "Nur fuer diesen Benutzer",
Left = 20, Top = 360, AutoSize = true,
Checked = AutostartManager.GetUserAutostart()
};
_chkAutostartAll = new CheckBox
{
Text = "Fuer alle Benutzer" + (isAdmin ? "" : " (nur mit Admin-Rechten aenderbar)"),
Left = 20, Top = 386, AutoSize = true,
Checked = AutostartManager.GetMachineAutostart(),
Enabled = isAdmin
};
_btnSave = new Button _btnSave = new Button
{ {
Text = "Speichern", Left = 95, Top = 240, Width = 85, Height = 28, Text = "Speichern", Left = 95, Top = 422, Width = 85, Height = 28,
DialogResult = DialogResult.None DialogResult = DialogResult.None
}; };
_btnSave.Click += (s, e) => Save(); _btnSave.Click += (s, e) => Save();
_btnCancel = new Button _btnCancel = new Button
{ {
Text = "Abbrechen", Left = 189, Top = 240, Width = 85, Height = 28, Text = "Abbrechen", Left = 189, Top = 422, Width = 85, Height = 28,
DialogResult = DialogResult.Cancel DialogResult = DialogResult.Cancel
}; };
Size = new Size(380, 330); Size = new Size(380, 512);
Controls.AddRange(new Control[] { _chkStartMinimized, _chkSyncOnStart, _chkAutoAcceptOutlook, lblHint, Controls.AddRange(new Control[] { _chkStartMinimized, _chkSyncOnStart, _chkAutoAcceptOutlook, lblHint,
lblShared, _txtSharedDir, _btnBrowseShared, lblSharedHint, _btnSave, _btnCancel }); _chkNotifGeneral, _chkNotifWarn, lblLogRetention, _numLogRetention,
lblShared, _txtSharedDir, _btnBrowseShared, lblSharedHint,
lblAutostart, _chkAutostartUser, _chkAutostartAll, _btnSave, _btnCancel });
AcceptButton = _btnSave; AcceptButton = _btnSave;
CancelButton = _btnCancel; CancelButton = _btnCancel;
} }
@@ -126,8 +182,25 @@ namespace StarfaceOutlookSync.UI
_settings.StartMinimized = _chkStartMinimized.Checked; _settings.StartMinimized = _chkStartMinimized.Checked;
_settings.SyncOnStart = _chkSyncOnStart.Checked; _settings.SyncOnStart = _chkSyncOnStart.Checked;
_settings.AutoAcceptOutlookPrompt = _chkAutoAcceptOutlook.Checked; _settings.AutoAcceptOutlookPrompt = _chkAutoAcceptOutlook.Checked;
_settings.NotificationsEnabled = _chkNotifGeneral.Checked;
_settings.NotifyWarningsErrors = _chkNotifWarn.Checked;
_settings.LogRetentionDays = (int)_numLogRetention.Value;
_settings.SharedDirectory = _txtSharedDir.Text.Trim(); _settings.SharedDirectory = _txtSharedDir.Text.Trim();
_settings.Save(); _settings.Save();
// Sofort anwenden, damit der Effekt direkt sichtbar ist.
Logger.PruneOlderThan(_settings.LogRetentionDays);
// Autostart (Registry). Pro Benutzer immer; alle Benutzer nur mit Admin.
AutostartManager.SetUserAutostart(_chkAutostartUser.Checked);
if (AutostartManager.IsAdmin())
{
if (!AutostartManager.SetMachineAutostart(_chkAutostartAll.Checked))
MessageBox.Show(this,
"Autostart fuer alle Benutzer konnte nicht geaendert werden (Rechte?).",
"Autostart", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
DialogResult = DialogResult.OK; DialogResult = DialogResult.OK;
Close(); Close();
} }
+36 -15
View File
@@ -11,6 +11,7 @@ namespace StarfaceOutlookSync.UI
{ {
private readonly SyncProfile _profile; private readonly SyncProfile _profile;
private readonly SyncEngine _engine = new SyncEngine(); private readonly SyncEngine _engine = new SyncEngine();
private readonly SyncCoordinator _coordinator = new SyncCoordinator();
private TextBox _txtLog; private TextBox _txtLog;
private ProgressBar _progressBar; private ProgressBar _progressBar;
private Button _btnClose, _btnStart; private Button _btnClose, _btnStart;
@@ -92,19 +93,46 @@ namespace StarfaceOutlookSync.UI
_progressBar.Style = ProgressBarStyle.Marquee; _progressBar.Style = ProgressBarStyle.Marquee;
_lblResult.Text = ""; _lblResult.Text = "";
_engine.OnProgress += AppendLog; // Engine-Aufruf inkl. Live-Log: laeuft im Hintergrund, damit das
// Fenster reagiert. Guard/Lock/Notizen/Protokoll uebernimmt der
try // Coordinator (gemeinsam mit dem Auto-/Tray-Sync).
Func<Task<SyncResult>> runEngine = async () =>
{ {
var result = await Task.Run(() => _engine.SyncProfileAsync(_profile)); _engine.OnProgress += AppendLog;
try { return await Task.Run(() => _engine.SyncProfileAsync(_profile)); }
finally { _engine.OnProgress -= AppendLog; }
};
_progressBar.Style = ProgressBarStyle.Blocks; var outcome = await _coordinator.RunAsync(_profile, runEngine, status: AppendLog);
_progressBar.Value = 100;
var resultText = $"Erstellt: {result.Created} | Aktualisiert: {result.Updated} | Fehler: {result.Errors}"; _progressBar.Style = ProgressBarStyle.Blocks;
_lblResult.Text = resultText; _progressBar.Value = 100;
if (outcome.Skipped)
{
_lblResult.Text = outcome.SkipReason;
_lblResult.ForeColor = Color.OrangeRed;
AppendLog(outcome.SkipReason);
}
else if (outcome.Error != null)
{
_lblResult.Text = $"Fehler: {outcome.Error.Message}";
_lblResult.ForeColor = Color.Red;
AppendLog($"FEHLER: {outcome.Error.Message}");
}
else
{
var result = outcome.Result;
_lblResult.Text = $"Erstellt: {result.Created} | Aktualisiert: {result.Updated} | Fehler: {result.Errors}";
_lblResult.ForeColor = result.Errors > 0 ? Color.OrangeRed : Color.Green; _lblResult.ForeColor = result.Errors > 0 ? Color.OrangeRed : Color.Green;
// Konflikt-Hinweise anderer Arbeitsplaetze im Fenster zeigen.
foreach (var n in outcome.RemoteNotices)
AppendLog($"Konflikt an anderem Arbeitsplatz: {n}");
foreach (var c in result.Conflicts)
AppendLog($"KONFLIKT: {c}");
if (result.ErrorMessages.Count > 0) if (result.ErrorMessages.Count > 0)
{ {
AppendLog("--- Fehler ---"); AppendLog("--- Fehler ---");
@@ -112,14 +140,7 @@ namespace StarfaceOutlookSync.UI
AppendLog(err); AppendLog(err);
} }
} }
catch (Exception ex)
{
_lblResult.Text = $"Fehler: {ex.Message}";
_lblResult.ForeColor = Color.Red;
AppendLog($"FEHLER: {ex.Message}");
}
_engine.OnProgress -= AppendLog;
_btnStart.Enabled = true; _btnStart.Enabled = true;
_btnStart.Text = "Erneut synchronisieren"; _btnStart.Text = "Erneut synchronisieren";
_btnClose.Enabled = true; _btnClose.Enabled = true;