using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Reflection; using System.Threading.Tasks; using System.Windows; using System.Windows.Media; using C4IT.API; using C4IT.API.Contracts; using C4IT.Logging; using C4IT.Matrix42.WebClient; using C4IT.Configuration; using Microsoft.Win32; using Newtonsoft.Json; using static C4IT.Logging.cLogManager; namespace C4IT_CustomerPanel.libs { public enum enumAlternateAuthMethods { none, authCredentials, authToken, authForms } public class ConfigClass { /* * Kommentar: * Variablen Definition * local_ = Konfigurationswerte zum Start und zur Kommunikation mit Server (HKEY_LOCAL_MACHINE) * usr_ = Durch den Benutzer konfigurierbare Einstellungen * rnt_ = Variablen nur während der Laufzeit des Anwendung * */ public enum enumPresentationMode { OS = 0, Off = 1, On = 2 }; private const string hKeyAppPath = @"SOFTWARE\Consulting4IT GmbH\Customer Panel"; private const string hKeyUserPath = hKeyAppPath + @"\user"; private const string hKeyConfigPath = hKeyAppPath + @"\config"; private const string hKeyAuthPath = hKeyAppPath + @"\authentication"; private const string hKeyDefaultUserSettingsPath = hKeyAppPath + @"\DefaultUserSettings"; private const string registryHKCUPath = @"HKEY_CURRENT_USER\"+ hKeyAppPath + @"\user"; private const string registryUserInformationValueName = "userInformation"; private const int minTicketTimerValue = 2; private const int minRegularAnnouncementTimerValue = 2; private const int minAdHocAnnouncementTimerValue = 1; public enum enumMainFunctions { Announcement = 0, Information, Ssp, Incident, CustomLinks }; public Dictionary MainFunctionActivation = new Dictionary() { {enumMainFunctions.Announcement, false }, {enumMainFunctions.Incident, false }, {enumMainFunctions.Ssp, false }, {enumMainFunctions.Information, true }, {enumMainFunctions.CustomLinks, false } }; public Dictionary MainFunctionM42Column = new Dictionary() { {enumMainFunctions.Announcement, "announcementEnabled" }, {enumMainFunctions.Incident, "incidentEnabled" }, {enumMainFunctions.Information, "informationEnabled" }, {enumMainFunctions.Ssp, "sspEnabled" }, {enumMainFunctions.CustomLinks, "customlinksEnabled" } }; public static Dictionary JournalActivityAction = new Dictionary() { {0, new journalAction(Properties.Resources.ticketNewComment) }, {1,new journalAction(Properties.Resources.ticketCreatedByAgent) }, {2, new journalAction(Properties.Resources.ticketForwardedToUser) }, {3,new journalAction(Properties.Resources.ticketForwardedToRole)}, {4,new journalAction(Properties.Resources.ticketTakeover)}, {5,new journalAction(Properties.Resources.ticketPaused) }, {7,new journalAction(Properties.Resources.ticketAccepted) }, {8,new journalAction(Properties.Resources.ticketClosed) }, {9,new journalAction(Properties.Resources.ticketMerged) }, {11,new journalAction(Properties.Resources.ticketMailSend) }, {12,new journalAction(Properties.Resources.ticketPostedback) }, {14,new journalAction(Properties.Resources.ticketMailAnswer) }, {18,new journalAction(Properties.Resources.ticketCreatedByMail) }, {19,new journalAction(Properties.Resources.ticketCreatedBySSP) } }; const string LocalDataPath = @"Consulting4IT GmbH\C4IT Customer Panel"; private const string ApiConfigBaseUrl = "https://{0}/m42Services/api/c4it/customerpanel/config?noCache={1}"; public int local_currentDPI = 96; int rnt_tryCounter; public String local_MatrixServer = String.Empty; public bool ShowIpInfoOnlyInCorporateNetwork = false; public String CustomerPanelTitle = String.Empty; public String CustomAnnouncementText = String.Empty; public int AnnouncementView; private int usr_userLanguage = 9; public string rnt_userInfoFromLogin; bool _isInternalTesting = false; string rnt_LogoUrlPrev = null; string rnt_TrayIconUrlPrev = null; //Aktive Buttons oder Mosueover public Point usr_windowPosition; private bool usr_enableNotifier; public CustomerPanelConfig cpConfig; internal UserInfo userInfo = new UserInfo(); public cM42WebClientV2 m42WebClient; internal bool usingGeneralAPIToken = false; private enumPresentationMode usr_PresentationMode = enumPresentationMode.OS; public bool isDraggable = true; public CustomerPanelConfig GetConfig() { return cpConfig; } public bool EnableNotifier { get => usr_enableNotifier; set { if (usr_enableNotifier != value) { usr_enableNotifier = value; WriteUserSetup(); } } } private static string _localDataPath = null; static public string GetLocalDataPath() { if (_localDataPath != null) return _localDataPath; var ass = Assembly.GetExecutingAssembly(); var Company = cLogManager.GetAssemblyCompanyName(ass); var ProductName = cLogManager.GetAssemblyProductName(ass); _localDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), Company, ProductName); return _localDataPath; } static public string GetLocalFilePath(string FileName, bool withoutAlternate) { var FN = Path.Combine(GetLocalDataPath(), FileName); if (!System.IO.File.Exists(FN) && !withoutAlternate) FN = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, FileName); return FN; } static public string GetLogoFilePath(bool withoutAlternate = false) { return GetLocalFilePath("logo.png", withoutAlternate); } static public string GetTrayIconFilePath(bool withoutAlternate = false) { return GetLocalFilePath("trayIcon.ico", withoutAlternate); } static public TEnum GetEnumFromString(string s, TEnum Default) where TEnum : System.Enum { try { if (!string.IsNullOrEmpty(s)) { var s2 = s.ToUpperInvariant(); var R3 = Enum.GetValues(Default.GetType()); var R4 = R3.OfType(); foreach (TEnum Entry in R4) { if (Entry.ToString().ToUpperInvariant() == s2) return Entry; } } } catch (Exception E) { LogException(E); throw; } finally { } return Default; } public Dictionary GetLinkList() { return cpConfig._linkList; } public Color GetButtonHoverColor(Color? baseColor = null, double contrastMultiplier = 1.0) { Color activeColor = baseColor ?? GetActiveButtonColor().Color; bool isLightActive = GetRelativeLuminance(activeColor) >= 0.55; double baseAmount = isLightActive ? 0.10 : 0.12; double blendAmount = Math.Max(0.0, Math.Min(0.35, baseAmount * contrastMultiplier)); return BlendColor(activeColor, isLightActive ? Colors.Black : Colors.White, blendAmount); } public SolidColorBrush GetActiveButtonColor() { return (SolidColorBrush)System.Windows.Application.Current.Resources["activeButtonColor"]; } public SolidColorBrush GetInactiveButtonColor() { return (SolidColorBrush)System.Windows.Application.Current.Resources["inactiveButtonColor"]; } public SolidColorBrush GetBackgroundColor() { return (SolidColorBrush)System.Windows.Application.Current.Resources["backgroundColor"]; } private static Color BlendColor(Color source, Color target, double amount) { amount = Math.Max(0.0, Math.Min(1.0, amount)); return Color.FromArgb( source.A, (byte)Math.Round((source.R * (1.0 - amount)) + (target.R * amount)), (byte)Math.Round((source.G * (1.0 - amount)) + (target.G * amount)), (byte)Math.Round((source.B * (1.0 - amount)) + (target.B * amount))); } private static double GetRelativeLuminance(Color color) { return ((0.2126 * color.R) + (0.7152 * color.G) + (0.0722 * color.B)) / 255.0; } private static bool TryGetConfiguredUiColor(Dictionary uiColors, string key, out Color color) { color = Colors.Transparent; if (uiColors == null || !uiColors.TryGetValue(key, out string rawColor) || string.IsNullOrWhiteSpace(rawColor)) return false; try { color = ConverterHelper.ColorConvertFromString(rawColor); return true; } catch { return false; } } private static void ApplyBackgroundDerivedResources(Color baseColor) { bool isLightBackground = GetRelativeLuminance(baseColor) >= 0.55; Color panelColor = BlendColor(baseColor, Colors.White, isLightBackground ? 0.06 : 0.08); Color navColor = BlendColor(baseColor, Colors.Black, isLightBackground ? 0.06 : 0.08); Color activeColor = BlendColor(baseColor, isLightBackground ? Colors.Black : Colors.White, isLightBackground ? 0.30 : 0.34); Color inactiveColor = BlendColor(baseColor, isLightBackground ? Colors.White : Colors.Black, isLightBackground ? 0.18 : 0.14); Color panelBorder = BlendColor(baseColor, isLightBackground ? Colors.Black : Colors.White, isLightBackground ? 0.16 : 0.22); Color navBorder = BlendColor(baseColor, isLightBackground ? Colors.Black : Colors.White, isLightBackground ? 0.20 : 0.28); Application.Current.Resources["backgroundColor"] = new SolidColorBrush(baseColor); Application.Current.Resources["activeButtonColor"] = new SolidColorBrush(activeColor); Application.Current.Resources["inactiveButtonColor"] = new SolidColorBrush(inactiveColor); Application.Current.Resources["panelBackgroundColor"] = new SolidColorBrush(panelColor); Application.Current.Resources["navigationRailColor"] = new SolidColorBrush(navColor); Application.Current.Resources["panelBorderColor"] = new SolidColorBrush(panelBorder); Application.Current.Resources["navigationRailBorderColor"] = new SolidColorBrush(navBorder); } private static void ApplyHeaderDerivedResources(Color headerColor) { bool isLightHeader = GetRelativeLuminance(headerColor) >= 0.55; Color controlBase = BlendColor(headerColor, isLightHeader ? Colors.Black : Colors.White, isLightHeader ? 0.14 : 0.18); Color controlHover = BlendColor(headerColor, isLightHeader ? Colors.Black : Colors.White, isLightHeader ? 0.22 : 0.26); Application.Current.Resources["headerControlBackgroundColor"] = new SolidColorBrush(controlBase); Application.Current.Resources["headerControlHoverBackgroundColor"] = new SolidColorBrush(controlHover); } public SolidColorBrush GetHeaderColor() { return (SolidColorBrush)System.Windows.Application.Current.Resources["headerColor"]; } public string GetNavIconColor() { if (cpConfig._iconColor == 10) { return "light"; } else if (cpConfig._iconColor == 20) { return "dark"; } return "dark"; } public int GetNavIconColorValue() { return cpConfig._iconColor; } public string GetMainIconColor() { if (cpConfig._mainIconTextColor == 10) { return "light"; } else if (cpConfig._mainIconTextColor == 20) { return "dark"; } return "dark"; } public bool IsPresentationModeFromOS() { return usr_PresentationMode == enumPresentationMode.OS; } public bool GetPresentationMode() { switch (usr_PresentationMode) { case enumPresentationMode.On: return true; case enumPresentationMode.Off: return false; default: return InformationHelper.IsOsInPresentationMode(); } } public void SetPresentationMode(enumPresentationMode PresentationMode) { usr_PresentationMode = PresentationMode; WriteUserSetup(); } public void SetWindowPos() { WriteUserSetup(true); } public string GetRemoteAppPath() { return cpConfig._remoteAppPath; } public bool GetStartMinimized() { return cpConfig._isStartApplicationMinimized; } public int GetTimerIntervalTicket() { if (cpConfig._timerIntervalTicket < minTicketTimerValue && !_isInternalTesting) { return minTicketTimerValue; } else { return cpConfig._timerIntervalTicket; } } public int GetTimerIntervalRegular() { if (cpConfig._timerIntervalRegularAnnouncements < minRegularAnnouncementTimerValue && !_isInternalTesting) { return minRegularAnnouncementTimerValue; } else { return cpConfig._timerIntervalRegularAnnouncements; } } public int GetTimerIntervalAdHoc() { if (cpConfig._timerIntervalAdHocAnnouncements < minAdHocAnnouncementTimerValue && !_isInternalTesting) { return minAdHocAnnouncementTimerValue; } else { return cpConfig._timerIntervalAdHocAnnouncements; } } public string GetMatrixServer(bool withHttps) { string Res = string.Empty; if (withHttps) Res = "https://"; Res += local_MatrixServer; return Res; } public void SetUserLanguage(int language) { usr_userLanguage = language; WriteUserSetup(); } public int GetUserLanguage() { if (usr_userLanguage != 0) return usr_userLanguage; return CultureInfo.CurrentUICulture.LCID; } public bool IsUserLanguageOsDefault() { return usr_userLanguage == 0; } public string GetCultureName() { try { int ul = GetUserLanguage(); // Beispiel: 1031, 1033, etc. CultureInfo culture = new CultureInfo(ul); return culture.TwoLetterISOLanguageName; } catch (CultureNotFoundException) { // LCID ist ungültig oder nicht unterstützt return "en"; } catch (Exception) { // Allgemeiner Fallback bei unerwarteten Fehlern return "en"; } } public ConfigClass() { } public void Initialize() { MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); } try { cpConfig = new CustomerPanelConfig(); ReadUserSetup(); ReadMachineSetup(fromUser: true); ReadMachineSetup(fromUser: false); } catch (Exception E) { LogException(E); } finally { if (CM != null) LogMethodEnd(CM); } } private void RegisterMsGateway() { MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); } try { var cfgV2 = ConfigClassV2.Instance; var msParams = new cM42MsGatewayAuthenticationParamters { Server = GetMatrixServer(false), ApplcationId = cfgV2.MsGateway_ApplicationId, TenantId = cfgV2.MsGateway_TenantId, Scope = cfgV2.MsGateway_Scope, InteractiveLogon = false }; var _auth = new cM42MsGatewayAuthentication(); _auth.Initialize(msParams); m42WebClient.RegisterAuthorisationProvider(_auth); } catch (Exception E) { LogException(E); } finally { if (CM != null) LogMethodEnd(CM); } } public async Task CreateM42ConnectionObject() { MethodBase CM = null; if (cLogManager.DefaultLogger.IsDebug) { CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); } try { m42WebClient = new cM42WebClientV2(GetMatrixServer(false), GetCultureName(), DisableDNSCache: true); var userInfosFromRegistry = ReadRegistryUserInfo(); if (userInfosFromRegistry && userInfo.ExpirationDate > DateTime.UtcNow) m42WebClient.RegisterApiTokenAuthentication(userInfo.EncryptedApiToken); if (App.DefaultCredentials != null) m42WebClient.RegisterCredentialAuthentication(App.DefaultCredentials); m42WebClient.RegisterPassThroughAuthentication(); if (ConfigClassV2.Instance.MsGateway_Enabled) RegisterMsGateway(); var _res = await m42WebClient.LogonAsync(); if (_res.Reason == eM42ApiReason.ok) { await ReadConfigAsync(); return true; } else LogEntry($"Initiales M42 Login fehlgeschlagen: {_res.Reason}"); } catch (Exception E) { LogException(E); } finally { if (CM != null) LogMethodEnd(CM); } return false; } //public async Task VerifyUserCredentialsAndAuthorizationOld() //{ // var methodInfo = MethodBase.GetCurrentMethod(); // LogMethodBegin(methodInfo); // await Task.CompletedTask; // bool authorizationState = false; // bool useRegistrationForm = false; // bool usePassThrough = false; // try // { // // --------------------------------------- // // 0) Versuch: (Registry) API-Token verwenden // // --------------------------------------- // LogEntry("Lese UserInfos aus Registry.", LogLevels.Debug); // var userInfosFromRegistry = ReadRegistryUserInfo(); // LogEntry($"UserInfosFromRegistry: {userInfosFromRegistry}", LogLevels.Debug); // if (userInfosFromRegistry == true && userInfo.ExpirationDate > DateTime.UtcNow) // { // LogEntry("Versuche Anmeldung mit lokalem API-Token (WebClient.LogonWithApiKeyAsync).", LogLevels.Debug); // usingGeneralAPIToken = true; // m42WebClient = new cM42WebClientV2(GetMatrixServer(false), GetCultureName(), DisableDNSCache: true); // var retVal = await m42WebClient.LogonWithApiKeyAsync(userInfo.EncryptedApiToken); // LogEntry($"LogonWithApiKeyAsync: {retVal}", LogLevels.Debug); // if (retVal == eM42ApiReason.ok) // { // LogEntry("API-Token-Anmeldung erfolgreich.", LogLevels.Debug); // authorizationState = true; // MainWindow.MainInstance.InitializeOrUpdateTrayMenu(); // } // else if (retVal == eM42ApiReason.unauthorized) // { // LogEntry($"API-Token-Anmeldung nicht erfolgreich. Grund: {retVal}", LogLevels.Debug); // ClearRegistryUserInfo(); // } // else // { // LogEntry($"API-Token-Anmeldung nicht erfolgreich. Grund: {retVal}", LogLevels.Debug); // } // } // else // { // LogEntry("User-Infos nicht vorhanden oder Token abgelaufen. Prüfe DefaultCredentials.", LogLevels.Debug); // // --------------------------------------- // // 1) Versuch: DefaultCredentials verwenden // // --------------------------------------- // if (App.DefaultCredentials != null) // { // LogEntry("DefaultCredentials vorhanden. Versuche Anmeldung via m42WebClient.Open()...", LogLevels.Debug); // m42WebClient = new cM42WebClientV2( // GetMatrixServer(false), // GetCultureName(), // DisableDNSCache: true // ); // eM42ApiReason retVal = await m42WebClient.Open(); // LogEntry($"m42WebClient.Open() (DefaultCredentials) => {retVal}", LogLevels.Debug); // if (retVal == eM42ApiReason.ok) // { // LogEntry("DefaultCredentials-Login erfolgreich. Lese nun UserInfo...", LogLevels.Debug); // cM42UserInfoResult result = await m42WebClient.GetUserInfoAsync(); // rnt_userInfoFromLogin = result.UserInfo; // await ReadConfigAsync(); // authorizationState = true; // LogEntry("DefaultCredentials-Login abgeschlossen. authorizationState=true", LogLevels.Debug); // } // else // { // LogEntry($"DefaultCredentials-Login fehlgeschlagen: {retVal}", LogLevels.Debug); // usePassThrough = true; // } // } // else // { // // Falls keine DefaultCredentials existieren, direkt PassThrough // usePassThrough = true; // LogEntry("Keine DefaultCredentials vorhanden. Wechsle zu PassThrough...", LogLevels.Debug); // } // // --------------------------------------- // // 2) Versuch: PassThrough // // --------------------------------------- // if (usePassThrough) // { // LogEntry("Starte PassThrough-Login (m42WebClient.Open() ohne Credentials)...", LogLevels.Debug); // m42WebClient = new cM42WebClientV2(GetMatrixServer(false), GetCultureName(), DisableDNSCache: true); // eM42ApiReason retVal = await m42WebClient.Open(); // LogEntry($"m42WebClient.Open() (PassThrough) => {retVal}", LogLevels.Debug); // if (retVal == eM42ApiReason.ok) // { // LogEntry("PassThrough-Login erfolgreich. Lese nun UserInfo...", LogLevels.Debug); // cM42UserInfoResult result = await m42WebClient.GetUserInfoAsync(); // rnt_userInfoFromLogin = result.UserInfo; // if (result.Reason == eM42ApiReason.unauthorized) // { // LogEntry("PassThrough: unauthorized. Muss Registrierungsformular anzeigen.", LogLevels.Debug); // useRegistrationForm = true; // } // else // { // await ReadConfigAsync(); // authorizationState = true; // LogEntry("PassThrough-Login abgeschlossen. authorizationState=true", LogLevels.Debug); // } // } // else // { // LogEntry($"PassThrough fehlgeschlagen (unbekannte Ursache): {retVal}", LogLevels.Debug); // } // } // // --------------------------------------- // // 3) Versuch: Anmeldeformular anzeigen // // --------------------------------------- // if (useRegistrationForm) // { // // Prüfen, ob schon ein CPM42FormsAuthentication offen ist // var existingWindow = Application // .Current // .Windows // .Cast() // .OfType() // .FirstOrDefault(); // if (existingWindow == null) // { // LogEntry("Zeige Forms-Authentifizierungsdialog an.", LogLevels.Debug); // CPM42FormsAuthentication cPM42FormsAuthentication = // new CPM42FormsAuthentication(); // cPM42FormsAuthentication.ShowDialog(); // if (cPM42FormsAuthentication._successfulAuthorized) // { // LogEntry("Forms-Authentifizierung erfolgreich.", LogLevels.Debug); // var accessToken = cPM42FormsAuthentication.GetAccessToken(); // if (accessToken != null) // { // m42WebClient = new cM42WebClientV2(GetMatrixServer(false), GetCultureName(), DisableDNSCache: true); // m42WebClient.SetBearerToken(accessToken); // await m42WebClient.Open(); // cM42UserInfoResult result = await m42WebClient.GetUserInfoAsync(); // rnt_userInfoFromLogin = result.UserInfo; // await ReadConfigAsync(); // WriteRegistryUserInfo(); // var readAgain = ReadRegistryUserInfo(); // LogEntry($"Registry nach Speichern erneut gelesen: {readAgain}", LogLevels.Debug); // // 5) Webclient mit neuem Token initialisieren // if (readAgain && userInfo?.EncryptedApiToken != null) // { // LogEntry("Initialisiere WebClient mit neuem API-Token...", LogLevels.Debug); // m42WebClient = new cM42WebClientV2(GetMatrixServer(false), GetCultureName(), DisableDNSCache: true); // var retVal = await m42WebClient.LogonWithApiKeyAsync(userInfo.EncryptedApiToken); // LogEntry($"LogonWithApiKeyAsync (nach Formular-Anmeldung) => {retVal}", LogLevels.Debug); // if (retVal == eM42ApiReason.ok) // { // // Jetzt analog zum bereits existierenden Code Konfiguration laden: // await ReadConfigAsync(); // authorizationState = true; // usingGeneralAPIToken = true; // LogEntry("Formular-Anmeldung mit neuem Token erfolgreich. authorizationState=true", LogLevels.Debug); // } // else // { // // Falls hier wieder ein Problem auftritt, können Sie weitere Logik einbauen // LogEntry("Anmeldung mit neuem Token fehlgeschlagen. " + // $"Grund: {retVal}", LogLevels.Debug); // } // } // else // { // LogEntry("Registry konnte nicht erneut gelesen werden oder Token war null.", LogLevels.Debug); // } // } // } // else // { // // Falls abgebrochen oder Auth. fehlgeschlagen: // LogEntry("Forms-Authentifizierung fehlgeschlagen oder abgebrochen. Setze App in Offline-Modus.", LogLevels.Debug); // MainWindow.MainInstance.OnlineState = MainWindow.enumOnlineState.Offline; // MainWindow.MainInstance.InitializeOrUpdateTrayMenu(); // } // } // else // { // // Es existiert bereits ein Fenster dieses Typs - nach vorne holen // existingWindow.Activate(); // existingWindow.Focus(); // } // } // } // } // catch (Exception ex) // { // LogEntry($"Ausnahme in {methodInfo.Name}: {ex.Message}", LogLevels.Debug); // LogException(ex); // } // finally // { // LogMethodEnd(methodInfo); // } // MainWindow.MainInstance.OnlineState = authorizationState ? MainWindow.enumOnlineState.Online : MainWindow.enumOnlineState.Offline; // MainWindow.MainInstance.OnlineStatusChanged(); // MainWindow.MainInstance.UpdateTimer(); // return authorizationState; //} private void FailureSetup(string message) { LogEntry(message, LogLevels.Error); SetDefault(); rnt_tryCounter++; cpConfig._timerIntervalTicket = 1; cpConfig._timerIntervalRegularAnnouncements = 1; cpConfig._timerIntervalAdHocAnnouncements = 1; if (rnt_tryCounter > 200) { rnt_tryCounter = 6; } } /* private void SetValues(System.Data.DataTable setupDic) { try { _announcementDataView = new Guid(setupDic.Rows[0]["announcementGUID"].ToString()); } catch { _announcementDataView = new Guid("05168130-f347-c548-aabe-08d390803da6"); } try { _incidentDataView = new Guid(setupDic.Rows[0]["incidentGUID"].ToString()); } catch { _incidentDataView = new Guid("375fe36d-83b3-c490-ae69-08d29106a41c"); } try { var strVersion = setupDic.Rows[0]["Version"]?.ToString(); Version.TryParse(strVersion, out _ServerVersion); } catch { _ServerVersion = new Version(0, 0, 0, 0); } foreach (var Entry in MainFunctionM42Column) { try { if (setupDic.Columns.Contains(Entry.Value)) MainFunctionActivation[Entry.Key] = bool.Parse(setupDic.Rows[0][Entry.Value].ToString()); } catch { MainFunctionActivation[Entry.Key] = true; } } try { IsStartApplicationMinimized = bool.Parse(setupDic.Rows[0]["startMinimized"].ToString()); } catch { IsStartApplicationMinimized = false; } try { IsUUX = bool.Parse(setupDic.Rows[0]["UseUuxLinksInEmails"].ToString()); WriteUserSetup(); } catch { IsUUX = false; } try { isDraggable = bool.Parse(setupDic.Rows[0]["isDraggable"].ToString()); WriteUserSetup(); } catch { isDraggable = false; } try { if (!String.IsNullOrEmpty(setupDic.Rows[0]["activeButtonColor"].ToString())) { uiColors["activeButtonColor"] = setupDic.Rows[0]["activeButtonColor"].ToString(); } else { uiColors["activeButtonColor"] = Properties.Resources.activeButtonColor; } Application.Current.Resources["activeButtonColor"] = new SolidColorBrush((Color)ColorConverter.ConvertFromString(uiColors["activeButtonColor"])); WriteUserSetup(); } catch { uiColors["activeButtonColor"] = Properties.Resources.activeButtonColor; } try { if (!String.IsNullOrEmpty(setupDic.Rows[0]["inactiveButtonColor"].ToString())) { uiColors["inactiveButtonColor"] = setupDic.Rows[0]["inactiveButtonColor"].ToString(); } else { uiColors["inactiveButtonColor"] = Properties.Resources.inactiveButtonColor; } Application.Current.Resources["inactiveButtonColor"] = new SolidColorBrush((Color)ColorConverter.ConvertFromString(uiColors["inactiveButtonColor"])); WriteUserSetup(); } catch { uiColors["inactiveButtonColor"] = Properties.Resources.inactiveButtonColor; } try { if (!String.IsNullOrEmpty(setupDic.Rows[0]["backgroundColor"].ToString())) { uiColors["backgroundColor"] = setupDic.Rows[0]["backgroundColor"].ToString(); } else { uiColors["backgroundColor"] = Properties.Resources.backgroundColor; } Application.Current.Resources["backgroundColor"] = new SolidColorBrush((Color)ColorConverter.ConvertFromString(uiColors["backgroundColor"])); WriteUserSetup(); } catch { uiColors["backgroundColor"] = Properties.Resources.backgroundColor; } try { if (!String.IsNullOrEmpty(setupDic.Rows[0]["headerColor"].ToString())) { uiColors["headerColor"] = setupDic.Rows[0]["headerColor"].ToString(); } else { uiColors["headerColor"] = Properties.Resources.headerColor; } Application.Current.Resources["headerColor"] = new SolidColorBrush((Color)ColorConverter.ConvertFromString(uiColors["headerColor"])); WriteUserSetup(); } catch { uiColors["headerColor"] = Properties.Resources.headerColor; } try { _timerInterval = Int32.Parse(setupDic.Rows[0]["updateInterval"].ToString()); } catch { _timerInterval = 10; } try { _iconColor = Int32.Parse(setupDic.Rows[0]["iconColor"].ToString()); SetButtonForeground(_iconColor); WriteUserSetup(); } catch { _iconColor = 10; SetButtonForeground(_iconColor); } try { _mainIconTextColor = Int32.Parse(setupDic.Rows[0]["mainIconTextColor"].ToString()); SetButtonForeground(_mainIconTextColor, true); WriteUserSetup(); } catch { _mainIconTextColor = 10; SetButtonForeground(_mainIconTextColor, true); } try { LogoUrl = setupDic.Rows[0]["logoUrl"].ToString(); } catch { // ignored } try { RemoteAppPath = setupDic.Rows[0]["remoteApp"].ToString(); WriteUserSetup(); } catch (Exception) { } try { TrayIconUrl = setupDic.Rows[0]["trayIcon"].ToString(); } catch (Exception) { } try { _linkList = new List>(); try { var L = setupDic.Rows[0]["customLinks"].ToString(); if (L.Length > 0) { FillCustomLinkList(L.Split(';')); } else { MainFunctionActivation[enumMainFunctions.CustomLinks] = false; } } catch (Exception) { } } catch (Exception) { } MainFunctionActivation[enumMainFunctions.CustomLinks] = cpConfig._linkList.Count > 0; try { disableClosing = bool.Parse(setupDic.Rows[0]["DisableClosing"].ToString()); WriteUserSetup(); } catch { disableClosing = true; } } */ private void SetValues() { try { var uiColors = cpConfig?._uiColors; Color backgroundColor = TryGetConfiguredUiColor(uiColors, "backgroundColor", out Color configuredBackground) ? configuredBackground : ConverterHelper.ColorConvertFromString(Properties.Resources.backgroundColor); Color headerColor = TryGetConfiguredUiColor(uiColors, "headerColor", out Color configuredHeader) ? configuredHeader : ConverterHelper.ColorConvertFromString(Properties.Resources.headerColor); bool hasConfiguredActiveColor = TryGetConfiguredUiColor(uiColors, "activeButtonColor", out Color configuredActiveButtonColor); bool hasConfiguredInactiveColor = TryGetConfiguredUiColor(uiColors, "inactiveButtonColor", out Color configuredInactiveButtonColor); System.Windows.Application.Current.Resources["headerColor"] = new SolidColorBrush(headerColor); ApplyBackgroundDerivedResources(backgroundColor); // Active/Inactive button colors must come directly from config (WebAPI), not be overridden by derived background shades. Color activeButtonColor = hasConfiguredActiveColor ? configuredActiveButtonColor : ConverterHelper.ColorConvertFromString(Properties.Resources.activeButtonColor); System.Windows.Application.Current.Resources["activeButtonColor"] = new SolidColorBrush(activeButtonColor); System.Windows.Application.Current.Resources["inactiveButtonColor"] = new SolidColorBrush( hasConfiguredInactiveColor ? configuredInactiveButtonColor : ConverterHelper.ColorConvertFromString(Properties.Resources.inactiveButtonColor)); System.Windows.Application.Current.Resources["primaryActionHoverColor"] = new SolidColorBrush( GetButtonHoverColor(activeButtonColor, 1.15)); ApplyHeaderDerivedResources(headerColor); LogEntry($"[Theme] activeButtonColor source={(hasConfiguredActiveColor ? "webapi" : "default")} value={((SolidColorBrush)System.Windows.Application.Current.Resources["activeButtonColor"]).Color}", LogLevels.Debug); } catch { Color fallbackBackground = ConverterHelper.ColorConvertFromString(Properties.Resources.backgroundColor); Color fallbackHeader = ConverterHelper.ColorConvertFromString(Properties.Resources.headerColor); Color fallbackActive = ConverterHelper.ColorConvertFromString(Properties.Resources.activeButtonColor); Color fallbackInactive = ConverterHelper.ColorConvertFromString(Properties.Resources.inactiveButtonColor); System.Windows.Application.Current.Resources["headerColor"] = new SolidColorBrush(fallbackHeader); ApplyBackgroundDerivedResources(fallbackBackground); System.Windows.Application.Current.Resources["activeButtonColor"] = new SolidColorBrush(fallbackActive); System.Windows.Application.Current.Resources["inactiveButtonColor"] = new SolidColorBrush(fallbackInactive); System.Windows.Application.Current.Resources["primaryActionHoverColor"] = new SolidColorBrush( GetButtonHoverColor(fallbackActive, 1.15)); ApplyHeaderDerivedResources(fallbackHeader); } try { // SetButtonThemens(); //SetButtonForeground(cpConfig._iconColor); } catch (Exception e) { cpConfig._iconColor = 10; cpConfig._mainIconTextColor = 10; var k = e.Message; // SetButtonThemens(); //SetButtonForeground(cpConfig._iconColor); } } /* private void FillCustomLinkList(string[] input) { if (input.Length > 0) { try { foreach (string s in input) { var temp = s.Split(','); cpConfig._linkList.Add(temp[1].Trim(), temp[0].Trim()); temp = null; } } catch (Exception) { } } } */ public async Task DownLoadFileAsync(string fileUrl, string destinationPath) { var CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); try { HttpResponseMessage response = null; using (var _http = m42WebClient.GetHttp()) { response = await _http.GetAsync(fileUrl); } if (response != null && response.IsSuccessStatusCode) { var content = await response.Content.ReadAsByteArrayAsync(); System.IO.File.WriteAllBytes(destinationPath, content); } return response; } catch (Exception E) { LogException(E); throw; } finally { LogMethodEnd(CM); } } public async Task DownloadLogoAsync() { if (cpConfig._logoUrl == rnt_LogoUrlPrev) return; var CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); try { rnt_LogoUrlPrev = cpConfig._logoUrl; var LogoFile = GetLogoFilePath(withoutAlternate: true); if (!string.IsNullOrEmpty(cpConfig._logoUrl)) { try { Directory.CreateDirectory(Path.GetDirectoryName(LogoFile)); await DownLoadFileAsync(cpConfig._logoUrl, LogoFile); } catch (Exception E) { LogException(E); } } else { try { System.IO.File.Delete(LogoFile); } catch { } } if (System.IO.File.Exists(LogoFile)) { var FI = new FileInfo(LogoFile); if (FI.Length == 0) FI.Delete(); } MainWindow.MainInstance?.RefreshLogo(); } catch (Exception E) { LogException(E); } finally { LogMethodEnd(CM); } } public async Task DownloadTrayIconAsync() { if (cpConfig._trayIconUrl == rnt_TrayIconUrlPrev) return; var CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); try { var IconFile = GetTrayIconFilePath(true); if (!string.IsNullOrEmpty(cpConfig._trayIconUrl)) { try { Directory.CreateDirectory(Path.GetDirectoryName(IconFile)); await DownLoadFileAsync(cpConfig._trayIconUrl, IconFile); } catch (Exception E) { LogException(E); } } else { System.IO.File.Delete(IconFile); } if (System.IO.File.Exists(IconFile)) { var FI = new FileInfo(IconFile); if (FI.Length == 0) FI.Delete(); } MainWindow.MainInstance?.RefreshTrayIcon(); } catch (Exception E) { LogException(E); } finally { LogMethodEnd(CM); } } public bool ReadRegistryUserInfo() { var CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); try { // 1) Registry-Wert lesen var regResult = Registry.GetValue(registryHKCUPath, registryUserInformationValueName, null); if (string.IsNullOrEmpty(regResult?.ToString())) { LogEntry($"Registry Key oder Wert nicht gefunden: {registryHKCUPath}\\{registryUserInformationValueName}", LogLevels.Warning); return false; } // 2) Dekodieren var decodedUserInfo = PrivateCustomerPanelSecurePassword.Instance.Decode(regResult.ToString()); if (string.IsNullOrEmpty(decodedUserInfo)) { LogEntry("Der dekodierte Registry-Inhalt ist leer.", LogLevels.Warning); return false; } // 3) Deserialisieren var deserialized = JsonConvert.DeserializeObject(decodedUserInfo); if (deserialized == null) { LogEntry("Deserialisierung von UserInfo aus der Registry fehlgeschlagen.", LogLevels.Warning); return false; } // 4) Wenn erfolgreich, in `userInfo` übernehmen userInfo = deserialized; // Zur Debug-Übersicht nur teilweise den Token anzeigen LogEntry($"Deserialisierte UserInfo: {userInfo}", LogLevels.Debug); return true; } catch (Exception ex) { LogException(ex); } finally { LogMethodEnd(CM); } return false; } public void WriteRegistryUserInfo() { var methodInfo = MethodBase.GetCurrentMethod(); LogMethodBegin(methodInfo); string userInfoAsJson; var userInfoAsObject = JsonConvert.DeserializeObject(rnt_userInfoFromLogin); try { RegistryKey hkcuSoftwareC4It = Registry.CurrentUser.CreateSubKey(hKeyUserPath); LogEntry($"Userinformationen in Registry schreiben:{hKeyUserPath}", LogLevels.Debug); if (hkcuSoftwareC4It != null) { userInfo.Id = userInfoAsObject.Id; userInfo.Email = userInfoAsObject.Email; userInfo.EncryptedApiToken = cpConfig._encryptedApiToken; userInfo.LoginDate = DateTime.UtcNow; userInfo.ExpirationDate = userInfo.LoginDate.AddDays(cpConfig._reloginIntervalDays); userInfoAsJson = JsonConvert.SerializeObject(userInfo); var encryptedUser = PrivateCustomerPanelSecurePassword.Instance.Encode(userInfoAsJson); hkcuSoftwareC4It.SetValue(registryUserInformationValueName, encryptedUser, RegistryValueKind.String); } else { LogEntry($"Schreiben der Userinformationen in Registry fehlgeschlagen: {methodInfo.Name}:{hkcuSoftwareC4It}", LogLevels.Debug); } } catch (Exception ex) { LogException(ex); LogMethodEnd(methodInfo); } } public bool ClearRegistryUserInfo() { var CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); try { // Versuche, den Registry-Schlüssel mit Schreibzugriff zu öffnen using (var key = Registry.CurrentUser.OpenSubKey(hKeyUserPath, writable: true)) { if (key == null) { LogEntry($"Registry-Pfad nicht gefunden: {hKeyUserPath}", LogLevels.Warning); return false; } // Prüfen, ob der Wert überhaupt existiert var existingValue = key.GetValue(registryUserInformationValueName); if (existingValue == null) { LogEntry($"Kein UserInfo-Wert zum Löschen gefunden: {hKeyUserPath}\\{registryUserInformationValueName}", LogLevels.Warning); return false; } // Wert löschen key.DeleteValue(registryUserInformationValueName); LogEntry($"Registry-Wert gelöscht: {hKeyUserPath}\\{registryUserInformationValueName}", LogLevels.Debug); // Im Speicher gehaltene UserInfo zurücksetzen userInfo = new UserInfo(); return true; } } catch (Exception ex) { LogException(ex); return false; } finally { LogMethodEnd(CM); } } public async Task ReadConfigAsync(bool force = false) { try { string json = null; try { using (var _http = m42WebClient.GetHttp()) { json = await _http.GetApiJsonAsync(String.Format(ApiConfigBaseUrl, local_MatrixServer, force), ""); } if (string.IsNullOrEmpty(json) || JsonConvert.DeserializeObject(json) == null) return false; cpConfig = JsonConvert.DeserializeObject(json); cpConfig._encryptedApiToken = CustomerPanelSecurePassword.Instance.Decode(cpConfig._encryptedApiToken); LogEntry($"[Config API] _isDraggable={cpConfig?._isDraggable}", LogLevels.Debug); if (cpConfig?._uiColors != null && cpConfig._uiColors.TryGetValue("activeButtonColor", out string apiActiveColor) && !string.IsNullOrWhiteSpace(apiActiveColor)) LogEntry($"[Config API] activeButtonColor={apiActiveColor}", LogLevels.Debug); else LogEntry("[Config API] activeButtonColor missing or empty", LogLevels.Warning); } catch (Exception E) { LogException(E); throw; } SetValues(); rnt_tryCounter = 0; return true; } catch (WebException webClientException) { LogException(webClientException); FailureSetup(webClientException.Message); } return false; } private void SetDefault() { } private bool WriteUserSetup(bool windowPosChanged=false) { bool setupOk = true; try { RegistryKey hkcuSoftwareC4It = Registry.CurrentUser.CreateSubKey(hKeyUserPath); if (windowPosChanged && hkcuSoftwareC4It != null) { hkcuSoftwareC4It.SetValue("windowPosition", JsonConvert.SerializeObject(usr_windowPosition), RegistryValueKind.String); return true; } RegistryKey hkcuSoftwareC4ItAuth = Registry.CurrentUser.CreateSubKey(hKeyAuthPath); if (hkcuSoftwareC4It != null) { hkcuSoftwareC4It.SetValue("userLanguage", usr_userLanguage, RegistryValueKind.DWord); hkcuSoftwareC4It.SetValue("PresentationMode", (int)usr_PresentationMode, RegistryValueKind.DWord); hkcuSoftwareC4It.SetValue("notifierEnabled", usr_enableNotifier, RegistryValueKind.DWord); } RegistryKey hkcuSoftwareC4ItConfig = Registry.CurrentUser.CreateSubKey(hKeyConfigPath); if (hkcuSoftwareC4ItConfig != null) { var configJson = JsonConvert.SerializeObject(cpConfig); hkcuSoftwareC4ItConfig.SetValue("config", configJson, RegistryValueKind.String); } } catch (Exception E) { LogException(E); setupOk = false; } return setupOk; } private void SetButtonForeground(int iconColor, bool mainColor = false) { if (mainColor) { if (iconColor != 0) { if (iconColor == 10) { System.Windows.Application.Current.Resources.MergedDictionaries.Add(MainWindow.MainInstance?._darkThemeMain); // Application.Current.Resources["mainForeground"] = new SolidColorBrush((Color)System.Windows.Media.Colors.Black); } else if (iconColor == 20) { System.Windows.Application.Current.Resources.MergedDictionaries.Add(MainWindow.MainInstance?._lightThemeMain); // Application.Current.Resources["mainForeground"] = new SolidColorBrush((Color)System.Windows.Media.Colors.White); } } else { // Application.Current.Resources["mainForeground"] = new SolidColorBrush((Color)System.Windows.Media.Colors.White); } } else { if (iconColor != 0) { if (iconColor == 10) { System.Windows.Application.Current.Resources.MergedDictionaries.Add(MainWindow.MainInstance?._darkThemeNav); //Application.Current.Resources["navForeground"] = new SolidColorBrush((Color)System.Windows.Media.Colors.Black); } else if (iconColor == 20) { System.Windows.Application.Current.Resources.MergedDictionaries.Add(MainWindow.MainInstance?._lightThemeNav); //Application.Current.Resources["navForeground"] = new SolidColorBrush((Color)System.Windows.Media.Colors.White); } } else { //Application.Current.Resources["navForeground"] = new SolidColorBrush((Color)System.Windows.Media.Colors.White); } } } public static void SaveAsJson(string Name, object O, string subKey = null) { var CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); try { var strValue = JsonConvert.SerializeObject(O); RegistryKey hkcuSoftware; if (String.IsNullOrEmpty(subKey)) { hkcuSoftware = Registry.CurrentUser.OpenSubKey("Software\\Consulting4IT GmbH\\Customer Panel", true); } else { hkcuSoftware = Registry.CurrentUser.OpenSubKey("Software\\Consulting4IT GmbH\\Customer Panel\\" + subKey, true); } if (hkcuSoftware != null) { hkcuSoftware.SetValue(Name, strValue); } else { hkcuSoftware = Registry.CurrentUser.CreateSubKey("Software\\Consulting4IT GmbH\\Customer Panel\\" + subKey, true); hkcuSoftware.SetValue(Name, strValue); } } catch (Exception E) { LogException(E); } finally { LogMethodEnd(CM); } } public static T LoadFromJson(string Name, string subKey = null) { var CM = MethodBase.GetCurrentMethod(); LogMethodBegin(CM); try { RegistryKey hkcuSoftware; if (String.IsNullOrEmpty(subKey)) { hkcuSoftware = Registry.CurrentUser.OpenSubKey("Software\\Consulting4IT GmbH\\Customer Panel", true); } else { hkcuSoftware = Registry.CurrentUser.OpenSubKey("Software\\Consulting4IT GmbH\\Customer Panel\\" + subKey, true); } if (hkcuSoftware != null) { var objValue = hkcuSoftware.GetValue(Name); var strValue = objValue?.ToString(); if (!string.IsNullOrEmpty(strValue)) { var RetVal = JsonConvert.DeserializeObject(strValue); return RetVal; } } } catch (Exception E) { LogException(E); } finally { LogMethodEnd(CM); } return default; } public T getConfigSetting(string setting) { return (T)cpConfig.GetType().GetProperty(setting).GetValue(cpConfig, null); } private string getStringFromRegistry(RegistryKey Key, string Name) { try { var _regVal = Key.GetValue(Name); if (_regVal is string regValue && !string.IsNullOrEmpty(regValue)) return regValue; } catch (Exception E) { LogException(E); } return null; } private bool? getBoolFromRegistry(RegistryKey Key, string Name) { try { var _regVal = Key.GetValue(Name); if (_regVal != null) return ConverterHelper.ObjectToBoolConverter(_regVal); } catch (Exception E) { LogException(E); } return null; } private void ReadUserSetup() { try { RegistryKey hkcuSoftware = Registry.CurrentUser.CreateSubKey(hKeyAppPath, true); RegistryKey hkcuSoftwareUsr = Registry.CurrentUser.CreateSubKey(hKeyUserPath, true); RegistryKey hkcuSoftwareConfig = Registry.CurrentUser.CreateSubKey(hKeyConfigPath, true); RegistryKey hkcuSoftwareAuth = Registry.CurrentUser.CreateSubKey(hKeyAuthPath, true); RegistryKey hkcuDPI = Registry.CurrentUser.CreateSubKey("Control Panel\\Desktop\\WindowMetrics", true); RegistryKey hklmDefaultUserKey = GetLocalMaschineHive().OpenSubKey(hKeyDefaultUserSettingsPath, false); if (hkcuSoftware != null) { if (Int32.TryParse(hkcuSoftware.GetValue("isInternalTesting")?.ToString(), out var iTesting)) if (iTesting > 0) _isInternalTesting = true; object objLang = hkcuSoftwareUsr.GetValue("userLanguage"); if (objLang == null && hklmDefaultUserKey != null) objLang = hklmDefaultUserKey.GetValue("userLanguage"); if (!Int32.TryParse((objLang ?? "0").ToString(), out usr_userLanguage)) usr_userLanguage = 0; object objNotifier = hkcuSoftwareUsr.GetValue("notifierEnabled"); if (objNotifier == null && hklmDefaultUserKey != null) objNotifier = hklmDefaultUserKey.GetValue("notifierEnabled"); usr_enableNotifier = ConverterHelper.ObjectToBoolConverter(objNotifier); object objPres = hkcuSoftwareUsr.GetValue("PresentationMode"); if (objPres == null && hklmDefaultUserKey != null) objPres = hklmDefaultUserKey.GetValue("PresentationMode"); if (objPres != null && Int32.TryParse(objPres.ToString(), out var iPresMode)) { switch (iPresMode) { case (int)enumPresentationMode.On: usr_PresentationMode = enumPresentationMode.On; break; case (int)enumPresentationMode.Off: usr_PresentationMode = enumPresentationMode.Off; break; default: usr_PresentationMode = enumPresentationMode.OS; break; } } else { // Fallback auf dndMode (alt) if (Int32.TryParse(hkcuSoftwareUsr.GetValue("dndMode")?.ToString(), out var intDND) && intDND == 1) { usr_PresentationMode = enumPresentationMode.On; } } try { var configJson = hkcuSoftwareConfig.GetValue("config")?.ToString(); if (!String.IsNullOrEmpty(configJson)) { cpConfig = JsonConvert.DeserializeObject(configJson); } } catch { //windowPosition = JsonConvert.DeserializeObject(tmpPos); } foreach (KeyValuePair co in cpConfig._uiColors) { try { System.Windows.Application.Current.Resources[co.Key] = new SolidColorBrush((Color)ColorConverter.ConvertFromString(co.Value)); } catch { } } var User = (hkcuSoftware.GetValue("UserName") ?? "").ToString(); var Password = (hkcuSoftware.GetValue("Password") ?? "").ToString(); if (!string.IsNullOrEmpty(User) && !string.IsNullOrEmpty(Password)) { var Creds = new NetworkCredential(User, Password); App.DefaultCredentials = Creds; } //if (!Int32.TryParse((hkcuSoftware.GetValue("disableClosing") ?? "0").ToString(), out tmpInt)) // tmpInt = 0; //disableClosing = tmpInt != 0; } if (hkcuDPI != null) { local_currentDPI = Int32.Parse(hkcuDPI.GetValue("AppliedDPI").ToString()); } } catch (Exception E) { LogException(E); } } public static RegistryKey GetLocalMaschineHive() { return RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32); } private void ReadMachineSetup(bool fromUser) { try { RegistryKey baseHive = fromUser ? Registry.CurrentUser : GetLocalMaschineHive(); RegistryKey hklmC4ItSetupPath = baseHive.OpenSubKey(hKeyAppPath, false); if (hklmC4ItSetupPath == null) { if (!fromUser) LogEntry($"Configuration registry path not found: {hKeyAppPath}", LogLevels.Error); return; } var _regVal = hklmC4ItSetupPath.GetValue("MatrixServer"); if (_regVal != null) { string rawValue = _regVal.ToString(); string fqdn = rawValue; // Default: so übernehmen, wie es in der Registry steht if (Uri.IsWellFormedUriString(rawValue, UriKind.Absolute)) { try { var uri = new Uri(rawValue); fqdn = uri.Host; LogEntry($"Registry-Wert MatrixServer war eine URL. Nur Hostnamen '{fqdn}' wird verwendet.", LogLevels.Debug); } catch (UriFormatException) { } } else { if (rawValue.Contains("/")) { string attempt = "https://" + rawValue; if (Uri.IsWellFormedUriString(attempt, UriKind.Absolute)) { try { var uri = new Uri(attempt); fqdn = uri.Host; LogEntry($"Registry-Wert MatrixServer enthielt Pfad ohne Schema. Nur Hostnamen '{fqdn}' wird verwendet.", LogLevels.Debug); } catch (UriFormatException) { } } } } local_MatrixServer = fqdn; } _regVal = hklmC4ItSetupPath.GetValue("ShowIpInfoOnlyInCorporateNetwork"); if (_regVal != null) { ShowIpInfoOnlyInCorporateNetwork = ConverterHelper.ObjectToBoolConverter(_regVal); } _regVal = hklmC4ItSetupPath.GetValue("CustomerPanelTitle"); if (_regVal is string regValue && !string.IsNullOrEmpty(regValue)) { CustomerPanelTitle = regValue; } _regVal = hklmC4ItSetupPath.GetValue("AnnouncementView"); if (_regVal is int regValue_AnnView) { AnnouncementView = regValue_AnnView; } _regVal = hklmC4ItSetupPath.GetValue("CustomAnnouncementText"); if (_regVal is string regValue_AnnText && !string.IsNullOrEmpty(regValue_AnnText)) { CustomAnnouncementText = regValue_AnnText; } } catch (Exception E) { LogException(E); } } } public class ConfigClassV2 { public const string constRegPathConfig = @"SOFTWARE\Consulting4IT GmbH\Customer Panel"; [RegConfig(ReadOnly: true)] public string MsGateway_TenantId { get; private set; } = string.Empty; [RegConfig(ReadOnly: true)] public string MsGateway_ApplicationId { get; private set; } = string.Empty; [RegConfig(ReadOnly: true)] public string MsGateway_Scope { get; private set; } = string.Empty; [RegConfigSubItem("authentication")] public ConfigAuthentication Authentication { get; set; } = new ConfigAuthentication(); public static ConfigClassV2 Instance = null; static ConfigClassV2() { Instance = new ConfigClassV2(); Instance.Load(); Instance.Save(); } public void Load() { cConfigRegistryHelper.Load(constRegPathConfig, this); } public void Save(string fullPropertyName = null) { cConfigRegistryHelper.Save(constRegPathConfig, this, fullPropertyName); } public bool MsGateway_Enabled { get { return !string.IsNullOrEmpty(MsGateway_TenantId) && !string.IsNullOrEmpty(MsGateway_ApplicationId) && !string.IsNullOrEmpty(MsGateway_Scope); } } } public class ConfigAuthentication { [RegConfig] public bool noPassthrough { get; set; } = default; [RegConfig] public bool noLogonAtAll { get; set; } = default; [RegConfig] public enumAlternateAuthMethods additionalMethod { get; set; } = default; [RegConfig] public string BasicUsername { get; set; } = string.Empty; [RegConfig] public string BasicPassword { get; set; } = string.Empty; [RegConfig] public string M42AccessToken { get; set; } = string.Empty; } }