private void btnStatsCancel_Click(object sender, EventArgs e) { ZAMsettings.RollbackCachedConfiguration(); errorProvider.Clear(); if (lvCollectors.SelectedItems.Count > 0) { CollectorListViewItem itemBeingEdited = (CollectorListViewItem)lvCollectors.SelectedItems[0]; Collector userBeingEdited = itemBeingEdited.Collector; // If a newly added row, remove it and select the first one in list if (1 == 0) { //lvCollectors.Items.Remove(itemBeingEdited); //if (lvCollectors.Items.Count > 0) //{ // lvCollectors.Items[0].Selected = true; //} } else { // Refresh user from rolled back configuration Collector refreshCollector = ZAMsettings.Settings.Collectors[userBeingEdited.Name]; Collectors_LoadFields(refreshCollector); // This will clone the Collector so that the listview doesn't have a direct link to the configuration itemBeingEdited.Collector = refreshCollector; } } EditingCollectors = false; }
public static void BeginCachedConfiguration() { Debug.Assert(_initialized, "Not initialized."); Debug.Assert(_uncommittedZAMsettings == null, "Configuration already in a cached state. It must be rolled back or committed before calling BeginCachedConfiguration."); try { //_logger.LogInformation($"In BeginCachedConfiguration:\n{_committedJsonStr}"); _uncommittedZAMsettings = JsonConvert.DeserializeObject <ZAMsettings>(_committedJsonStr); _uncommittedZAMsettings.m_readOnly = false; // Because this value is not persisted in json file, set current user manually. _uncommittedZAMsettings.CurrentUserProfile = _committedZAMsettings.CurrentUserProfile; _logger.LogInformation($"Configuration cached."); } catch (Exception ex) { throw new ApplicationException($"Exception occurred trying to load configuration from JSON string.", ex); } }
/// <summary> /// On initial load, the desired collection durations are load from configuration. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainForm_Load(object sender, EventArgs e) { // for handling UI events m_dispatcher = Dispatcher.CurrentDispatcher; // Initialize the settings manager ZAMsettings.Initialize(m_loggerFactory); // Determine window position if (ZAMsettings.Settings.WindowPositionX > 0 && ZAMsettings.Settings.WindowPositionY > 0) { this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Location = new System.Drawing.Point(ZAMsettings.Settings.WindowPositionX, ZAMsettings.Settings.WindowPositionY); } this.lvOverall.Items.Clear(); this.lvOverall.Items.Add(m_summaryHelper.SummaryListViewItem); //m_labelHelpers.Add(new LabelHelper(lblMA1, lblAvgPower1, lblMaxPower1, lblFtpPower1, lblAvgHR1)); //m_labelHelpers.Add(new LabelHelper(lblMA2, lblAvgPower2, lblMaxPower2, lblFtpPower2, lblAvgHR2)); //m_labelHelpers.Add(new LabelHelper(lblMA3, lblAvgPower3, lblMaxPower3, lblFtpPower3, lblAvgHR3)); // Set the environment based on the current user SetupCurrentUser(); m_logger.LogInformation("MainForm Loaded"); }
private CancellationTokenSource m_cancellationTokenSource; // For cancelling thread awaiting rider start public MainForm(IServiceProvider serviceProvider, IConfiguration configuration, ZPMonitorService zpMonitorService, ILoggerFactory loggerFactory) { m_logger = loggerFactory.CreateLogger <MainForm>();; m_serviceProvider = serviceProvider; m_zpMonitorService = zpMonitorService; m_loggerFactory = loggerFactory; m_maCollection = new Dictionary <DurationType, MovingAverageWrapper>(); m_summaryHelper = new SummaryHelper(new SummaryListViewItem(new SummaryItem())); //m_labelUnits = new Dictionary<string, string>(); //m_labelHelpers = new List<LabelHelper>(); m_normalizedPower = new NormalizedPower(zpMonitorService, loggerFactory); m_normalizedPower.NormalizedPowerChangedEvent += NormalizedPowerChangedEventHandler; m_normalizedPower.MetricsChangedEvent += MetricsChangedEventHandler; InitializeComponent(); // This rounds the edges of the borderless window this.Region = System.Drawing.Region.FromHrgn(ZAMsettings.CreateRoundRectRgn(0, 0, Width, Height, 15, 15)); btnClose.FlatAppearance.BorderColor = Color.FromArgb(0, 255, 255, 255); //transparent //MainForm.colorListViewHeader(ref lvViewer, lvViewer.BackColor, Color.White); // transparent ListView headers //MainForm.colorListViewHeader(ref lvOverall, lvOverall.BackColor, Color.White); // transparent ListView headers SetListViewHeaderColor(ref lvViewer, Color.FromArgb(255, 243, 108, 61), Color.White); // Orange ListView headers SetListViewHeaderColor(ref lvOverall, Color.FromArgb(255, 243, 108, 61), Color.White); // Orange ListView headers }
private void btnCancelProfile_Click(object sender, EventArgs e) { ZAMsettings.RollbackCachedConfiguration(); errorProvider.Clear(); if (lvUserProfiles.SelectedItems.Count > 0) { UserProfileListViewItem itemBeingEdited = (UserProfileListViewItem)lvUserProfiles.SelectedItems[0]; UserProfile userBeingEdited = itemBeingEdited.UserProfile; // If a newly added row, remove it and select the first one in list if (userBeingEdited.UniqueId.Length == 0) { lvUserProfiles.Items.Remove(itemBeingEdited); if (lvUserProfiles.Items.Count > 0) { lvUserProfiles.Items[0].Selected = true; lvUserProfiles.Items[0].Focused = true; } } else { // Refresh user from rolled back configuration UserProfile refreshUser = ZAMsettings.Settings.UserProfiles[userBeingEdited.UniqueId]; UserProfiles_LoadFields(refreshUser); // This will clone the UserProfile so that the listview doesn't have a direct link to the configuration itemBeingEdited.UserProfile = refreshUser; } } EditingUserProfiles = false; }
public static void CommitCachedConfiguration() { Debug.Assert(_initialized, "Not initialized."); Debug.Assert(_uncommittedZAMsettings != null, "Configuration not in a cached state. It must be cached first using BeginCachedConfiguration."); try { string json = JsonConvert.SerializeObject(_uncommittedZAMsettings, Formatting.Indented); File.WriteAllText(FileName, json); //_logger.LogInformation($"In CommitCachedConfiguration:\n{json}"); _committedZAMsettings = _uncommittedZAMsettings; _committedJsonStr = json; _committedZAMsettings.m_readOnly = true; _uncommittedZAMsettings = null; _logger.LogInformation($"Cached configuration saved to file: {FileName}"); } catch (Exception ex) { throw new ApplicationException($"Exception occurred trying to save cached configuration to file: {FileName}", ex); } }
private void btnRemoveProfile_Click(object sender, EventArgs e) { if (lvUserProfiles.SelectedItems.Count > 0) { UserProfileListViewItem itemBeingEdited = (UserProfileListViewItem)lvUserProfiles.SelectedItems[0]; UserProfile userBeingEdited = itemBeingEdited.UserProfile; if (MessageBox.Show(this, $"Delete user ({userBeingEdited.Name}), are you sure?", "Deletion Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes) { try { ZAMsettings.BeginCachedConfiguration(); ZAMsettings.Settings.DeleteUserProfile(userBeingEdited); ZAMsettings.CommitCachedConfiguration(); lvUserProfiles.BeginUpdate(); lvUserProfiles.Items.Remove(itemBeingEdited); if (lvUserProfiles.Items.Count > 0) { lvUserProfiles.Items[0].Focused = true; lvUserProfiles.Items[0].Selected = true; } lvUserProfiles.EndUpdate(); } catch (Exception ex) { MessageBox.Show("Exception occurred: " + ex.ToString(), "Error deleting User Profile", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } }
private void btnSaveSettings_Click(object sender, EventArgs e) { bool errorOccurred = false; errorOccurred = (errorOccurred || ValidateSystemSettings(this.cbMeasurementSystem)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.rbManual)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.rbAutomatic)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.cbDistanceUom)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.cbPosition)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.tbDistance)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.tbHrs)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.tbMins)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.tbSecs)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.rbDistance)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.rbTime)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.rbPosition)); // final validation errorOccurred = (errorOccurred || ValidateSystemSettings(this.gbLaps)); if (!errorOccurred) { ZAMsettings.CommitCachedConfiguration(); EditingSystemSettings = false; } }
public static Task Main(string[] args) { var executableLocation = Path.GetDirectoryName(typeof(Program).Assembly.Location); var host = new HostBuilder() .ConfigureWinForms <MainForm>() //.ConfigureWinForms<MonitorStatistics>() .ConfigureConfiguration(args) .ConfigureLogging() .ConfigureSingleInstance(builder => { builder.MutexId = "{80B16FA8-ECAE-4DD8-9F8A-FE7E6780A825}"; builder.WhenNotFirstInstance = (hostingEnvironment, logger) => { // This is called when an instance was already started, this is in the second instance logger.LogWarning("Application {0} already running.", hostingEnvironment.ApplicationName); }; }) //.ConfigurePlugins(pluginBuilder => //{ // if (executableLocation == null) // { // return; // } // var runtime = Path.GetFileName(executableLocation); // var parentDirectory = Directory.GetParent(executableLocation).FullName; // var configuration = Path.GetFileName(parentDirectory); // var basePath = Path.Combine(executableLocation, @"..\..\..\..\"); // // Specify the location from where the Dll's are "globbed" // pluginBuilder.AddScanDirectories(basePath); // // Add the framework libraries which can be found with the specified globs // pluginBuilder.IncludeFrameworks(@$"**\bin\{configuration}\netstandard2.0\*.FrameworkLib.dll"); // // Add the plugins which can be found with the specified globs // pluginBuilder.IncludePlugins(@$"**\bin\{configuration}\{runtime}\*.Sample.Plugin*.dll"); //}) .ConfigureServices(serviceCollection => { // Add the ZwiftPacketMonitor extensions ZwiftPacketMonitor.RegistrationExtensions.AddZwiftPacketMonitoring(serviceCollection); // add our ZwiftPacketMonitor wrapper service serviceCollection.AddSingleton <ZPMonitorService>(); serviceCollection.AddTransient <AdvancedOptions>(); serviceCollection.AddTransient <ConfigurationOptions>(); serviceCollection.AddSingleton <MonitorTimer>(); }) .UseWinFormsLifetime() .Build(); ILoggerFactory lf = host.Services.GetRequiredService <ILoggerFactory>(); ZPMonitorService zp = host.Services.GetRequiredService <ZPMonitorService>(); ZAMsettings.Initialize(lf, zp); return(host.RunAsync()); }
private bool m_mouseDown; // for moving window public AboutForm() { InitializeComponent(); // This rounds the edges of the borderless window this.Region = System.Drawing.Region.FromHrgn(ZAMsettings.CreateRoundRectRgn(0, 0, Width, Height, 15, 15)); btnClose.FlatAppearance.BorderColor = Color.FromArgb(0, 255, 255, 255); //transparent }
public static void RollbackCachedConfiguration() { Debug.Assert(_initialized, "Not initialized."); Debug.Assert(_uncommittedZAMsettings != null, "Configuration not in a cached state. It must be cached first using RollbackCachedConfiguration."); _uncommittedZAMsettings = null; _logger.LogInformation($"Cached configuration rolled back."); }
private void btnCancelSettings_Click(object sender, EventArgs e) { ZAMsettings.RollbackCachedConfiguration(); errorProvider.Clear(); // Reload values from configuration into fields since cancel was pressed SystemSettings_LoadFields(); EditingSystemSettings = false; }
public MainForm(IServiceProvider serviceProvider) { Logger = ZAMsettings.LoggerFactory.CreateLogger <MainForm>(); m_serviceProvider = serviceProvider; InitializeComponent(); // This rounds the edges of the borderless window this.Region = System.Drawing.Region.FromHrgn(ZAMsettings.CreateRoundRectRgn(0, 0, Width, Height, 15, 15)); btnClose.FlatAppearance.BorderColor = Color.FromArgb(0, 255, 255, 255); //transparent }
private void btnAddProfile_Click(object sender, EventArgs e) { UserProfileListViewItem item = new UserProfileListViewItem(); lvUserProfiles.Items.Add(item); item.Selected = true; item.Focused = true; ZAMsettings.BeginCachedConfiguration(); EditingUserProfiles = true; }
public EventCompletion() { InitializeComponent(); this.CountdownTimer = new(); this.CountdownTimer.Interval = 1000; this.CountdownTimer.Tick += this.CountdownTimer_Tick; // This rounds the edges of the borderless window this.Region = System.Drawing.Region.FromHrgn(ZAMsettings.CreateRoundRectRgn(0, 0, Width, Height, 15, 15)); btnClose.FlatAppearance.BorderColor = Color.FromArgb(0, 255, 255, 255); //transparent }
private void btnEditSettings_Click(object sender, EventArgs e) { if (ckbCustomized.Checked) { DialogResult result = MessageBox.Show(this.ParentForm, "Editing settings will overwrite all custom split goals when saved. Continue?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation); if (result == DialogResult.No) { return; } } ZAMsettings.BeginCachedConfiguration(); EditingSystemSettings = true; }
private void btnSaveSettings_Click(object sender, EventArgs e) { bool errorOccurred = false; errorOccurred = (errorOccurred || ValidateSystemSettings(tbWindowPosX)); errorOccurred = (errorOccurred || ValidateSystemSettings(tbWindowPosY)); errorOccurred = (errorOccurred || ValidateSystemSettings(cbNetwork)); errorOccurred = (errorOccurred || ValidateSystemSettings(cbCurrentUser)); errorOccurred = (errorOccurred || ValidateSystemSettings(ckbAutoStart)); if (!errorOccurred) { ZAMsettings.CommitCachedConfiguration(); EditingSystemSettings = false; } }
private void btnSaveSettings_Click(object sender, EventArgs e) { bool errorOccurred = false; if (this.EditingSystemSettings) { errorOccurred = (errorOccurred || ValidateSystemSettings(this.ckbShowSplits)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.tbSplitDistance)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.cbSplitUom)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.ckbCalculateGoal)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.dtpGoalTime)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.tbGoalDistance)); if (!errorOccurred) { // Wipe out splits and recalculate. These will be saved in settings. ZAMsettings.Settings.SplitsV2.CalculateDefaultSplits(); ZAMsettings.CommitCachedConfiguration(); EditingSystemSettings = false; // show recalculated splits this.SystemSettings_LoadFields(); } } else if (this.EditingSplitSettings) { errorOccurred = (errorOccurred || ValidateSystemSettings(this.dgvSplits)); if (!errorOccurred) { ZAMsettings.CommitCachedConfiguration(); EditingSplitSettings = false; this.SystemSettings_LoadFields(); } } }
private void btnSaveSettings_Click(object sender, EventArgs e) { bool errorOccurred = false; errorOccurred = (errorOccurred || ValidateSystemSettings(this.ckbShowSplits)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.tbSplitDistance)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.cbSplitUom)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.ckbCalculateGoal)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.tbGoalHrs)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.tbGoalMins)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.tbGoalSecs)); errorOccurred = (errorOccurred || ValidateSystemSettings(this.tbGoalDistance)); // Check to make sure selections / values all make sense errorOccurred = (errorOccurred || ValidateSystemSettings(this.lvSplits)); if (!errorOccurred) { ZAMsettings.CommitCachedConfiguration(); EditingSystemSettings = false; this.LoadSplitChart(); } }
private void btnEditSettings_Click(object sender, EventArgs e) { ZAMsettings.BeginCachedConfiguration(); EditingSystemSettings = true; }
private void btnSaveProfile_Click(object sender, EventArgs e) { bool errorOccurred = false; // this should not happen if (lvUserProfiles.SelectedItems.Count < 1) { ZAMsettings.RollbackCachedConfiguration(); EditingUserProfiles = false; return; } UserProfileListViewItem itemBeingEdited = (UserProfileListViewItem)lvUserProfiles.SelectedItems[0]; UserProfile userBeingEdited = itemBeingEdited.UserProfile; errorOccurred = (errorOccurred || ValidateUserProfiles(tbName)); errorOccurred = (errorOccurred || ValidateUserProfiles(ckbDefault)); errorOccurred = (errorOccurred || ValidateUserProfiles(tbWeight)); errorOccurred = (errorOccurred || ValidateUserProfiles(rbLbs)); errorOccurred = (errorOccurred || ValidateUserProfiles(rbKgs)); errorOccurred = (errorOccurred || ValidateUserProfiles(nPowerThreshold)); errorOccurred = (errorOccurred || ValidateUserProfiles(clbCollectors)); if (!errorOccurred) { try { // Add or Update the UserProfile dictionary in the configuration. ZAMsettings.Settings.UpsertUserProfile(userBeingEdited); ZAMsettings.CommitCachedConfiguration(); lvUserProfiles.BeginUpdate(); // Refresh the fields and the list view UserProfiles_LoadFields(userBeingEdited); itemBeingEdited.Refresh(); //UserProfileListViewItem lvi = new UserProfileListViewItem(userBeingEdited); //lvUserProfiles.Items.Add(lvi); //lvi.Selected = true; //lvUserProfiles.Items.Remove(itemBeingEdited); foreach (UserProfileListViewItem item in lvUserProfiles.Items) { bool isDefault = (item.UserProfile.UniqueId == ZAMsettings.Settings.DefaultUserProfile); if (item.UserProfile.Default != isDefault) { item.UserProfile.Default = isDefault; item.Refresh(); } } lvUserProfiles.EndUpdate(); } catch (Exception ex) { MessageBox.Show("Exception occurred: " + ex.ToString(), "Error saving User Profile", MessageBoxButtons.OK, MessageBoxIcon.Warning); errorOccurred = true; } finally { EditingUserProfiles = false; } } }
private void btnStatsEdit_Click(object sender, EventArgs e) { ZAMsettings.BeginCachedConfiguration(); EditingCollectors = true; }
private void btnStatsSave_Click(object sender, EventArgs e) { bool errorOccurred = false; // this should not happen if (lvCollectors.SelectedItems.Count < 1) { ZAMsettings.RollbackCachedConfiguration(); EditingCollectors = false; return; } CollectorListViewItem itemBeingEdited = (CollectorListViewItem)lvCollectors.SelectedItems[0]; Collector collectorBeingEdited = itemBeingEdited.Collector; errorOccurred = (errorOccurred || ValidateStatistics(rbAvgHide)); errorOccurred = (errorOccurred || ValidateStatistics(rbAvgWatts)); errorOccurred = (errorOccurred || ValidateStatistics(rbAvgWkg)); errorOccurred = (errorOccurred || ValidateStatistics(rbAvgMaxHide)); errorOccurred = (errorOccurred || ValidateStatistics(rbAvgMaxWatts)); errorOccurred = (errorOccurred || ValidateStatistics(rbAvgMaxWkg)); errorOccurred = (errorOccurred || ValidateStatistics(rbFtpHide)); errorOccurred = (errorOccurred || ValidateStatistics(rbFtpWatts)); errorOccurred = (errorOccurred || ValidateStatistics(rbFtpWkg)); if (!errorOccurred) { try { // Add or Update the Collector dictionary in the configuration. ZAMsettings.Settings.UpsertCollector(collectorBeingEdited); ZAMsettings.CommitCachedConfiguration(); lvCollectors.BeginUpdate(); // Refresh the fields and the list view Collectors_LoadFields(collectorBeingEdited); itemBeingEdited.Refresh(); //CollectorListViewItem lvi = new CollectorListViewItem(collectorBeingEdited); //lvCollectors.Items.Add(lvi); //lvi.Selected = true; //lvCollectors.Items.Remove(itemBeingEdited); lvCollectors.EndUpdate(); } catch (Exception ex) { MessageBox.Show("Exception occurred: " + ex.ToString(), "Error saving Collector", MessageBoxButtons.OK, MessageBoxIcon.Warning); errorOccurred = true; } finally { EditingCollectors = false; } } }
/// <summary> /// Call this from the ListView's Resize event handler /// </summary> /// <param name="listView"></param> protected static void HideHorizontalScrollBar(ListView listView) { listView.Scrollable = true; ZAMsettings.ShowScrollBar(listView.Handle, 0, false); }
public static void Initialize(ILoggerFactory loggerFactory, ZPMonitorService zpMonitorService) { if (_initialized) { return; } _loggerFactory = loggerFactory; _logger = loggerFactory.CreateLogger <ZAMsettings>(); ZPMonitorService = zpMonitorService; JObject parsedJson = null; bool userFileExists = false; try { try { // Try to load user .json file settings string jsonStr = File.ReadAllText(FileName); parsedJson = JObject.Parse(jsonStr); userFileExists = true; _logger.LogInformation($"Configuration cached from user settings file {FileName}."); } catch (FileNotFoundException) { // User .json file not found. Try to load default .json file settings string jsonStr = File.ReadAllText(FileNameDefault); parsedJson = JObject.Parse(jsonStr); _logger.LogInformation($"Configuration cached from default settings file {FileNameDefault}. User settings file {FileName} not found."); } // Configuration has been loaded and .json is good. Now deserialize into the settings objects. _committedJsonStr = parsedJson.ToString(); _committedZAMsettings = JsonConvert.DeserializeObject <ZAMsettings>(_committedJsonStr); // this could throw if settings don't match the .json _committedZAMsettings.m_readOnly = true; // Set current user according to default selection. This value is not persisted in json file. _committedZAMsettings.CurrentUserProfile = _committedZAMsettings.DefaultUserProfile; _initialized = true; if (userFileExists) { if (!Settings.Collectors.ContainsKey("6 min")) { BeginCachedConfiguration(); Collector c = new Collector() { Name = "6 min", DurationDesc = "SixMinute", DurationSecs = 360, FieldAvgDesc = "Watts", FieldAvgMaxDesc = "Wkg", FieldFtpDesc = "Hidden" }; Settings.Collectors.Add("6 min", c); CommitCachedConfiguration(); } } } catch (Exception ex) { throw new ApplicationException($"Exception occurred while trying to load configuration.", ex); } // This version would first read the default json settings file, and merge the user json settings file into it. // Problem is things like UserProfiles would suddenly have Collectors from the default showing up as selected by the user. //try //{ // string defaultJsonStr = File.ReadAllText(FileNameDefault); // JObject defaultJson = JObject.Parse(defaultJsonStr); // try // { // string userJsonStr = File.ReadAllText(FileName); // JObject userJson = JObject.Parse(userJsonStr); // defaultJson.Merge(userJson, new JsonMergeSettings // { // // union array values together to avoid duplicates // MergeArrayHandling = MergeArrayHandling.Union // }); // _logger.LogInformation($"Configuration cached from default settings file {FileNameDefault} and merged with user settings file {FileName}."); // } // catch (FileNotFoundException) // { // // this is okay as defaults will be used // _logger.LogInformation($"Configuration cached from default settings file {FileNameDefault}. User settings file {FileName} not found."); // } // _committedJsonStr = defaultJson.ToString(); // _committedZAMsettings = JsonConvert.DeserializeObject<ZAMsettings>(_committedJsonStr); // _committedZAMsettings.m_readOnly = true; // // Set current user according to default selection. This value is not persisted in json file. // _committedZAMsettings.CurrentUserProfile = _committedZAMsettings.DefaultUserProfile; // _initialized = true; //} //catch (Exception ex) //{ // throw new ApplicationException($"Exception occurred trying to load configuration from file: {FileName}", ex); //} }
public static void Initialize(ILoggerFactory loggerFactory) { if (_initialized) { return; } _logger = loggerFactory.CreateLogger <ZAMsettings>(); JObject parsedJson = null; try { try { // Try to load user .json file settings string jsonStr = File.ReadAllText(FileName); parsedJson = JObject.Parse(jsonStr); _logger.LogInformation($"Configuration cached from user settings file {FileName}."); } catch (FileNotFoundException) { // User .json file not found. Try to load default .json file settings string jsonStr = File.ReadAllText(FileNameDefault); parsedJson = JObject.Parse(jsonStr); _logger.LogInformation($"Configuration cached from default settings file {FileNameDefault}. User settings file {FileName} not found."); } // Configuration has been loaded and .json is good. Now deserialize into the settings objects. _committedJsonStr = parsedJson.ToString(); _committedZAMsettings = JsonConvert.DeserializeObject <ZAMsettings>(_committedJsonStr); // this could throw if settings don't match the .json _committedZAMsettings.m_readOnly = true; // Set current user according to default selection. This value is not persisted in json file. _committedZAMsettings.CurrentUserProfile = _committedZAMsettings.DefaultUserProfile; _initialized = true; } catch (Exception ex) { throw new ApplicationException($"Exception occurred while trying to load configuration.", ex); } // This version would first read the default json settings file, and merge the user json settings file into it. // Problem is things like UserProfiles would suddenly have Collectors from the default showing up as selected by the user. //try //{ // string defaultJsonStr = File.ReadAllText(FileNameDefault); // JObject defaultJson = JObject.Parse(defaultJsonStr); // try // { // string userJsonStr = File.ReadAllText(FileName); // JObject userJson = JObject.Parse(userJsonStr); // defaultJson.Merge(userJson, new JsonMergeSettings // { // // union array values together to avoid duplicates // MergeArrayHandling = MergeArrayHandling.Union // }); // _logger.LogInformation($"Configuration cached from default settings file {FileNameDefault} and merged with user settings file {FileName}."); // } // catch (FileNotFoundException) // { // // this is okay as defaults will be used // _logger.LogInformation($"Configuration cached from default settings file {FileNameDefault}. User settings file {FileName} not found."); // } // _committedJsonStr = defaultJson.ToString(); // _committedZAMsettings = JsonConvert.DeserializeObject<ZAMsettings>(_committedJsonStr); // _committedZAMsettings.m_readOnly = true; // // Set current user according to default selection. This value is not persisted in json file. // _committedZAMsettings.CurrentUserProfile = _committedZAMsettings.DefaultUserProfile; // _initialized = true; //} //catch (Exception ex) //{ // throw new ApplicationException($"Exception occurred trying to load configuration from file: {FileName}", ex); //} }
private void btnEditProfile_Click(object sender, EventArgs e) { ZAMsettings.BeginCachedConfiguration(); EditingUserProfiles = true; }