public void TestInitialise()
        {
            _ClassFactorySnapshot = Factory.TakeSnapshot();
            _RuntimeEnvironment = TestUtilities.CreateMockSingleton<IRuntimeEnvironment>();

            _Implementation = new Configuration();
        }
        public void TestInitialise()
        {
            _OriginalFactory = Factory.TakeSnapshot();

            _ConfigurationStorage = TestUtilities.CreateMockSingleton<IConfigurationStorage>();
            _Configuration = new Configuration();
            _ConfigurationStorage.Setup(cs => cs.Load()).Returns(_Configuration);

            _Log = TestUtilities.CreateMockSingleton<ILog>();
            _HeartbeatService = TestUtilities.CreateMockSingleton<IHeartbeatService>();
            _WebServer = new Mock<IWebServer>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
            _AutoConfigWebServer = TestUtilities.CreateMockSingleton<IAutoConfigWebServer>();
            _AutoConfigWebServer.Setup(s => s.WebServer).Returns(_WebServer.Object);
            _UPnpManager = new Mock<IUniversalPlugAndPlayManager>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
            _NewVersionChecker = TestUtilities.CreateMockSingleton<INewVersionChecker>();
            _HeartbeatTick = new EventRecorder<EventArgs>();
            _BaseStationAircraftList = new Mock<IBaseStationAircraftList>();
            _PluginManager = TestUtilities.CreateMockSingleton<IPluginManager>();
            _RebroadcastServerManager = TestUtilities.CreateMockSingleton<IRebroadcastServerManager>();

            _SelfConfiguringListener = TestUtilities.CreateMockSingleton<IAutoConfigListener>();
            _Listener = new Mock<IListener>(MockBehavior.Default) { DefaultValue = DefaultValue.Mock };
            _SelfConfiguringListener.Setup(r => r.Listener).Returns(_Listener.Object);

            _Presenter = Factory.Singleton.Resolve<IMainPresenter>();

            _Provider = new Mock<IMainPresenterProvider>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
            _Provider.Setup(p => p.UtcNow).Returns(DateTime.UtcNow);
            _Presenter.Provider = _Provider.Object;

            _View = new Mock<IMainView>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
        }
        public void TestInitialise()
        {
            _OriginalClassFactory = Factory.TakeSnapshot();
            _RuntimeEnvironment = TestUtilities.CreateMockSingleton<IRuntimeEnvironment>();

            _ConfigurationStorage = TestUtilities.CreateMockSingleton<IConfigurationStorage>();
            _Configuration = new Configuration();
            _ConfigurationStorage.Setup(s => s.Load()).Returns(_Configuration);

            _CreateDatabaseFileName = Path.Combine(TestContext.TestDeploymentDir, "CreatedDatabase.sqb");
            if(File.Exists(_CreateDatabaseFileName)) File.Delete(_CreateDatabaseFileName);

            _EmptyDatabaseFileName = Path.Combine(TestContext.TestDeploymentDir, "TestCopyBaseStation.sqb");
            File.Copy(Path.Combine(TestContext.TestDeploymentDir, "BaseStation.sqb"), _EmptyDatabaseFileName, true);

            _Database = Factory.Singleton.Resolve<IBaseStationDatabase>();
            _Database.FileName = _EmptyDatabaseFileName;

            _Provider = new Mock<IBaseStationDatabaseProvider>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
            _Database.Provider = _Provider.Object;
            _Provider.Setup(p => p.UtcNow).Returns(DateTime.UtcNow);

            _ConnectionStringBuilder = new SQLiteConnectionStringBuilder() { DataSource = _EmptyDatabaseFileName };

            _Criteria = new SearchBaseStationCriteria() {
                FromDate = DateTime.MinValue,
                ToDate = DateTime.MaxValue,
            };

            _FileNameChangingEvent = new EventRecorder<EventArgs>();
            _FileNameChangedEvent = new EventRecorder<EventArgs>();
        }
        public void TestInitialise()
        {
            _ClassFactorySnapshot = Factory.TakeSnapshot();

            _RuntimeEnvironment = TestUtilities.CreateMockSingleton<IRuntimeEnvironment>();
            _RuntimeEnvironment.Setup(r => r.IsMono).Returns(false);

            _ConfigurationStorage = TestUtilities.CreateMockSingleton<IConfigurationStorage>();
            _Configuration = new Configuration();
            _ConfigurationStorage.Setup(r => r.Load()).Returns(_Configuration);
            _ConfigurationStorage.Setup(r => r.Folder).Returns(Path.Combine(TestContext.TestDeploymentDir, "StandingDataTest"));

            _Implementation = Factory.Singleton.Resolve<IStandingDataManager>();

            _Provider = new Mock<IStandingDataManagerProvider>();
            _Implementation.Provider = _Provider.Object;

            _FileExists = new Dictionary<string,bool>();
            _FileExists.Add(DatabaseFileName, true);
            _FileExists.Add(FlightNumberCoverageFileName, true);
            _Provider.Setup(p => p.FileExists(It.IsAny<string>())).Returns((string fileName) => {
                return _FileExists[Path.GetFileName(fileName).ToUpper()];
            });

            _ReadAllLines = new Dictionary<string,List<string>>();
            _ReadAllLines.Add(FlightNumberCoverageFileName, new List<string>());
            _Provider.Setup(p => p.ReadAllLines(It.IsAny<string>())).Returns((string fileName) => {
                return _ReadAllLines[Path.GetFileName(fileName).ToUpper()].ToArray();
            });

            _ReadAllLines[FlightNumberCoverageFileName].Add("A,B,C,D,E");
            _ReadAllLines[FlightNumberCoverageFileName].Add("2001-02-01,2002-12-31,1000,X,X");
        }
        public void TestInitialise()
        {
            _ClassFactorySnapshot = Factory.TakeSnapshot();

            _DirectoryCache = TestUtilities.CreateMockImplementation<IDirectoryCache>();
            _Configuration = new Configuration();
            _ConfigurationStorage = TestUtilities.CreateMockSingleton<IConfigurationStorage>();
            _ConfigurationStorage.Setup(s => s.Load()).Returns(_Configuration);

            _AutoConfig = Factory.Singleton.Resolve<IAutoConfigPictureFolderCache>();
        }
        public void TestInitialise()
        {
            _BackgroundException = null;

            _ClassFactorySnapshot = Factory.TakeSnapshot();

            _RuntimeEnvironment = TestUtilities.CreateMockSingleton<IRuntimeEnvironment>();
            _RuntimeEnvironment.Setup(r => r.IsTest).Returns(true);

            _ConfigurationStorage = TestUtilities.CreateMockSingleton<IConfigurationStorage>();
            _Configuration = new Configuration();
            _ConfigurationStorage.Setup(m => m.Load()).Returns(_Configuration);

            _AircraftPictureManager = TestUtilities.CreateMockSingleton<IAircraftPictureManager>();
            _HeartbeatService = TestUtilities.CreateMockSingleton<IHeartbeatService>();
            _AutoConfigPictureFolderCache = TestUtilities.CreateMockSingleton<IAutoConfigPictureFolderCache>();
            _PictureDirectoryCache = new Mock<IDirectoryCache>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
            _AutoConfigPictureFolderCache.Setup(a => a.DirectoryCache).Returns(_PictureDirectoryCache.Object);

            _AircraftList = Factory.Singleton.Resolve<IBaseStationAircraftList>();
            _AircraftList.ExceptionCaught += AircraftListExceptionCaughtHandler;

            _Provider = new Mock<IBaseStationAircraftListProvider>().SetupAllProperties();
            _Provider.Setup(m => m.UtcNow).Returns(DateTime.UtcNow);

            _Port30003Listener = new Mock<IListener>().SetupAllProperties();

            _BaseStationDatabase = new Mock<IBaseStationDatabase>().SetupAllProperties();
            _StandingDataManager = TestUtilities.CreateMockSingleton<IStandingDataManager>();

            _AircraftList.Provider = _Provider.Object;
            _AircraftList.Listener = _Port30003Listener.Object;
            _AircraftList.BaseStationDatabase = _BaseStationDatabase.Object;
            _AircraftList.StandingDataManager = _StandingDataManager.Object;

            _BaseStationMessage = new BaseStationMessage();
            _BaseStationMessage.MessageType = BaseStationMessageType.Transmission;
            _BaseStationMessage.Icao24 = "4008F6";
            _BaseStationMessageEventArgs = new BaseStationMessageEventArgs(_BaseStationMessage);

            _BaseStationAircraft = new BaseStationAircraft();
            _BaseStationDatabase.Setup(m => m.GetAircraftByCode("4008F6")).Returns(_BaseStationAircraft);

            _Heathrow = new Airport() { IcaoCode = "EGLL", IataCode = "LHR", Name = "Heathrow", Country = "UK", };
            _JohnFKennedy = new Airport() { IcaoCode = "KJFK", IataCode = "JFK", Country = "USA", };
            _Helsinki = new Airport() { IataCode = "HEL", };
            _Boston = new Airport() { IcaoCode = "KBOS", };
            _Route = new Route() { From = _Heathrow, To = _JohnFKennedy, Stopovers = { _Helsinki }, };

            _ExceptionCaughtEvent = new EventRecorder<EventArgs<Exception>>();
            _CountChangedEvent = new EventRecorder<EventArgs>();
        }
        public void TestInitialise()
        {
            _ClassFactorySnapshot = Factory.TakeSnapshot();
            _RuntimeEnvironment = TestUtilities.CreateMockSingleton<IRuntimeEnvironment>();

            _Database = TestUtilities.CreateMockImplementation<IBaseStationDatabase>();

            _ConfigurationStorage = TestUtilities.CreateMockSingleton<IConfigurationStorage>();
            _Configuration = new Configuration();
            _ConfigurationStorage.Setup(s => s.Load()).Returns(_Configuration);

            _AutoConfigDatabase = Factory.Singleton.Resolve<IAutoConfigBaseStationDatabase>();
        }
        public void TestInitialise()
        {
            _OriginalClassFactory = Factory.TakeSnapshot();

            _ConfigurationStorage = TestUtilities.CreateMockSingleton<IConfigurationStorage>();
            _Configuration = new Configuration();
            _ConfigurationStorage.Setup(c => c.Load()).Returns(_Configuration);

            _DirectoryCache = new Mock<IDirectoryCache>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();

            _CacheCleared = new EventRecorder<EventArgs>();

            _PictureManager = Factory.Singleton.Resolve<IAircraftPictureManager>();
        }
        public void TestInitialise()
        {
            _ClassFactorySnapshot = Factory.TakeSnapshot();

            _FlightSimulatorX = TestUtilities.CreateMockImplementation<IFlightSimulatorX>();
            _FlightSimulatorX.Setup(fsx => fsx.IsInstalled).Returns(true);

            _ConfigurationStorage = TestUtilities.CreateMockSingleton<IConfigurationStorage>();
            _Configuration = new Configuration();
            _ConfigurationStorage.Setup(c => c.Load()).Returns(_Configuration);

            _Log = TestUtilities.CreateMockSingleton<ILog>();

            _Presenter = Factory.Singleton.Resolve<IFlightSimulatorXPresenter>();

            _Provider = new Mock<IFlightSimulatorXPresenterProvider>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
            _Provider.Setup(p => p.UtcNow).Returns(DateTime.UtcNow);
            _LimitTimedInvokeCallbacks = 1;
            int callbacks = 0;
            _Provider.Setup(p => p.TimedInvokeOnBackgroundThread(It.IsAny<Action>(), It.IsAny<int>())).Callback((Action callback, int milliseconds) => {
                if(callbacks++ < _LimitTimedInvokeCallbacks) callback();
            });
            _Presenter.Provider = _Provider.Object;

            _SelectedAircraft = new Mock<IAircraft>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties().Object;
            _View = new Mock<IFlightSimulatorXView>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
            _View.Setup(v => v.CanBeRefreshed).Returns(true);
            _View.Setup(v => v.SelectedRealAircraft).Returns(_SelectedAircraft);

            _BaseStationAircraftList = new Mock<IBaseStationAircraftList>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
            _FlightSimulatorAircraftList = new Mock<ISimpleAircraftList>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();

            long trash1, trash2;

            _RealAircraftList = new List<IAircraft>();
            _BaseStationAircraftList.Setup(b => b.TakeSnapshot(out trash1, out trash2)).Returns(_RealAircraftList);

            _FSXAircraftList = new List<IAircraft>();
            var syncLock = new object();
            _FlightSimulatorAircraftList.Setup(f => f.Aircraft).Returns(_FSXAircraftList);
            _FlightSimulatorAircraftList.Setup(f => f.ListSyncLock).Returns(syncLock);

            _WebServer = new Mock<IWebServer>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();

            _Presenter.BaseStationAircraftList = _BaseStationAircraftList.Object;
            _Presenter.FlightSimulatorAircraftList = _FlightSimulatorAircraftList.Object;
            _Presenter.WebServer = _WebServer.Object;
        }
        public void TestInitialise()
        {
            _ClassFactorySnapshot = Factory.TakeSnapshot();

            _ConfigurationStorage = TestUtilities.CreateMockSingleton<IConfigurationStorage>();
            _Configuration = new Configuration();
            _ConfigurationStorage.Setup(c => c.Load()).Returns(_Configuration);

            _AutoConfigListener = TestUtilities.CreateMockSingleton<IAutoConfigListener>();
            _AutoConfigListener.Setup(r => r.Listener).Returns((IListener)null);
            _AutoConfigListener.Setup(r => r.Initialise()).Callback(() => { _AutoConfigListener.Setup(r => r.Listener).Returns(_Listener.Object); });

            _Log = TestUtilities.CreateMockSingleton<ILog>();
            _HearbeatService = TestUtilities.CreateMockSingleton<IHeartbeatService>();
            _StandingDataManager = TestUtilities.CreateMockSingleton<IStandingDataManager>();
            _Listener = new Mock<IListener>(MockBehavior.Default) { DefaultValue = DefaultValue.Mock };
            _BaseStationAircraftList = TestUtilities.CreateMockImplementation<IBaseStationAircraftList>();
            _AutoConfigWebServer = TestUtilities.CreateMockSingleton<IAutoConfigWebServer>();
            _WebServer = new Mock<IWebServer>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
            _AutoConfigWebServer.Setup(s => s.WebServer).Returns(_WebServer.Object);
            _WebSite = TestUtilities.CreateMockImplementation<IWebSite>();
            _FlightSimulatorXAircraftList = TestUtilities.CreateMockImplementation<ISimpleAircraftList>();
            _UniversalPlugAndPlayManager = TestUtilities.CreateMockImplementation<IUniversalPlugAndPlayManager>();
            _ConnectionLogger = TestUtilities.CreateMockSingleton<IConnectionLogger>();
            _LogDatabase = TestUtilities.CreateMockSingleton<ILogDatabase>();
            _BackgroundDataDownloader = TestUtilities.CreateMockSingleton<IBackgroundDataDownloader>();
            _PluginManager = TestUtilities.CreateMockSingleton<IPluginManager>();
            _ApplicationInformation = TestUtilities.CreateMockImplementation<IApplicationInformation>();
            _AutoConfigPictureFolderCache = TestUtilities.CreateMockSingleton<IAutoConfigPictureFolderCache>();
            _RebroadcastServerManager = TestUtilities.CreateMockSingleton<IRebroadcastServerManager>();
            _Statistics = TestUtilities.CreateMockSingleton<IStatistics>();

            _BackgroundExceptionEvent = new EventRecorder<EventArgs<Exception>>();

            _BaseStationDatabase = new Mock<IBaseStationDatabase>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
            _AutoConfigBaseStationDatabase = TestUtilities.CreateMockSingleton<IAutoConfigBaseStationDatabase>();
            _AutoConfigBaseStationDatabase.Setup(a => a.Database).Returns(_BaseStationDatabase.Object);
            _BaseStationDatabase.Setup(d => d.FileName).Returns("x");
            _BaseStationDatabase.Setup(d => d.TestConnection()).Returns(true);

            _Provider = new Mock<ISplashPresenterProvider>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
            _Provider.Setup(p => p.FolderExists(It.IsAny<string>())).Returns(true);

            _Presenter = Factory.Singleton.Resolve<ISplashPresenter>();
            _Presenter.Provider = _Provider.Object;

            _View = new Mock<ISplashView>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
        }
        public void TestInitialise()
        {
            _ClassFactorySnapshot = Factory.TakeSnapshot();

            _WebServer = TestUtilities.CreateMockImplementation<IWebServer>();
            _RuntimeEnvironment = TestUtilities.CreateMockSingleton<IRuntimeEnvironment>();
            _ExternalIPAddressService = TestUtilities.CreateMockSingleton<IExternalIPAddressService>();
            _HeartbeatService = TestUtilities.CreateMockSingleton<IHeartbeatService>();
            _Log = TestUtilities.CreateMockSingleton<ILog>();
            _Configuration = new Configuration();
            _ConfigurationStorage = TestUtilities.CreateMockSingleton<IConfigurationStorage>();
            _ConfigurationStorage.Setup(s => s.Load()).Returns(_Configuration);
            _InstallerSettingsStorage = TestUtilities.CreateMockImplementation<IInstallerSettingsStorage>();
            _InstallerSettings = new InstallerSettings();
            _InstallerSettingsStorage.Setup(s => s.Load()).Returns(_InstallerSettings);

            _AutoConfigWebServer = Factory.Singleton.Resolve<IAutoConfigWebServer>();
        }
        public void TestInitialise()
        {
            _ClassFactorySnapshot = Factory.TakeSnapshot();

            _HeartbeatService = TestUtilities.CreateMockSingleton<IHeartbeatService>();
            _RuntimeEnvironment = TestUtilities.CreateMockSingleton<IRuntimeEnvironment>();
            _StandingDataUpdater = TestUtilities.CreateMockImplementation<IStandingDataUpdater>();
            _StandingDataManager = TestUtilities.CreateMockSingleton<IStandingDataManager>();
            _Log = TestUtilities.CreateMockSingleton<ILog>();
            _ConfigurationStorage = TestUtilities.CreateMockSingleton<IConfigurationStorage>();
            _Configuration = new Configuration();
            _Configuration.FlightRouteSettings.AutoUpdateEnabled = true;
            _ConfigurationStorage.Setup(c => c.Load()).Returns(_Configuration);

            _BackgroundDataDownloader = Factory.Singleton.Resolve<IBackgroundDataDownloader>();
            _Provider = new Mock<IBackgroundDataDownloaderProvider>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
            _BackgroundDataDownloader.Provider = _Provider.Object;
        }
        public void TestInitialise()
        {
            _OriginalFactory = Factory.TakeSnapshot();

            _RuntimeEnvironment = TestUtilities.CreateMockSingleton<IRuntimeEnvironment>();
            _ConfigurationStorage = TestUtilities.CreateMockSingleton<IConfigurationStorage>();
            _Configuration = new Configuration();
            _ConfigurationStorage.Setup(c => c.Load()).Returns(_Configuration);

            _PortMappings = new List<IPortMapping>();
            _Manager = Factory.Singleton.Resolve<IUniversalPlugAndPlayManager>();
            _Provider = new Mock<IUniversalPlugAndPlayManagerProvider>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
            _Provider.Setup(p => p.GetPortMappings()).Returns(_PortMappings);
            _Manager.Provider = _Provider.Object;

            _WebServer = new Mock<IWebServer>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
            _Manager.WebServer = _WebServer.Object;

            _StateChangedEvent = new EventRecorder<EventArgs>();
        }
        public void TestInitialise()
        {
            _AutoConfigMessageListener = TestUtilities.CreateMockSingleton<IAutoConfigListener>();
            _Listener = TestUtilities.CreateMockImplementation<IListener>();
            _AutoConfigMessageListener.Setup(r => r.Listener).Returns(_Listener.Object);

            _StartupParameters = new PluginStartupParameters(null, null, null, null);
            _ClassFactorySnapshot = Factory.TakeSnapshot();
            _PluginSettingsStorage = TestUtilities.CreateMockSingleton<IPluginSettingsStorage>();
            _PluginSettings = new PluginSettings();
            _PluginSettingsStorage.Setup(s => s.Load()).Returns(_PluginSettings);
            _RuntimeEnvironment = TestUtilities.CreateMockSingleton<IRuntimeEnvironment>();
            _RuntimeEnvironment.Setup(r => r.IsTest).Returns(true);

            _BaseStationDatabase = new Mock<IBaseStationDatabase>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
            _BaseStationDatabase.Object.FileName = "fn";
            _AutoConfigBaseStationDatabase = TestUtilities.CreateMockSingleton<IAutoConfigBaseStationDatabase>();
            _AutoConfigBaseStationDatabase.Setup(a => a.Database).Returns(_BaseStationDatabase.Object);

            _BaseStationDatabase.Setup(d => d.GetLocations()).Returns(new List<BaseStationLocation>() { new BaseStationLocation() { LocationID = 9821 } } );
            SetDBHistory(true);

            _StandingDataManager = TestUtilities.CreateMockSingleton<IStandingDataManager>();
            _HeartbeatService = TestUtilities.CreateMockSingleton<IHeartbeatService>();
            _Log = TestUtilities.CreateMockSingleton<ILog>();

            _ConfigurationStorage = TestUtilities.CreateMockSingleton<IConfigurationStorage>();
            _Configuration = new Configuration();
            _ConfigurationStorage.Setup(c => c.Load()).Returns(_Configuration);

            _StatusChangedEvent = new EventRecorder<EventArgs>();

            _Plugin = new PluginNS.Plugin();
            _Provider = new Mock<PluginNS.IPluginProvider>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
            _Provider.Setup(p => p.FileExists(It.IsAny<string>())).Returns(true);
            _Provider.Setup(p => p.LocalNow).Returns(new DateTime(2001, 2, 3, 4, 5, 6));
            _Provider.Setup(p => p.FileSize(It.IsAny<string>())).Returns(1000000L);
            _OptionsView = new Mock<PluginNS.IOptionsView>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
            _Provider.Setup(p => p.CreateOptionsView()).Returns(_OptionsView.Object);
            _Plugin.Provider = _Provider.Object;
        }
        public void TestInitialise()
        {
            _OriginalClassFactory = Factory.TakeSnapshot();

            // Note that the class factory will keep returning the SAME instance for all of the
            // interfaces for which CreateMockImplementation is called... this means we can't
            // comprehensively test the handling of multiple servers. Creating a wrapper using
            // Mock<> is kind of possible but gets tricky around events, and in any case it's
            // rather defeating the point of using a mocking framework.
            _Server = TestUtilities.CreateMockImplementation<IRebroadcastServer>();
            _Listener = TestUtilities.CreateMockImplementation<IListener>();
            _BroadcastProvider = TestUtilities.CreateMockImplementation<IBroadcastProvider>();

            _ConfigurationStorage = TestUtilities.CreateMockSingleton<IConfigurationStorage>();
            _Configuration = new Configuration();
            _ConfigurationStorage.Setup(r => r.Load()).Returns(_Configuration);
            _RebroadcastSettings = new RebroadcastSettings() { Name = "A", Enabled = true, Port = 1000, Format = RebroadcastFormat.Passthrough };
            _Configuration.RebroadcastSettings.Add(_RebroadcastSettings);

            _Manager = Factory.Singleton.Resolve<IRebroadcastServerManager>();
            _Manager.Listener = _Listener.Object;
        }
        private void Check_ResetToDefaultClicked_Copies_Default_Configuration_To_UI(List<ConfigurationProperty> configurationProperties)
        {
            var worksheet = new ExcelWorksheetData(TestContext);

            if(worksheet.String("Direction") != "ConfigToUI") {
                var name = worksheet.String("Name");
                var configurationProperty = configurationProperties.Where(r => r.Name == name).Single();
                var configurationValue = configurationProperty.GetSpreadsheetConfig(worksheet, "ConfigValue");

                var defaultConfig = new Configuration();
                _ConfigurationStorage.Setup(r => r.Save(_Configuration)).Callback(() => {
                    Assert.AreEqual(configurationProperty.GetConfig(defaultConfig), configurationProperty.GetConfig(_Configuration), name);
                });

                configurationProperty.SetConfig(_Configuration, configurationValue);
                _Presenter.Initialise(_View.Object);
                _View.Raise(v => v.ResetToDefaultsClicked += null, EventArgs.Empty);
                _View.Raise(v => v.SaveClicked += null, EventArgs.Empty);

                _ConfigurationStorage.Verify(c => c.Save(_Configuration), Times.Once(), name);
            }
        }
 /// <summary>
 /// See base class.
 /// </summary>
 /// <param name="configuration"></param>
 protected override void DoLoadConfiguration(Configuration configuration)
 {
     base.DoLoadConfiguration(configuration);
     _InternetClientCanRequestClosestAircraft = configuration.InternetClientSettings.AllowInternetProximityGadgets;
 }
        public void TestInitialise()
        {
            _ClassFactorySnapshot = Factory.TakeSnapshot();

            _ConfigurationStorage = TestUtilities.CreateMockSingleton<IConfigurationStorage>();
            _Configuration = new Configuration();
            _ConfigurationStorage.Setup(c => c.Load()).Returns(_Configuration);

            _Presenter = Factory.Singleton.Resolve<IOptionsPresenter>();
            _Provider = new Mock<IOptionsPresenterProvider>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
            _Provider.Setup(p => p.FileExists(It.IsAny<string>())).Returns(true);
            _Provider.Setup(p => p.FolderExists(It.IsAny<string>())).Returns(true);
            _Provider.Setup(p => p.TestNetworkConnection(It.IsAny<string>(), It.IsAny<int>())).Returns((Exception)null);
            _Provider.Setup(p => p.TestSerialConnection(It.IsAny<string>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<StopBits>(), It.IsAny<Parity>(), It.IsAny<Handshake>())).Returns((Exception)null);
            _Presenter.Provider = _Provider.Object;
            _View = new Mock<IOptionsView>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
        }
        private IListener StartListener(Configuration configuration)
        {
            _View.ReportProgress(Strings.SplashScreenConnectingToBaseStation);

            var autoConfigListener = Factory.Singleton.Resolve<IAutoConfigListener>().Singleton;
            autoConfigListener.Initialise();
            if(BackgroundThreadExceptionHandler != null) {
                autoConfigListener.ExceptionCaught += BackgroundThreadExceptionHandler;
            }

            try {
                autoConfigListener.Listener.Connect(configuration.BaseStationSettings.AutoReconnectAtStartup);
            } catch(Exception ex) {
                Factory.Singleton.Resolve<ILog>().Singleton.WriteLine("Could not connect to data feed: {0}", ex.ToString());
                _View.ReportProblem(String.Format(Strings.CannotConnectToBaseStationFull, ex.Message), Strings.CannotConnectToBaseStationTitle, false);
            }

            return autoConfigListener.Listener;
        }
        public void ConfigurationStorage_Erase_Raises_ConfigurationChanged()
        {
            var configuration = new Configuration() { AudioSettings = new AudioSettings() { VoiceName = "This was saved" } };
            _Implementation.Save(configuration);

            _Implementation.ConfigurationChanged += _ConfigurationChangedEvent.Handler;
            _ConfigurationChangedEvent.EventRaised += (object sender, EventArgs args) => { Assert.AreEqual(null, _Implementation.Load().AudioSettings.VoiceName); };

            _Implementation.Erase();

            Assert.AreEqual(1, _ConfigurationChangedEvent.CallCount);
            Assert.IsNotNull(_ConfigurationChangedEvent.Args);
            Assert.AreSame(_Implementation, _ConfigurationChangedEvent.Sender);
        }
        public void ConfigurationStorage_Resets_IgnoreBadMessages()
        {
            // The connection flag "IgnoreBadMessages" has been retired. If the user has the value set to false in their
            // configuration then Load overrides this and forces it to true. It is no longer presented to the user.
            var configuration = new Configuration();
            configuration.BaseStationSettings.IgnoreBadMessages = false;
            _Implementation.Save(configuration);

            var readBack = _Implementation.Load();
            Assert.IsTrue(readBack.BaseStationSettings.IgnoreBadMessages);
        }
        private Configuration CreateKnownConfiguration()
        {
            var result = new Configuration();
            foreach(PropertyInfo property in result.GetType().GetProperties()) {
                switch(property.Name) {
                    case "BaseStationSettings":     result.BaseStationSettings = new BaseStationSettings() {
                                                        Address = "Aa",
                                                        Port = 65535,
                                                        DataSource = DataSource.Sbs3,
                                                        DatabaseFileName = "Bb",
                                                        OperatorFlagsFolder = "Cc",
                                                        SilhouettesFolder = "Ee",
                                                        OutlinesFolder = "Ff",
                                                        DisplayTimeoutSeconds = 120,
                                                        PicturesFolder = "Pp",
                                                        IgnoreBadMessages = true,
                                                        ConnectionType = ConnectionType.COM,
                                                        ComPort = "/dev/com4",
                                                        BaudRate = 2400,
                                                        DataBits = 7,
                                                        StopBits = StopBits.OnePointFive,
                                                        Parity = Parity.Space,
                                                        Handshake = Handshake.XOnXOff,
                                                        StartupText = "startup",
                                                        ShutdownText = "shutdown",
                                                        AutoReconnectAtStartup = true,
                                                        TrackingTimeoutSeconds = 3600,
                                                    }; break;
                    case "FlightRouteSettings":     result.FlightRouteSettings = new FlightRouteSettings() {
                                                        AutoUpdateEnabled = true,
                                                    }; break;
                    case "WebServerSettings":       result.WebServerSettings = new WebServerSettings() {
                                                        AuthenticationScheme = AuthenticationSchemes.Basic,
                                                        BasicAuthenticationUser = "******",
                                                        BasicAuthenticationPasswordHash = new Hash("Funk to funky"),
                                                        EnableUPnp = true,
                                                        UPnpPort = 8181,
                                                        IsOnlyInternetServerOnLan = false,
                                                        AutoStartUPnP = true,
                                                    }; break;
                    case "GoogleMapSettings":       result.GoogleMapSettings = new GoogleMapSettings() {
                                                        InitialMapLatitude = -12.123456,
                                                        InitialMapLongitude = 120.123987,
                                                        InitialMapType = "HYBRID",
                                                        InitialMapZoom = 7,
                                                        InitialRefreshSeconds = 9,
                                                        MinimumRefreshSeconds = 8,
                                                        ShortTrailLengthSeconds = 400,
                                                        InitialDistanceUnit = DistanceUnit.Kilometres,
                                                        InitialHeightUnit = HeightUnit.Metres,
                                                        InitialSpeedUnit = SpeedUnit.MilesPerHour,
                                                        PreferIataAirportCodes = true,
                                                    }; break;
                    case "VersionCheckSettings":    result.VersionCheckSettings = new VersionCheckSettings() {
                                                        CheckAutomatically = false,
                                                        CheckPeriodDays = 12,
                                                    }; break;
                    case "InternetClientSettings":  result.InternetClientSettings = new InternetClientSettings() {
                                                        CanRunReports = true,
                                                        CanShowPinText = true,
                                                        CanShowPictures = true,
                                                        TimeoutMinutes = 15,
                                                        CanPlayAudio = true,
                                                        AllowInternetProximityGadgets = true,
                                                        CanSubmitRoutes = true,
                                                    }; break;
                    case "AudioSettings":           result.AudioSettings = new AudioSettings() {
                                                        Enabled = false,
                                                        VoiceName = "Male Voice",
                                                        VoiceRate = 2,
                                                    }; break;
                    case "RawDecodingSettings":     result.RawDecodingSettings = new RawDecodingSettings() {
                                                        AcceptableAirborneSpeed = 17.25,
                                                        AcceptableAirSurfaceTransitionSpeed = 19.75,
                                                        AcceptableSurfaceSpeed = 21.25,
                                                        AirborneGlobalPositionLimit = 19,
                                                        FastSurfaceGlobalPositionLimit = 17,
                                                        SlowSurfaceGlobalPositionLimit = 12,
                                                        IgnoreCallsignsInBds20 = true,
                                                        IgnoreMilitaryExtendedSquitter = true,
                                                        ReceiverLocationId = 7,
                                                        ReceiverRange = 400,
                                                        SuppressReceiverRangeCheck = false,
                                                        UseLocalDecodeForInitialPosition = true,
                                                        AcceptIcaoInNonPICount = 20,
                                                        AcceptIcaoInNonPISeconds = 21,
                                                        AcceptIcaoInPI0Count = 7,
                                                        AcceptIcaoInPI0Seconds = 42,
                                                    }; break;
                    case "ReceiverLocations":       result.ReceiverLocations.Clear();
                                                    result.ReceiverLocations.AddRange(new ReceiverLocation[] {
                                                        new ReceiverLocation() {
                                                            UniqueId = 74,
                                                            Name = "Home",
                                                            Latitude = 51.234,
                                                            Longitude = -0.642,
                                                        },
                                                        new ReceiverLocation() {
                                                            UniqueId = 90,
                                                            Name = "Away",
                                                            Latitude = 17.123,
                                                            Longitude = 12.456,
                                                        },
                                                    });
                                                    break;
                    case "RebroadcastSettings":     result.RebroadcastSettings.Clear();
                                                    result.RebroadcastSettings.AddRange(new RebroadcastSettings[] {
                                                        new RebroadcastSettings() {
                                                            Enabled = true,
                                                            Format = RebroadcastFormat.Passthrough,
                                                            Name = "Server 1",
                                                            Port = 10000,
                                                        },
                                                        new RebroadcastSettings() {
                                                            Enabled = false,
                                                            Format = RebroadcastFormat.Port30003,
                                                            Name = "Server 2",
                                                            Port = 10001,
                                                        },
                                                    });
                                                    break;
                    default:                        throw new NotImplementedException();
                }
            }

            return result;
        }
        /// <summary>
        /// Creates and configures the object to translate Mode-S messages into BaseStation messages.
        /// </summary>
        /// <param name="config"></param>
        /// <param name="isNewSource"></param>
        /// <returns></returns>
        private IRawMessageTranslator DetermineRawMessageTranslator(Configuration config, bool isNewSource)
        {
            var result = isNewSource || Listener.RawMessageTranslator == null ? Factory.Singleton.Resolve<IRawMessageTranslator>() : Listener.RawMessageTranslator;

            // There's every chance that the translator is in use while we're changing the properties here. In practise I
            // don't think it's going to make a huge difference, and people won't be changing this stuff very often anyway,
            // but I might have to add some shared locking code here. I'd like to avoid it if I can though.

            var receiverLocation = config.ReceiverLocation(config.RawDecodingSettings.ReceiverLocationId);
            result.ReceiverLocation = receiverLocation == null ? null : new GlobalCoordinate(receiverLocation.Latitude, receiverLocation.Longitude);

            result.AcceptIcaoInNonPICount                       = config.RawDecodingSettings.AcceptIcaoInNonPICount;
            result.AcceptIcaoInNonPIMilliseconds                = config.RawDecodingSettings.AcceptIcaoInNonPISeconds * 1000;
            result.AcceptIcaoInPI0Count                         = config.RawDecodingSettings.AcceptIcaoInPI0Count;
            result.AcceptIcaoInPI0Milliseconds                  = config.RawDecodingSettings.AcceptIcaoInPI0Seconds * 1000;
            result.GlobalDecodeAirborneThresholdMilliseconds    = config.RawDecodingSettings.AirborneGlobalPositionLimit * 1000;
            result.GlobalDecodeFastSurfaceThresholdMilliseconds = config.RawDecodingSettings.FastSurfaceGlobalPositionLimit * 1000;
            result.GlobalDecodeSlowSurfaceThresholdMilliseconds = config.RawDecodingSettings.SlowSurfaceGlobalPositionLimit * 1000;
            result.IgnoreMilitaryExtendedSquitter               = config.RawDecodingSettings.IgnoreMilitaryExtendedSquitter;
            result.LocalDecodeMaxSpeedAirborne                  = config.RawDecodingSettings.AcceptableAirborneSpeed;
            result.LocalDecodeMaxSpeedSurface                   = config.RawDecodingSettings.AcceptableSurfaceSpeed;
            result.LocalDecodeMaxSpeedTransition                = config.RawDecodingSettings.AcceptableAirSurfaceTransitionSpeed;
            result.ReceiverRangeKilometres                      = config.RawDecodingSettings.ReceiverRange;
            result.SuppressCallsignsFromBds20                   = config.RawDecodingSettings.IgnoreCallsignsInBds20;
            result.SuppressReceiverRangeCheck                   = config.RawDecodingSettings.SuppressReceiverRangeCheck;
            result.TrackingTimeoutSeconds                       = config.BaseStationSettings.TrackingTimeoutSeconds;
            result.UseLocalDecodeForInitialPosition             = config.RawDecodingSettings.UseLocalDecodeForInitialPosition;

            return result;
        }
        /// <summary>
        /// Creates and configures the provider to use to connect to the data feed.
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        private IListenerProvider DetermineListenerProvider(Configuration config)
        {
            IListenerProvider result = Listener.Provider;

            var settings = config.BaseStationSettings;
            switch(config.BaseStationSettings.ConnectionType) {
                case ConnectionType.COM:
                    var existingSerialProvider = result as ISerialListenerProvider;
                    if(existingSerialProvider == null || existingSerialProvider.BaudRate != settings.BaudRate || existingSerialProvider.ComPort != settings.ComPort ||
                       existingSerialProvider.DataBits != settings.DataBits || existingSerialProvider.Handshake != settings.Handshake ||
                       existingSerialProvider.Parity != settings.Parity || existingSerialProvider.ShutdownText != settings.ShutdownText ||
                       existingSerialProvider.StartupText != settings.StartupText || existingSerialProvider.StopBits != settings.StopBits) {
                        var serialProvider = Factory.Singleton.Resolve<ISerialListenerProvider>();
                        serialProvider.BaudRate = settings.BaudRate;
                        serialProvider.ComPort = settings.ComPort;
                        serialProvider.DataBits = settings.DataBits;
                        serialProvider.Handshake = settings.Handshake;
                        serialProvider.Parity = settings.Parity;
                        serialProvider.ShutdownText = settings.ShutdownText;
                        serialProvider.StartupText = settings.StartupText;
                        serialProvider.StopBits = settings.StopBits;
                        result = serialProvider;
                    }
                    break;
                case ConnectionType.TCP:
                    var existingTcpProvider = result as ITcpListenerProvider;
                    if(existingTcpProvider == null || existingTcpProvider.Address != settings.Address || existingTcpProvider.Port != settings.Port) {
                        var tcpProvider = Factory.Singleton.Resolve<ITcpListenerProvider>();
                        tcpProvider.Address = settings.Address;
                        tcpProvider.Port = settings.Port;
                        result = tcpProvider;
                    }
                    break;
                default:
                    throw new NotImplementedException();
            }

            return result;
        }
        /// <summary>
        /// Creates and configures the message bytes extractor to use to get the message bytes out of the feed.
        /// </summary>
        /// <param name="config"></param>
        /// <returns></returns>
        private IMessageBytesExtractor DetermineBytesExtractor(Configuration config)
        {
            IMessageBytesExtractor result = Listener.BytesExtractor;

            switch(config.BaseStationSettings.DataSource) {
                case DataSource.Beast:      if(result == null || !(result is IBeastMessageBytesExtractor)) result = Factory.Singleton.Resolve<IBeastMessageBytesExtractor>(); break;
                case DataSource.Port30003:  if(result == null || !(result is IPort30003MessageBytesExtractor)) result = Factory.Singleton.Resolve<IPort30003MessageBytesExtractor>(); break;
                case DataSource.Sbs3:       if(result == null || !(result is ISbs3MessageBytesExtractor)) result = Factory.Singleton.Resolve<ISbs3MessageBytesExtractor>(); break;
                default:                    throw new NotImplementedException();
            }

            return result;
        }
        private void InitialiseUniversalPlugAndPlay(Configuration configuration)
        {
            _View.ReportProgress(Strings.SplashScreenInitialisingUPnPManager);

            var manager = Factory.Singleton.Resolve<IUniversalPlugAndPlayManager>();
            manager.WebServer = Factory.Singleton.Resolve<IAutoConfigWebServer>().Singleton.WebServer;
            manager.Initialise();

            if(configuration.WebServerSettings.AutoStartUPnP) {
                _View.ReportProgress(Strings.SplashScreenStartingUPnP);
                manager.PutServerOntoInternet();
            }

            _View.UPnpManager = manager;
        }
        private Configuration LoadConfiguration(IConfigurationStorage configurationStorage)
        {
            Configuration result = new Configuration();

            _View.ReportProgress(Strings.SplashScreenLoadingConfiguration);

            try {
                result = configurationStorage.Load();
            } catch(Exception ex) {
                string message = String.Format(Strings.InvalidConfigurationFileFull, ex.Message, configurationStorage.Folder);
                if(_View.YesNoPrompt(message, Strings.InvalidConfigurationFileTitle, true)) {
                    configurationStorage.Save(new Configuration());
                    _View.ReportProblem(Strings.DefaultSettingsSavedFull, Strings.DefaultSettingsSavedTitle, true);
                }
                Provider.AbortApplication();
            }

            return result;
        }
        /// <summary>
        /// See interface docs.
        /// </summary>
        /// <returns></returns>
        public Configuration Load()
        {
            var result = new Configuration();

            if(File.Exists(FileName)) {
                using(StreamReader stream = new StreamReader(FileName, Encoding.UTF8)) {
                    XmlSerializer serialiser = new XmlSerializer(typeof(Configuration));
                    result = (Configuration)serialiser.Deserialize(stream);
                }
            }

            // Force retired settings to their expected values
            result.BaseStationSettings.IgnoreBadMessages = true;

            return result;
        }
        /// <summary>
        /// See interface docs.
        /// </summary>
        /// <param name="configuration"></param>
        public void Save(Configuration configuration)
        {
            if(!Directory.Exists(Provider.Folder)) Directory.CreateDirectory(Provider.Folder);

            using(StreamWriter stream = new StreamWriter(FileName, false, Encoding.UTF8)) {
                XmlSerializer serialiser = new XmlSerializer(typeof(Configuration));
                serialiser.Serialize(stream, configuration);
            }

            OnConfigurationChanged(EventArgs.Empty);
        }
        public void TestInitialise()
        {
            _OriginalClassFactory = Factory.TakeSnapshot();

            _ConfigurationStorage = TestUtilities.CreateMockSingleton<IConfigurationStorage>();
            _Configuration = new Configuration();
            _Configuration.ReceiverLocations.AddRange(_DefaultReceiverLocations);
            _ConfigurationStorage.Setup(r => r.Load()).Returns(_Configuration);

            _Statistics = TestUtilities.CreateMockSingleton<IStatistics>();

            _Listener = TestUtilities.CreateMockImplementation<IListener>();
            _Listener.Setup(r => r.Provider).Returns((IListenerProvider)null);
            _Listener.Setup(r => r.BytesExtractor).Returns((IMessageBytesExtractor)null);
            _Listener.Setup(r => r.RawMessageTranslator).Returns((IRawMessageTranslator)null);
            _Listener.Setup(r => r.ChangeSource(It.IsAny<IListenerProvider>(), It.IsAny<IMessageBytesExtractor>(), It.IsAny<IRawMessageTranslator>(), It.IsAny<bool>()))
                     .Callback((IListenerProvider provider, IMessageBytesExtractor extractor, IRawMessageTranslator translator, bool reconnect) => {
                _Listener.Setup(r => r.Provider).Returns(provider);
                _Listener.Setup(r => r.BytesExtractor).Returns(extractor);
                _Listener.Setup(r => r.RawMessageTranslator).Returns(translator);
            });

            CreateNewListenerChildObjectInstances();

            _AutoConfigListener = Factory.Singleton.Resolve<IAutoConfigListener>();
        }