Rewrite as standalone C# WinForms app

Replace the Office Web Add-in with a native Windows application.
The web add-in required Exchange/M365 for registration which is
not available in all customer environments (standalone Office,
POP/IMAP only).

The new app:
- Uses COM Interop to access Outlook contacts directly
- Communicates with Starface REST API (accepts self-signed certs)
- Runs as System Tray app with optional auto-sync
- Profile-based config stored in %AppData%
- No webserver, no certificates, no Exchange, no M365 needed
- Inno Setup installer for clean MSI-style deployment
- Works with any Outlook version (Classic and New)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-03 10:26:58 +02:00
parent 8d7ae01ac3
commit 84ba78a1c5
51 changed files with 2205 additions and 10109 deletions
@@ -0,0 +1,317 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using StarfaceOutlookSync.Models;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace StarfaceOutlookSync.Services
{
public class OutlookContactsService : IDisposable
{
private Outlook.Application _outlookApp;
private bool _weStartedOutlook;
private Outlook.Application GetOutlookApp()
{
if (_outlookApp != null) return _outlookApp;
try
{
// Versuche laufende Outlook-Instanz zu finden
_outlookApp = (Outlook.Application)Marshal.GetActiveObject("Outlook.Application");
_weStartedOutlook = false;
}
catch
{
// Outlook starten falls nicht laufend
_outlookApp = new Outlook.Application();
_weStartedOutlook = true;
}
return _outlookApp;
}
public List<string> GetContactFolderPaths()
{
var folders = new List<string>();
try
{
var app = GetOutlookApp();
var ns = app.GetNamespace("MAPI");
// Standard-Kontaktordner
var defaultFolder = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
folders.Add(defaultFolder.FolderPath);
// Unterordner
AddSubFolders(defaultFolder, folders);
// Weitere Kontaktordner in anderen Stores
foreach (Outlook.Store store in ns.Stores)
{
try
{
var rootFolder = store.GetRootFolder();
FindContactFolders(rootFolder, folders);
}
catch { }
}
Marshal.ReleaseComObject(ns);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error getting folders: {ex.Message}");
}
return folders;
}
private void AddSubFolders(Outlook.MAPIFolder folder, List<string> paths)
{
foreach (Outlook.MAPIFolder sub in folder.Folders)
{
if (sub.DefaultItemType == Outlook.OlItemType.olContactItem)
{
if (!paths.Contains(sub.FolderPath))
paths.Add(sub.FolderPath);
AddSubFolders(sub, paths);
}
}
}
private void FindContactFolders(Outlook.MAPIFolder folder, List<string> paths)
{
if (folder.DefaultItemType == Outlook.OlItemType.olContactItem)
{
if (!paths.Contains(folder.FolderPath))
paths.Add(folder.FolderPath);
}
foreach (Outlook.MAPIFolder sub in folder.Folders)
{
FindContactFolders(sub, paths);
}
}
private Outlook.MAPIFolder GetFolderByPath(string folderPath)
{
var app = GetOutlookApp();
var ns = app.GetNamespace("MAPI");
// Standard-Kontaktordner als Fallback
if (string.IsNullOrEmpty(folderPath))
return ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
try
{
// Pfad durchlaufen
var parts = folderPath.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
Outlook.MAPIFolder current = null;
foreach (Outlook.Store store in ns.Stores)
{
if (store.GetRootFolder().Name == parts[0] ||
store.GetRootFolder().FolderPath.TrimStart('\\') == parts[0])
{
current = store.GetRootFolder();
break;
}
}
if (current == null)
return ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
for (int i = 1; i < parts.Length; i++)
{
bool found = false;
foreach (Outlook.MAPIFolder sub in current.Folders)
{
if (sub.Name == parts[i])
{
current = sub;
found = true;
break;
}
}
if (!found)
return ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
}
return current;
}
catch
{
return ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
}
}
public List<UnifiedContact> GetContacts(string folderPath)
{
var contacts = new List<UnifiedContact>();
try
{
var folder = GetFolderByPath(folderPath);
var items = folder.Items;
foreach (var item in items)
{
if (item is Outlook.ContactItem ci)
{
contacts.Add(MapFromOutlook(ci));
Marshal.ReleaseComObject(ci);
}
}
Marshal.ReleaseComObject(items);
Marshal.ReleaseComObject(folder);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error reading contacts: {ex.Message}");
}
return contacts;
}
public UnifiedContact CreateContact(UnifiedContact contact, string folderPath)
{
try
{
var folder = GetFolderByPath(folderPath);
var ci = (Outlook.ContactItem)folder.Items.Add(Outlook.OlItemType.olContactItem);
MapToOutlook(contact, ci);
ci.Save();
contact.OutlookEntryId = ci.EntryID;
Marshal.ReleaseComObject(ci);
Marshal.ReleaseComObject(folder);
return contact;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error creating contact: {ex.Message}");
return null;
}
}
public bool UpdateContact(string entryId, UnifiedContact contact)
{
try
{
var app = GetOutlookApp();
var ns = app.GetNamespace("MAPI");
var ci = (Outlook.ContactItem)ns.GetItemFromID(entryId);
MapToOutlook(contact, ci);
ci.Save();
Marshal.ReleaseComObject(ci);
Marshal.ReleaseComObject(ns);
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error updating contact: {ex.Message}");
return false;
}
}
public bool DeleteContact(string entryId)
{
try
{
var app = GetOutlookApp();
var ns = app.GetNamespace("MAPI");
var ci = (Outlook.ContactItem)ns.GetItemFromID(entryId);
ci.Delete();
Marshal.ReleaseComObject(ci);
Marshal.ReleaseComObject(ns);
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Error deleting contact: {ex.Message}");
return false;
}
}
private UnifiedContact MapFromOutlook(Outlook.ContactItem ci)
{
return new UnifiedContact
{
OutlookEntryId = ci.EntryID ?? "",
FirstName = ci.FirstName ?? "",
LastName = ci.LastName ?? "",
Company = ci.CompanyName ?? "",
JobTitle = ci.JobTitle ?? "",
Email = ci.Email1Address ?? "",
EmailSecondary = ci.Email2Address ?? "",
PhoneWork = ci.BusinessTelephoneNumber ?? "",
PhoneMobile = ci.MobileTelephoneNumber ?? "",
PhoneHome = ci.HomeTelephoneNumber ?? "",
Fax = ci.BusinessFaxNumber ?? "",
Street = ci.BusinessAddressStreet ?? "",
City = ci.BusinessAddressCity ?? "",
PostalCode = ci.BusinessAddressPostalCode ?? "",
State = ci.BusinessAddressState ?? "",
Country = ci.BusinessAddressCountry ?? "",
Website = ci.WebPage ?? "",
Notes = ci.Body ?? "",
Salutation = ci.Title ?? "",
Title = ci.Suffix ?? "",
Birthday = ci.Birthday != DateTime.MinValue && ci.Birthday.Year > 1900
? ci.Birthday.ToString("yyyy-MM-dd") : ""
};
}
private void MapToOutlook(UnifiedContact contact, Outlook.ContactItem ci)
{
ci.FirstName = contact.FirstName;
ci.LastName = contact.LastName;
ci.CompanyName = contact.Company;
ci.JobTitle = contact.JobTitle;
ci.Email1Address = contact.Email;
if (!string.IsNullOrEmpty(contact.EmailSecondary))
ci.Email2Address = contact.EmailSecondary;
ci.BusinessTelephoneNumber = contact.PhoneWork;
ci.MobileTelephoneNumber = contact.PhoneMobile;
ci.HomeTelephoneNumber = contact.PhoneHome;
ci.BusinessFaxNumber = contact.Fax;
ci.BusinessAddressStreet = contact.Street;
ci.BusinessAddressCity = contact.City;
ci.BusinessAddressPostalCode = contact.PostalCode;
ci.BusinessAddressState = contact.State;
ci.BusinessAddressCountry = contact.Country;
ci.WebPage = contact.Website;
ci.Body = contact.Notes;
ci.Title = contact.Salutation;
if (!string.IsNullOrEmpty(contact.Birthday) &&
DateTime.TryParse(contact.Birthday, out var bday) && bday.Year > 1900)
{
ci.Birthday = bday;
}
}
public void Dispose()
{
if (_outlookApp != null)
{
if (_weStartedOutlook)
{
try { _outlookApp.Quit(); } catch { }
}
Marshal.ReleaseComObject(_outlookApp);
_outlookApp = null;
}
}
}
}
@@ -0,0 +1,122 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using StarfaceOutlookSync.Models;
namespace StarfaceOutlookSync.Services
{
public class ProfileManager
{
private readonly string _dataDir;
private readonly string _profilesFile;
private readonly string _mappingsDir;
public ProfileManager()
{
_dataDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"StarfaceOutlookSync");
_mappingsDir = Path.Combine(_dataDir, "mappings");
_profilesFile = Path.Combine(_dataDir, "profiles.json");
Directory.CreateDirectory(_dataDir);
Directory.CreateDirectory(_mappingsDir);
}
public List<SyncProfile> GetProfiles()
{
try
{
if (!File.Exists(_profilesFile)) return new List<SyncProfile>();
var json = File.ReadAllText(_profilesFile);
return JsonConvert.DeserializeObject<List<SyncProfile>>(json) ?? new List<SyncProfile>();
}
catch { return new List<SyncProfile>(); }
}
public void SaveProfiles(List<SyncProfile> profiles)
{
var json = JsonConvert.SerializeObject(profiles, Formatting.Indented);
File.WriteAllText(_profilesFile, json);
}
public SyncProfile GetProfile(string id)
{
return GetProfiles().FirstOrDefault(p => p.Id == id);
}
public void AddProfile(SyncProfile profile)
{
var profiles = GetProfiles();
profiles.Add(profile);
SaveProfiles(profiles);
}
public void UpdateProfile(SyncProfile profile)
{
var profiles = GetProfiles();
var idx = profiles.FindIndex(p => p.Id == profile.Id);
if (idx >= 0)
{
profiles[idx] = profile;
SaveProfiles(profiles);
}
}
public void DeleteProfile(string id)
{
var profiles = GetProfiles().Where(p => p.Id != id).ToList();
SaveProfiles(profiles);
var mappingFile = Path.Combine(_mappingsDir, $"{id}.json");
if (File.Exists(mappingFile)) File.Delete(mappingFile);
}
public void UpdateLastSync(string profileId)
{
var profiles = GetProfiles();
var profile = profiles.FirstOrDefault(p => p.Id == profileId);
if (profile != null)
{
profile.LastSync = DateTime.Now.ToString("o");
SaveProfiles(profiles);
}
}
public List<SyncMapping> GetMappings(string profileId)
{
try
{
var file = Path.Combine(_mappingsDir, $"{profileId}.json");
if (!File.Exists(file)) return new List<SyncMapping>();
return JsonConvert.DeserializeObject<List<SyncMapping>>(File.ReadAllText(file))
?? new List<SyncMapping>();
}
catch { return new List<SyncMapping>(); }
}
public void SaveMappings(string profileId, List<SyncMapping> mappings)
{
var file = Path.Combine(_mappingsDir, $"{profileId}.json");
File.WriteAllText(file, JsonConvert.SerializeObject(mappings, Formatting.Indented));
}
public void AddOrUpdateMapping(SyncMapping mapping)
{
var mappings = GetMappings(mapping.ProfileId);
var existing = mappings.FindIndex(m =>
m.OutlookEntryId == mapping.OutlookEntryId || m.StarfaceId == mapping.StarfaceId);
if (existing >= 0)
mappings[existing] = mapping;
else
mappings.Add(mapping);
SaveMappings(mapping.ProfileId, mappings);
}
public string GenerateId()
{
return DateTime.Now.Ticks.ToString("x") + Guid.NewGuid().ToString("N").Substring(0, 8);
}
}
}
@@ -0,0 +1,326 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using StarfaceOutlookSync.Models;
namespace StarfaceOutlookSync.Services
{
public class StarfaceApiClient : IDisposable
{
private readonly HttpClient _http;
private readonly StarfaceConnection _connection;
private readonly string _baseUrl;
private string _token;
public StarfaceApiClient(StarfaceConnection connection)
{
_connection = connection;
var handler = new HttpClientHandler();
// Self-signed Zertifikate der Starface akzeptieren
handler.ServerCertificateCustomValidationCallback = (msg, cert, chain, errors) => true;
_http = new HttpClient(handler);
_http.DefaultRequestHeaders.Add("X-Version", "2");
_http.Timeout = TimeSpan.FromSeconds(30);
var protocol = connection.UseSsl ? "https" : "http";
var portPart = (connection.UseSsl && connection.Port == 443) ||
(!connection.UseSsl && connection.Port == 80)
? "" : $":{connection.Port}";
_baseUrl = $"{protocol}://{connection.Host}{portPart}/rest";
}
private static string Sha512(string input)
{
using (var sha = SHA512.Create())
{
var bytes = Encoding.UTF8.GetBytes(input);
var hash = sha.ComputeHash(bytes);
var sb = new StringBuilder(128);
foreach (var b in hash)
sb.Append(b.ToString("x2"));
return sb.ToString();
}
}
public async Task<bool> LoginAsync()
{
try
{
// Schritt 1: Nonce holen
var nonceResp = await _http.GetAsync($"{_baseUrl}/login");
if (!nonceResp.IsSuccessStatusCode) return false;
var nonceJson = JObject.Parse(await nonceResp.Content.ReadAsStringAsync());
var loginType = nonceJson["loginType"]?.ToString() ?? "Internal";
var nonce = nonceJson["nonce"]?.ToString() ?? "";
// Schritt 2: Secret berechnen
var passwordHash = Sha512(_connection.Password);
var combined = _connection.LoginId + nonce + passwordHash;
var combinedHash = Sha512(combined);
var secret = $"{_connection.LoginId}:{combinedHash}";
// Schritt 3: Login
var loginBody = new { loginType, nonce, secret };
var content = new StringContent(JsonConvert.SerializeObject(loginBody), Encoding.UTF8, "application/json");
var loginResp = await _http.PostAsync($"{_baseUrl}/login", content);
if (!loginResp.IsSuccessStatusCode) return false;
var tokenJson = JObject.Parse(await loginResp.Content.ReadAsStringAsync());
_token = tokenJson["token"]?.ToString();
if (!string.IsNullOrEmpty(_token))
{
_http.DefaultRequestHeaders.Remove("authToken");
_http.DefaultRequestHeaders.Add("authToken", _token);
}
return !string.IsNullOrEmpty(_token);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"Starface login failed: {ex.Message}");
return false;
}
}
public async Task LogoutAsync()
{
if (string.IsNullOrEmpty(_token)) return;
try { await _http.DeleteAsync($"{_baseUrl}/login"); } catch { }
_token = null;
}
public async Task<string> GetCurrentUserIdAsync()
{
try
{
var resp = await _http.GetAsync($"{_baseUrl}/users/me");
if (!resp.IsSuccessStatusCode) return null;
var json = JObject.Parse(await resp.Content.ReadAsStringAsync());
return json["id"]?.ToString();
}
catch { return null; }
}
public async Task<List<StarfaceAddressBook>> GetAddressBooksAsync()
{
var books = new List<StarfaceAddressBook>();
books.Add(new StarfaceAddressBook
{
Type = "central",
Name = "Zentrales Adressbuch"
});
var userId = await GetCurrentUserIdAsync();
if (!string.IsNullOrEmpty(userId))
{
books.Add(new StarfaceAddressBook
{
Type = "user",
UserId = userId,
Name = "Persoenliches Adressbuch"
});
}
// Tags als virtuelle Adressbuecher
try
{
var resp = await _http.GetAsync($"{_baseUrl}/contacts/tags");
if (resp.IsSuccessStatusCode)
{
var tags = JArray.Parse(await resp.Content.ReadAsStringAsync());
foreach (var tag in tags)
{
books.Add(new StarfaceAddressBook
{
Type = "tag",
TagId = tag["id"]?.ToString() ?? "",
Name = $"Tag: {tag["name"]}"
});
}
}
}
catch { }
return books;
}
public async Task<List<UnifiedContact>> GetContactsAsync(StarfaceAddressBook book)
{
var contacts = new List<UnifiedContact>();
int page = 0;
const int pageSize = 200;
while (true)
{
var query = $"page={page}&pagesize={pageSize}";
if (book.Type == "user" && !string.IsNullOrEmpty(book.UserId))
query += $"&userId={book.UserId}";
if (book.Type == "tag" && !string.IsNullOrEmpty(book.TagId))
query += $"&tags={book.TagId}";
var resp = await _http.GetAsync($"{_baseUrl}/contacts?{query}");
if (!resp.IsSuccessStatusCode) break;
var array = JArray.Parse(await resp.Content.ReadAsStringAsync());
if (array.Count == 0) break;
foreach (var item in array)
contacts.Add(MapFromStarface(item));
if (array.Count < pageSize) break;
page++;
}
return contacts;
}
public async Task<UnifiedContact> CreateContactAsync(UnifiedContact contact, StarfaceAddressBook book)
{
var sfContact = MapToStarface(contact);
var query = "";
if (book.Type == "user" && !string.IsNullOrEmpty(book.UserId))
query = $"?userId={book.UserId}";
var content = new StringContent(sfContact.ToString(), Encoding.UTF8, "application/json");
var resp = await _http.PostAsync($"{_baseUrl}/contacts{query}", content);
if (!resp.IsSuccessStatusCode) return null;
var created = JObject.Parse(await resp.Content.ReadAsStringAsync());
return MapFromStarface(created);
}
public async Task<bool> UpdateContactAsync(string contactId, UnifiedContact contact, StarfaceAddressBook book)
{
var sfContact = MapToStarface(contact);
sfContact["id"] = contactId;
var query = "";
if (book.Type == "user" && !string.IsNullOrEmpty(book.UserId))
query = $"?userId={book.UserId}";
var content = new StringContent(sfContact.ToString(), Encoding.UTF8, "application/json");
var resp = await _http.PutAsync($"{_baseUrl}/contacts/{contactId}{query}", content);
return resp.IsSuccessStatusCode;
}
public async Task<bool> DeleteContactAsync(string contactId)
{
var resp = await _http.DeleteAsync($"{_baseUrl}/contacts/{contactId}");
return resp.IsSuccessStatusCode;
}
private UnifiedContact MapFromStarface(JToken item)
{
var contact = new UnifiedContact();
contact.StarfaceId = item["id"]?.ToString() ?? "";
var attrs = new Dictionary<string, string>();
var blocks = item["blocks"] as JArray;
if (blocks != null)
{
foreach (var block in blocks)
{
var blockAttrs = block["attributes"] as JArray;
if (blockAttrs == null) continue;
foreach (var attr in blockAttrs)
{
var key = attr["displayKey"]?.ToString() ?? "";
var val = attr["value"]?.ToString() ?? "";
if (!string.IsNullOrEmpty(val))
attrs[key] = val;
}
}
}
contact.FirstName = attrs.GetValueOrDefault("NAME", "");
contact.LastName = attrs.GetValueOrDefault("SURNAME", "");
contact.Company = attrs.GetValueOrDefault("COMPANY", "");
contact.JobTitle = attrs.GetValueOrDefault("JOB_TITLE", "");
contact.Email = attrs.GetValueOrDefault("EMAIL", "");
contact.PhoneWork = attrs.GetValueOrDefault("OFFICE_PHONE_NUMBER", "");
contact.PhoneMobile = attrs.GetValueOrDefault("MOBILE_PHONE_NUMBER", "");
contact.PhoneHome = attrs.GetValueOrDefault("PRIVATE_PHONE_NUMBER", "");
contact.Fax = attrs.GetValueOrDefault("FAX_NUMBER", "");
contact.Street = attrs.GetValueOrDefault("STREET", "");
contact.City = attrs.GetValueOrDefault("CITY", "");
contact.PostalCode = attrs.GetValueOrDefault("POSTAL_CODE", "");
contact.State = attrs.GetValueOrDefault("STATE", "");
contact.Country = attrs.GetValueOrDefault("COUNTRY", "");
contact.Website = attrs.GetValueOrDefault("URL", "");
contact.Notes = attrs.GetValueOrDefault("NOTE", "");
contact.Salutation = attrs.GetValueOrDefault("SALUTATION", "");
contact.Title = attrs.GetValueOrDefault("TITLE", "");
contact.Birthday = attrs.GetValueOrDefault("BIRTHDAY", "");
return contact;
}
private JObject MapToStarface(UnifiedContact contact)
{
var attrs = new JArray();
void AddAttr(string displayKey, string name, string value)
{
if (!string.IsNullOrEmpty(value))
attrs.Add(new JObject { ["displayKey"] = displayKey, ["name"] = name, ["value"] = value });
}
AddAttr("NAME", "firstName", contact.FirstName);
AddAttr("SURNAME", "lastName", contact.LastName);
AddAttr("COMPANY", "company", contact.Company);
AddAttr("JOB_TITLE", "jobTitle", contact.JobTitle);
AddAttr("EMAIL", "email", contact.Email);
AddAttr("OFFICE_PHONE_NUMBER", "businessPhone", contact.PhoneWork);
AddAttr("MOBILE_PHONE_NUMBER", "mobilePhone", contact.PhoneMobile);
AddAttr("PRIVATE_PHONE_NUMBER", "homePhone", contact.PhoneHome);
AddAttr("FAX_NUMBER", "fax", contact.Fax);
AddAttr("STREET", "street", contact.Street);
AddAttr("CITY", "city", contact.City);
AddAttr("POSTAL_CODE", "postalCode", contact.PostalCode);
AddAttr("STATE", "state", contact.State);
AddAttr("COUNTRY", "country", contact.Country);
AddAttr("URL", "website", contact.Website);
AddAttr("NOTE", "notes", contact.Notes);
AddAttr("SALUTATION", "salutation", contact.Salutation);
AddAttr("TITLE", "title", contact.Title);
AddAttr("BIRTHDAY", "birthday", contact.Birthday);
return new JObject
{
["id"] = contact.StarfaceId ?? "",
["blocks"] = new JArray
{
new JObject
{
["name"] = "contact",
["resourceKey"] = "contact",
["attributes"] = attrs
}
}
};
}
public void Dispose()
{
_http?.Dispose();
}
}
internal static class DictionaryExtensions
{
public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key, TValue defaultValue)
{
return dict.TryGetValue(key, out var value) ? value : defaultValue;
}
}
}
@@ -0,0 +1,226 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using StarfaceOutlookSync.Models;
namespace StarfaceOutlookSync.Services
{
public class SyncEngine
{
private readonly ProfileManager _profileManager = new ProfileManager();
private readonly OutlookContactsService _outlookService = new OutlookContactsService();
public event Action<string> OnProgress;
private void Log(string message) => OnProgress?.Invoke(message);
private static UnifiedContact FindMatch(UnifiedContact contact, List<UnifiedContact> candidates)
{
// Erst E-Mail-Match
if (!string.IsNullOrEmpty(contact.Email))
{
var byEmail = candidates.FirstOrDefault(c =>
!string.IsNullOrEmpty(c.Email) &&
c.Email.Equals(contact.Email, StringComparison.OrdinalIgnoreCase));
if (byEmail != null) return byEmail;
}
// Dann Name-Match
if (!string.IsNullOrEmpty(contact.FirstName) || !string.IsNullOrEmpty(contact.LastName))
{
var byName = candidates.FirstOrDefault(c =>
c.FirstName.Equals(contact.FirstName, StringComparison.OrdinalIgnoreCase) &&
c.LastName.Equals(contact.LastName, StringComparison.OrdinalIgnoreCase) &&
(!string.IsNullOrEmpty(c.FirstName) || !string.IsNullOrEmpty(c.LastName)));
if (byName != null) return byName;
}
return null;
}
public async Task<SyncResult> SyncProfileAsync(SyncProfile profile)
{
var result = new SyncResult
{
ProfileName = profile.Name,
Timestamp = DateTime.Now.ToString("o")
};
try
{
// Starface verbinden
Log("Verbinde mit Starface...");
using (var starface = new StarfaceApiClient(profile.StarfaceConnection))
{
var loginOk = await starface.LoginAsync();
if (!loginOk)
{
result.ErrorMessages.Add("Starface-Login fehlgeschlagen");
result.Errors++;
return result;
}
var mappings = _profileManager.GetMappings(profile.Id);
var mappingByOutlook = mappings.ToDictionary(m => m.OutlookEntryId, m => m);
var mappingByStarface = mappings.ToDictionary(m => m.StarfaceId, m => m);
// Kontakte laden
Log("Lade Outlook-Kontakte...");
var outlookContacts = _outlookService.GetContacts(profile.OutlookFolderPath);
Log($"{outlookContacts.Count} Outlook-Kontakte geladen");
Log("Lade Starface-Kontakte...");
var starfaceContacts = await starface.GetContactsAsync(profile.StarfaceAddressBook);
Log($"{starfaceContacts.Count} Starface-Kontakte geladen");
// Outlook -> Starface
if (profile.SyncDirection == SyncDirection.Both ||
profile.SyncDirection == SyncDirection.OutlookToStarface)
{
Log("Synchronisiere Outlook -> Starface...");
foreach (var oc in outlookContacts)
{
try
{
SyncMapping existing = null;
if (!string.IsNullOrEmpty(oc.OutlookEntryId))
mappingByOutlook.TryGetValue(oc.OutlookEntryId, out existing);
if (existing != null)
{
var hash = oc.GetHash();
if (hash != existing.LastSyncHash)
{
if (await starface.UpdateContactAsync(existing.StarfaceId, oc, profile.StarfaceAddressBook))
{
existing.LastSyncHash = hash;
result.Updated++;
}
}
}
else
{
var match = FindMatch(oc, starfaceContacts);
if (match != null && !string.IsNullOrEmpty(match.StarfaceId))
{
if (await starface.UpdateContactAsync(match.StarfaceId, oc, profile.StarfaceAddressBook))
{
_profileManager.AddOrUpdateMapping(new SyncMapping
{
ProfileId = profile.Id,
OutlookEntryId = oc.OutlookEntryId,
StarfaceId = match.StarfaceId,
LastSyncHash = oc.GetHash()
});
result.Updated++;
}
}
else
{
var created = await starface.CreateContactAsync(oc, profile.StarfaceAddressBook);
if (created != null && !string.IsNullOrEmpty(created.StarfaceId))
{
_profileManager.AddOrUpdateMapping(new SyncMapping
{
ProfileId = profile.Id,
OutlookEntryId = oc.OutlookEntryId,
StarfaceId = created.StarfaceId,
LastSyncHash = oc.GetHash()
});
result.Created++;
}
}
}
}
catch (Exception ex)
{
result.Errors++;
result.ErrorMessages.Add($"{oc.DisplayName}: {ex.Message}");
}
}
}
// Starface -> Outlook
if (profile.SyncDirection == SyncDirection.Both ||
profile.SyncDirection == SyncDirection.StarfaceToOutlook)
{
Log("Synchronisiere Starface -> Outlook...");
foreach (var sc in starfaceContacts)
{
try
{
SyncMapping existing = null;
if (!string.IsNullOrEmpty(sc.StarfaceId))
mappingByStarface.TryGetValue(sc.StarfaceId, out existing);
if (existing != null)
{
var hash = sc.GetHash();
if (hash != existing.LastSyncHash)
{
if (_outlookService.UpdateContact(existing.OutlookEntryId, sc))
{
existing.LastSyncHash = hash;
result.Updated++;
}
}
}
else
{
var match = FindMatch(sc, outlookContacts);
if (match != null && !string.IsNullOrEmpty(match.OutlookEntryId))
{
if (_outlookService.UpdateContact(match.OutlookEntryId, sc))
{
_profileManager.AddOrUpdateMapping(new SyncMapping
{
ProfileId = profile.Id,
OutlookEntryId = match.OutlookEntryId,
StarfaceId = sc.StarfaceId,
LastSyncHash = sc.GetHash()
});
result.Updated++;
}
}
else
{
var created = _outlookService.CreateContact(sc, profile.OutlookFolderPath);
if (created != null && !string.IsNullOrEmpty(created.OutlookEntryId))
{
_profileManager.AddOrUpdateMapping(new SyncMapping
{
ProfileId = profile.Id,
OutlookEntryId = created.OutlookEntryId,
StarfaceId = sc.StarfaceId,
LastSyncHash = sc.GetHash()
});
result.Created++;
}
}
}
}
catch (Exception ex)
{
result.Errors++;
result.ErrorMessages.Add($"{sc.DisplayName}: {ex.Message}");
}
}
}
_profileManager.UpdateLastSync(profile.Id);
_profileManager.SaveMappings(profile.Id, mappings);
await starface.LogoutAsync();
Log("Synchronisation abgeschlossen!");
}
}
catch (Exception ex)
{
result.Errors++;
result.ErrorMessages.Add($"Allgemeiner Fehler: {ex.Message}");
}
return result;
}
}
}