ConfigurationData.cs 2.47 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace GazeWebSocketServer
{
    public class ConfigurationData
    {
        public string TrackerSerialNumber { get; private set; }
        public float TrackerFrequency { get; private set; }
14
        public float OutputFrequency { get; private set; }
15 16 17 18 19 20 21 22 23 24
        public int WebSocketPort { get; private set; }
        public string WebSocketEndpoint { get; private set; }
        public bool DebugFlag { get; private set; }

        public static ConfigurationData ParseToObject()
        {
            ConfigurationData result = new ConfigurationData
            {
                TrackerSerialNumber = ConfigurationManager.AppSettings["TrackerSerialNumber"],
                TrackerFrequency = float.Parse(ConfigurationManager.AppSettings["TrackerFrequency_Hz"]),
25
                OutputFrequency = float.Parse(ConfigurationManager.AppSettings["OutputFrequency_Hz"]),
26 27 28 29 30 31 32 33 34
                WebSocketPort = int.Parse(ConfigurationManager.AppSettings["WebSocketPort"]),
                WebSocketEndpoint = ConfigurationManager.AppSettings["WebSocketEndpoint"],
                DebugFlag = bool.Parse(ConfigurationManager.AppSettings["DebugFlag"])
            };
            return result;
        }

        public static void InitializeUnexistingWithDefaults()
        {
35
            InitializeSetting("TrackerSerialNumber", "TPSP1-");
36
            InitializeSetting("TrackerFrequency_Hz", "600");
37
            InitializeSetting("OutputFrequency_Hz", "60");
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
            InitializeSetting("WebSocketPort", "8001");
            InitializeSetting("WebSocketEndpoint", "/gaze");
            InitializeSetting("DebugFlag", "false");
        }

        private static void InitializeSetting(string key, string value)
        {
            try
            {
                var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var settings = configFile.AppSettings.Settings;
                if (settings[key] == null)
                {
                    settings.Add(key, value);
                }
                configFile.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
            }
            catch (ConfigurationErrorsException)
            {
                Console.WriteLine("Error writing app settings");
            }
        }
    }
}