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;
        }
Esempio n. 2
0
        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);
            }
        }
Esempio n. 3
0
        /// <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");
        }
Esempio n. 4
0
        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
        }
Esempio n. 5
0
        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;
        }
Esempio n. 6
0
        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);
            }
        }
Esempio n. 7
0
        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;
            }
        }
Esempio n. 9
0
        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());
        }
Esempio n. 10
0
        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
        }
Esempio n. 11
0
        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;
        }
Esempio n. 13
0
        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
        }
Esempio n. 14
0
        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
        }
Esempio n. 16
0
        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;
            }
        }
Esempio n. 18
0
        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;
 }
Esempio n. 21
0
        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;
                }
            }
        }
Esempio n. 24
0
        /// <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);
        }
Esempio n. 25
0
        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);
            //}
        }
Esempio n. 26
0
        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);
            //}
        }
Esempio n. 27
0
 private void btnEditProfile_Click(object sender, EventArgs e)
 {
     ZAMsettings.BeginCachedConfiguration();
     EditingUserProfiles = true;
 }