public void Setup()
        {
            _container?.Dispose();
            TestUtils.DeleteTestChainData();
            _eventData = new Dictionary <UInt256, ByteString>();
            var containerBuilder = new SimpleInjectorContainerBuilder(new ConfigManager(
                                                                          Path.Join(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "config.json"),
                                                                          new RunOptions()
                                                                          ));

            containerBuilder.RegisterModule <BlockchainModule>();
            containerBuilder.RegisterModule <ConfigModule>();
            containerBuilder.RegisterModule <StorageModule>();
            _container          = containerBuilder.Build();
            _blockManager       = _container.Resolve <IBlockManager>();
            _transactionBuilder = _container.Resolve <ITransactionBuilder>();
            _stateManager       = _container.Resolve <IStateManager>();
            _wallet             = _container.Resolve <IPrivateWallet>();
            _transactionPool    = _container.Resolve <ITransactionPool>();
            _configManager      = _container.Resolve <IConfigManager>();
            // set chainId from config
            if (TransactionUtils.ChainId(false) == 0)
            {
                var chainId    = _configManager.GetConfig <NetworkConfig>("network")?.ChainId;
                var newChainId = _configManager.GetConfig <NetworkConfig>("network")?.NewChainId;
                TransactionUtils.SetChainId((int)chainId !, (int)newChainId !);
                HardforkHeights.SetHardforkHeights(_configManager.GetConfig <HardforkConfig>("hardfork") ?? throw new InvalidOperationException());
                StakingContract.Initialize(_configManager.GetConfig <NetworkConfig>("network") ?? throw new InvalidOperationException());
                CycleDuration = StakingContract.CycleDuration;
            }
        }
Beispiel #2
0
        public void Setup()
        {
            _container?.Dispose();
            TestUtils.DeleteTestChainData();

            var containerBuilder = new SimpleInjectorContainerBuilder(new ConfigManager(
                                                                          Path.Join(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "config.json"),
                                                                          new RunOptions()
                                                                          ));

            containerBuilder.RegisterModule <ConfigModule>();

            _container = containerBuilder.Build();

            _configManager = _container.Resolve <IConfigManager>();
            if (TransactionUtils.ChainId(false) == 0)
            {
                var chainId    = _configManager.GetConfig <NetworkConfig>("network")?.ChainId;
                var newChainId = _configManager.GetConfig <NetworkConfig>("network")?.NewChainId;
                TransactionUtils.SetChainId((int)chainId !, (int)newChainId !);
                HardforkHeights.SetHardforkHeights(_configManager.GetConfig <HardforkConfig>("hardfork") ?? throw new InvalidOperationException());
            }

            Console.WriteLine($"old chain id: {TransactionUtils.ChainId(false)}, new chain id: {TransactionUtils.ChainId(true)}");
        }
        public void Setup()
        {
            _container?.Dispose();
            TestUtils.DeleteTestChainData();
            var containerBuilder = new SimpleInjectorContainerBuilder(new ConfigManager(
                                                                          Path.Join(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "config.json"),
                                                                          new RunOptions()
                                                                          ));

            containerBuilder.RegisterModule <BlockchainModule>();
            containerBuilder.RegisterModule <ConfigModule>();
            containerBuilder.RegisterModule <StorageModule>();
            _container       = containerBuilder.Build();
            _blockManager    = _container.Resolve <IBlockManager>();
            _stateManager    = _container.Resolve <IStateManager>();
            _wallet          = _container.Resolve <IPrivateWallet>();
            _transactionPool = _container.Resolve <ITransactionPool>();
            _configManager   = _container.Resolve <IConfigManager>();
            // set chainId from config
            if (TransactionUtils.ChainId(false) == 0)
            {
                var chainId    = _configManager.GetConfig <NetworkConfig>("network")?.ChainId;
                var newChainId = _configManager.GetConfig <NetworkConfig>("network")?.ChainId;
                TransactionUtils.SetChainId((int)chainId !, (int)newChainId !);
                HardforkHeights.SetHardforkHeights(_configManager.GetConfig <HardforkConfig>("hardfork") ?? throw new InvalidOperationException());
            }
            _validatorStatusManager = new ValidatorStatusManager(
                _transactionPool, _container.Resolve <ITransactionSigner>(), _container.Resolve <ITransactionBuilder>(),
                _wallet, _stateManager, _container.Resolve <IValidatorAttendanceRepository>(),
                _container.Resolve <ISystemContractReader>()
                );
        }
Beispiel #4
0
        public void TestForNetwork(string?networkName = null)
        {
            BuildForNetwork(networkName);
            var network = _configManager.GetConfig <NetworkConfig>("network") ??
                          throw new ApplicationException("No network section in config");

            Assert.That(network.NewChainId != null);
            var oldChainId = _configManager.GetConfig <NetworkConfig>("network")?.ChainId;
            var newChainId = _configManager.GetConfig <NetworkConfig>("network")?.NewChainId;

            SetChainId(oldChainId !.Value, newChainId !.Value);

            Logger.LogInformation($"old chain id: {ChainId(false)}, new chain id: {ChainId(true)}");
            Assert.AreEqual(ChainId(false), oldChainId);
            Assert.AreEqual(ChainId(true), newChainId);

            int noOfTest = 10;

            for (var it = 0; it < noOfTest; it++)
            {
                var key = GetRandomKey();
                VerifyPublicKey(key.PublicKey);
                SignMessageAndVerify(key);
            }
        }
Beispiel #5
0
        protected override bool ExecuteAction(object source, IActionParam param)
        {
            //System.Console.Out.WriteLine("CPTZAction.ExecuteAction: Action=" + Config.Desc);
            CLocalSystem.WriteDebugLog(string.Format("CPTZAction({0}[{1}]).ExecuteAction", Config.Desc, Name));

            IVisionAlarm alarm = source as IVisionAlarm;

            if (alarm != null)
            {
                //System.Console.Out.WriteLine("CPTZAction.ExecuteAction: Sender=" + alarm.Sender + ", AlarmID=" + alarm.ID);
                CLocalSystem.WriteDebugLog(string.Format("CPTZAction({0}).ExecuteAction: Sender={1}, AlarmID={2}, ActionParam={3}", Name, alarm.Sender, alarm.ID, param.Name));

                //alarm.OnTransactAlarm += new TransactAlarm(DoTransactAlarm);

                if (System.Threading.Monitor.TryEnter(mPTZLockObj))
                {
                    try
                    {
                        IVisionMonitorConfig vmc = alarm.Monitor.Config as IVisionMonitorConfig;
                        if (vmc != null)
                        {
                            IConfigManager <IVideoSourceConfig> vsConfigManager = vmc.SystemContext.VideoSourceConfigManager;
                            if (vsConfigManager != null)
                            {
                                CVideoSourceConfig vcConfig = vsConfigManager.GetConfig(vmc.VisionParamConfig.VSName) as CVideoSourceConfig;
                                if (vcConfig != null)
                                {
                                    string vsName = vcConfig.StrValue("PTZVSName");

                                    CLocalSystem.WriteDebugLog(string.Format("CPTZAction({0}).ExecuteAction: PTZVSName={1}", Config.Desc, vsName));

                                    if (!vsName.Equals(""))
                                    {
                                        IVideoSourceConfig ptzvsConfig = vsConfigManager.GetConfig(vsName);
                                        if (ptzvsConfig != null)
                                        {
                                            return(StartPTZ(ptzvsConfig, alarm.AreaIndex));
                                        }
                                    }
                                }
                            }
                        }
                    }
                    finally
                    {
                        System.Threading.Monitor.Exit(mPTZLockObj);
                    }
                }
            }
            return(false);
        }
Beispiel #6
0
        private void OnLocationUpdated(object sender, LocationUpdatedEventArgs args)
        {
            if (args.Location.Equals(GeoPoint.Empty))
            {
                return;
            }

            if (this.Area == null)
            {
                var config = _configManager.GetConfig();

                var location = config.Areas
                               .Select(x => new Tuple <double, Area>(
                                           args.Location.DistanceTo(new GeoPoint(x.Latitude, x.Longitude)),
                                           x))
                               .OrderBy(x => x.Item1)
                               .First();

                if (location.Item1 <= AppConsts.MaxDistanceFromCityCenter)
                {
                    this.Area         = location.Item2;
                    this.DetectedArea = true;
                }
                else if (!_unknownAreaReported)
                {
                    this.RaiseAreaLocatingFailedEvent();
                    _unknownAreaReported = true;
                }
            }

            this.RaiseLocationChangedEvent();
        }
Beispiel #7
0
            public void Execute(params string[] args)
            {
                logger.Trace("Выполняется команда {}...", this.GetType().Name);
                var subscriptions = configManager.GetConfig().Subscriptions;
                int shown_cnt     = 0;

                foreach (var url in subscriptions)
                {
                    var feed = storage.LoadFromStorage(url);
                    if (feed == null)
                    {
                        continue;
                    }
                    else
                    {
                        shown_cnt++;
                        feedPrinter.PrintFeed(feed);
                    }
                }
                if (shown_cnt == 0)
                {
                    Console.WriteLine("Нечего отображать.");
                    return;
                }
                logger.Trace("Выполнение команды {} завершено.", this.GetType().Name);
            }
        private async void OnProPresenterFound(object sender, ProPresenterInstancesChangedEventArgs args)
        {
            var instances = args.Instances;

            if (instances.Any() && !BridgeOn)
            {
                var cts = new CancellationTokenSource();

                if (instances.Count() == 1)
                {
                    await _proPresenterDa.Connect(instances.First().Name, cts.Token);
                }
                else
                {
                    var configInstanceName = _configManager.GetConfig(ConfigKeys.ProPresenterName);

                    var instance = instances.FirstOrDefault(x => x.Name == configInstanceName);

                    if (instance != null)
                    {
                        await _proPresenterDa.Connect(configInstanceName, cts.Token);
                    }
                }

                if (!_proPresenterDa.Connected)
                {
                    cts.Cancel();
                    _logger.LogInfo("Could not connect");
                    BridgeOn = false;
                }
            }
        }
Beispiel #9
0
        public MetricsService(IRocksDbContext context, IConfigManager config)
        {
            _context = context;
            var rpcConfig = config.GetConfig <RpcConfig>("rpc") ?? RpcConfig.Default;

            _server = new MetricServer(hostname: "*", port: rpcConfig.MetricsPort);
        }
Beispiel #10
0
        public BlockManager(
            ITransactionManager transactionManager,
            IGenesisBuilder genesisBuilder,
            IMultisigVerifier multisigVerifier,
            IStateManager stateManager,
            ISnapshotIndexRepository snapshotIndexRepository,
            IConfigManager configManager,
            ILocalTransactionRepository localTransactionRepository
            )
        {
            _transactionManager         = transactionManager;
            _genesisBuilder             = genesisBuilder;
            _multisigVerifier           = multisigVerifier;
            _stateManager               = stateManager;
            _snapshotIndexRepository    = snapshotIndexRepository;
            _configManager              = configManager;
            _localTransactionRepository = localTransactionRepository;
            _transactionManager.OnSystemContractInvoked += TransactionManagerOnSystemContractInvoked;

            var cacheConfig = _configManager.GetConfig <CacheConfig>("cache");

            if (cacheConfig != null && cacheConfig.BlockHeight != null && cacheConfig.BlockHeight.SizeLimit != null)
            {
                _blockSizeLimit = cacheConfig.BlockHeight.SizeLimit.Value;
            }

            _heightCache      = new Dictionary <ulong, Block?>(_blockSizeLimit);
            _heightCacheQueue = new Queue <ulong>(_blockSizeLimit);
        }
        public ProPresenterDataAgent(IConfigManager configManager, ILogger logger)
        {
            _instances = new List <ProPresenterInstance>();

            _serviceBrowser = new ServiceBrowser();

            _serviceBrowser.ServiceAdded   += OnServiceAdded;
            _serviceBrowser.ServiceRemoved += OnServiceRemoved;

            _logger = logger;
            try
            {
                _password = configManager.GetConfig(ConfigKeys.ProPresenterPassword);
            }
            catch (Exception e)
            {
                _password = "";
                _logger.LogError("Error reading configuration file", e);

                configManager.EditConfig(ConfigKeys.ProPresenterPassword, _password);
                configManager.SaveConfig();
            }

            Connected     = false;
            Connecting    = false;
            StopListening = false;
        }
Beispiel #12
0
        private void Init()
        {
            Mapper.Initialize(cfg =>
            {
                cfg.AddProfile <ModelProfile>();
            });

            _configManager = new ConfigManager();
            _config        = _configManager.GetConfig();

            string connectionString = _config.DatabaseSource;

            IHeatMapRepository  heatMapRepository  = new HeatMapRepository(connectionString);
            ICountingRepository countingRepository = new CountingRepository(connectionString);

            _dataManager = new DataManager(heatMapRepository, countingRepository);

            IReportRepository reportRepository = new ReportRepository(connectionString);

            _reportManager = new ReportManager(reportRepository);

            ICameraRepository cameraRepository = new CameraRepository(connectionString);

            _cameraManager = new CameraManager(cameraRepository);
        }
Beispiel #13
0
        private void LoadConfig()
        {
            ConfigModel config = _configManager.GetConfig();

            ReportLocation = config.ExportConfig.Location;
            BufferLocation = config.DataConfig.Location;
        }
Beispiel #14
0
        public PrivateWallet(IConfigManager configManager)
        {
            var config = configManager.GetConfig <VaultConfig>("vault") ??
                         throw new Exception("No 'vault' section in config file");

            if (!(configManager.CommandLineOptions.WalletPath is null))
            {
                config.Path = configManager.CommandLineOptions.WalletPath;
            }

            if (config.Path is null || config.Password is null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            _walletPath = Path.IsPathRooted(config.Path) || config.Path.StartsWith("~/")
                ? config.Path
                : Path.Join(Path.GetDirectoryName(Path.GetFullPath(configManager.ConfigPath)), config.Path);

            _walletPassword = config.Password;
            _unlockEndTime  = 0;
            if (!File.Exists(_walletPath))
            {
                GenerateNewWallet(_walletPath, _walletPassword);
            }
            var needsSave = RestoreWallet(_walletPath, _walletPassword, out var keyPair, out var hubKey);

            EcdsaKeyPair  = keyPair;
            HubPrivateKey = hubKey;
            if (needsSave)
            {
                SaveWallet(_walletPath, _walletPassword);
            }
        }
        public void Setup()
        {
            _container?.Dispose();
            TestUtils.DeleteTestChainData();

            var containerBuilder = new SimpleInjectorContainerBuilder(new ConfigManager(
                                                                          Path.Join(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "config2.json"),
                                                                          new RunOptions()
                                                                          ));

            containerBuilder.RegisterModule <BlockchainModule>();
            containerBuilder.RegisterModule <ConfigModule>();
            containerBuilder.RegisterModule <StorageModule>();
            _container = containerBuilder.Build();


            _configManager        = _container.Resolve <IConfigManager>();
            _stateManager         = _container.Resolve <IStateManager>();
            _contractRegisterer   = _container.Resolve <IContractRegisterer>();
            _privateWallet        = _container.Resolve <IPrivateWallet>();
            _snapshotIndexer      = _container.Resolve <ISnapshotIndexRepository>();
            _systemContractReader = _container.Resolve <ISystemContractReader>();

            _transactionManager = _container.Resolve <ITransactionManager>();
            _transactionBuilder = _container.Resolve <ITransactionBuilder>();
            _transactionSigner  = _container.Resolve <ITransactionSigner>();
            _transactionPool    = _container.Resolve <ITransactionPool>();
            _blockManager       = _container.Resolve <IBlockManager>();

            // set chainId from config
            if (TransactionUtils.ChainId(false) == 0)
            {
                var chainId    = _configManager.GetConfig <NetworkConfig>("network")?.ChainId;
                var newChainId = _configManager.GetConfig <NetworkConfig>("network")?.ChainId;
                TransactionUtils.SetChainId((int)chainId !, (int)newChainId !);
                HardforkHeights.SetHardforkHeights(_configManager.GetConfig <HardforkConfig>("hardfork") ?? throw new InvalidOperationException());
            }
            ServiceBinder.BindService <GenericParameterAttributes>();

            _apiService = new AccountServiceWeb3(_stateManager, _snapshotIndexer, _contractRegisterer, _systemContractReader, _transactionPool);

            _transactionApiService = new TransactionServiceWeb3(_stateManager, _transactionManager, _transactionBuilder, _transactionSigner,
                                                                _transactionPool, _contractRegisterer, _privateWallet);

            _blockManager.TryBuildGenesisBlock();
        }
Beispiel #16
0
        public MapRouteStopsViewModel(IConfigManager configManager)
        {
            this.Stops = new ReadOnlyCollection <RouteStopMapViewModel>(_stops);
            _config    = configManager.GetConfig();

            this.LoadRouteStopsCommand  = new MvxCommand(this.LoadRouteStops, () => _liveDataProvider != null);
            this.SelectRouteStopCommand = new MvxCommand <string>(this.SelectRouteStop);
        }
Beispiel #17
0
        /// <summary>
        /// Get the config instance for the namespace. </summary>
        /// <param name="namespaceName"> the namespace of the config </param>
        /// <returns> config instance </returns>
        public Task <IConfig> GetConfig([NotNull] string namespaceName)
        {
            if (string.IsNullOrEmpty(namespaceName))
            {
                throw new ArgumentNullException(nameof(namespaceName));
            }

            return(_manager.GetConfig(namespaceName));
        }
Beispiel #18
0
            public void Execute(params string[] args)
            {
                logger.Trace("Выполняется команда {}...", this.GetType().Name);
                Config s = configManager.GetConfig();

                Console.WriteLine("Подписки: ");
                foreach (string url in s.Subscriptions)
                {
                    Console.WriteLine("    " + url);
                }
                logger.Trace("Выполнение команды {} завершено.", this.GetType().Name);
            }
Beispiel #19
0
        private void FillAreas()
        {
            var areaVMs = _configManager.GetConfig()
                          .Areas
                          .Select(a => new AreaViewModel(a, this[string.Format(AppConsts.AreaLocalizedNameStringKeyFormat, a.Id)]))
                          .ToList();

            foreach (var vm in areaVMs)
            {
                _areas.Add(vm);
            }
        }
Beispiel #20
0
        public BlockWithTransactions Build()
        {
            if (_genesisBlock != null)
            {
                return(_genesisBlock);
            }

            var genesisConfig = _configManager.GetConfig <GenesisConfig>("genesis") ??
                                throw new InvalidOperationException("No genesis config found");

            var fromAddress = UInt160Utils.Zero; // mint initial tokens from zero address
            var balances    = genesisConfig !.Balances
                              .OrderBy(x => x.Key)
                              .ToArray();
            var genesisTransactions = balances.Select((t, i) => new Transaction
            {
                From     = fromAddress,
                Nonce    = (ulong)i,
                Value    = Money.Parse(t.Value).ToUInt256(),
                To       = t.Key.HexToUInt160(),
                GasPrice = 0,
            })
                                      .Select(tx => new TransactionReceipt
            {
                Transaction = tx,
                Hash        = HardforkHeights.IsHardfork_9Active(0) ? tx.FullHash(SignatureUtils.ZeroNew, true) : tx.FullHash(SignatureUtils.ZeroOld, false),
                Signature   = HardforkHeights.IsHardfork_9Active(0) ? SignatureUtils.ZeroNew : SignatureUtils.ZeroOld,
            })
                                      .ToList();

            var txHashes = genesisTransactions.Select(tx => tx.Hash).ToArray();

            var header = new BlockHeader
            {
                PrevBlockHash = UInt256Utils.Zero,
                MerkleRoot    = MerkleTree.ComputeRoot(txHashes) ?? UInt256Utils.Zero,
                Index         = 0,
                StateHash     = UInt256Utils.Zero,
                Nonce         = GenesisConsensusData
            };

            var result = new Block
            {
                Hash = header.Keccak(),
                TransactionHashes = { txHashes },
                Header            = header
            };

            _genesisBlock = new BlockWithTransactions(result, genesisTransactions.ToArray());
            return(_genesisBlock);
        }
Beispiel #21
0
        public SetAreaViewModel(IConfigManager configManager, IAreaPositioningService locationService)
        {
            _locationService = locationService;

            var areaVMs = configManager.GetConfig()
                          .Areas
                          .Select(a => new AreaViewModel(a, this[string.Format(AppConsts.AreaLocalizedNameStringKeyFormat, a.Id)]))
                          .ToList();

            this.Areas = new ObservableCollection <AreaViewModel>(areaVMs);

            this.SelectAreaCommand = new MvxCommand <int>(this.SelectAreaManually);
            this.CancelCommand     = new MvxCommand(this.Cancel);
        }
Beispiel #22
0
        public VmixDataAgent(IConfigManager configManager, ILogger logger)
        {
            try
            {
                var ip   = configManager.GetConfig(ConfigKeys.VmixIp);
                var port = configManager.GetConfig(ConfigKeys.VmixPort);
                _inputNumber = configManager.GetConfig(ConfigKeys.VmixInputNumber);
                _baseAddress = new Uri($"http://{ip}:{port}");
            }
            catch (Exception e)
            {
                logger.LogError("Error while reading configuration file", e);

                const string ip   = "127.0.0.1";
                const string port = "8088";
                _inputNumber = "1";
                _baseAddress = new Uri($"http://{ip}:{port}");


                configManager.EditConfig(ConfigKeys.VmixIp, ip);
                configManager.EditConfig(ConfigKeys.VmixPort, port);
                configManager.EditConfig(ConfigKeys.VmixInputNumber, _inputNumber);
            }
        }
Beispiel #23
0
        public MapVehiclesViewModel(IMvxMessenger messenger, IConfigManager configManager)
        {
            _messenger             = messenger;
            _config                = configManager.GetConfig();
            _viewPortUpdateSubject = new Subject <VehiclesViewPortUpdate>();
            this.ViewportUpdate    = new Subject <VisibleVehiclesDelta>();

            _updateVehicleLocationsSubscriptionToken = _messenger.Subscribe <VehicleLocationsUpdateRequestMessage>(
                message => this.ForceVehicleLocationsUpdate());

            _subscription = _viewPortUpdateSubject.Throttle(TimeSpan.FromMilliseconds(200))
                            .Subscribe(this.UpdateVehiclesInTheViewPort);

            this.ForceVehicleLocationsUpdateCommand = new MvxCommand(this.ForceVehicleLocationsUpdate);
            this.SelectVehicleCommand = new MvxCommand <string>(this.SelectVehicle);
        }
Beispiel #24
0
        public LogConfiguration(IAppDirBuilder dirBuilder, IConfigManager configManager)
        {
            var config = configManager.GetConfig();

            try
            {
                logLevel = LogLevel.FromString(config.LogLevel);
            }
            catch
            {
                config.LogLevel = logLevel.Name;
                configManager.UpdateConfig(config);
            }
            logFolderPath = dirBuilder.GetLogDir();
            logFilePath   = Path.Combine(logFolderPath, "log.txt");
        }
Beispiel #25
0
        public void OnLoad()
        {
            File.WriteAllLines(@"C:\Temp\nitrolog.txt", new[] { DateTime.Now.ToString() });
            _configManager = new XmlFileConfigManager();
            _userSettings  = _configManager.GetConfig <UserSettings>() ?? new UserSettings {
                RuleProfiles = new List <RuleProfile>()
            };
            _cacheRules = _userSettings.RuleProfiles.SelectMany(p => p.Rules.Select(r => new CachingRule
            {
                Cache      = new MemoryCache(),
                ProfileId  = p.Id,
                FilterRule = r
            })).ToList();


            Action <string> clearCacheForId = (string id) => _cacheRules
                                              .Where(r => r.FilterRule.Id == id)
                                              .ToList()
                                              .ForEach(c => c.Cache.Clear());

            Action <string> clearCacheForProfile = (string id) => _cacheRules
                                                   .Where(r => r.ProfileId == id)
                                                   .ToList()
                                                   .ForEach(c => c.Cache.Clear());

            Action clearAllCache = () => _cacheRules
                                   .ForEach(c => c.Cache.Clear());



            var cacherPage = new TabPage("Nitro Cacher");


            Action <bool> toggleIcon = (enabled) =>
            {
                var key = enabled ? "NitroCacher.Enabled" : "NitroCacher.Disabled";
                cacherPage.ImageKey = key;
            };

            var cacherControl = new Home(_userSettings, clearCacheForId, clearCacheForProfile, clearAllCache, toggleIcon);

            cacherPage.Controls.Add(cacherControl);
            cacherControl.Dock = DockStyle.Fill;
            FiddlerApplication.UI.imglSessionIcons.Images.Add("NitroCacher.Enabled", enabledIconBase64.ToImage());
            FiddlerApplication.UI.imglSessionIcons.Images.Add("NitroCacher.Disabled", disabledIconBase64.ToImage());
            FiddlerApplication.UI.tabsViews.TabPages.Add(cacherPage);
        }
Beispiel #26
0
        public void UnlockWallet(bool unlock, int time = 100)
        {
            string password;

            if (unlock)
            {
                var config = _configManager.GetConfig <VaultConfig>("vault") ??
                             throw new Exception("No 'vault' section in config file");
                password = config.Password !;
                Assert.AreEqual(true, _privateWallet.Unlock(password, time));
            }
            else
            {
                password = "******";  // random password
                Assert.AreEqual(false, _privateWallet.Unlock(password, time));
            }
        }
Beispiel #27
0
        public MapViewModel(
            IBusTrackerLocationService locationService,
            ILiveDataProviderFactory providerFactory,
            IConfigManager configManager,
            IMvxMessenger messenger)
        {
            _providerFactory              = providerFactory;
            _configManager                = configManager;
            _messenger                    = messenger;
            _locationService              = locationService;
            _locationService.AreaChanged += (s, a) =>
            {
                this.DetectedArea = a.Detected;
                this.ChangeArea(a.Area, a.LastLocation);
            };

            _config = _configManager.GetConfig();

            this.MapRouteStopsViewModel = Mvx.IocConstruct <MapRouteStopsViewModel>();
            this.MapRouteStopsViewModel.RouteStopSelected += (s, a) => this.CenterMap(a.RouteStop.Location.Position);

            this.MapVehiclesViewModel = Mvx.IocConstruct <MapVehiclesViewModel>();

            this.SelectRouteStopCommand = new MvxCommand <string>(this.SelectRouteStop);
            this.SelectVehicleCommand   = new MvxCommand <string>(this.SelectVehicle);
            this.ClearSelectionCommand  = new MvxCommand(this.ClearSelection);
            this.UpdateMapCenterCommand = new MvxCommand <Tuple <GeoPoint, bool> >(tuple =>
            {
                if (tuple.Item2)
                {
                    this.MapCenter = tuple.Item1;
                }
                else
                {
                    _mapCenter = tuple.Item1;
                }
            });

            _routeStopInfoSubscriptionToken = _messenger.Subscribe <ShowRouteStopForecastOnMapMessage>(
                message => this.SelectRouteStopCommand.Execute(message.RouteStopId));

            _vehicleInfoSubscriptionToken = _messenger.Subscribe <ShowVehicleForecastOnMapMessage>(
                message => this.SelectVehicleCommand.Execute(message.VehicleId));
        }
Beispiel #28
0
            public void Execute(params string[] args)
            {
                logger.Trace("Выполняется команда {}...", this.GetType().Name);
                if (args.Length < 1)
                {
                    Console.WriteLine("Слишком мало параметров. Используйте help для справки.");
                    return;
                }
                Config config = configManager.GetConfig();

                try {
                    int num = Convert.ToInt32(args[0]);
                    config.Subscriptions.RemoveAt(num);
                }
                catch {
                    Console.WriteLine("Неверный индекс удаляемого канала.");
                }
                configManager.UpdateConfig(config);
                logger.Trace("Выполнение команды {} завершено.", this.GetType().Name);
            }
Beispiel #29
0
            public void Execute(params string[] args)
            {
                logger.Trace("Выполняется команда {}...", this.GetType().Name);
                Config config = configManager.GetConfig();

                foreach (var url in config.Subscriptions)
                {
                    System.Console.WriteLine("Загружаем из " + url);
                    var data = loader.Download(url);
                    if (data == null)
                    {
                        System.Console.WriteLine("    Не удалось загрузить канал.");
                    }
                    else
                    {
                        System.Console.WriteLine("    Загружен канал: " + data.Title.Text);
                        System.Console.WriteLine("    Загружено записей: " + data.Items.Count());
                        storage.SaveToStorage(url, data);
                    }
                }
                logger.Trace("Выполнение команды {} завершено.", this.GetType().Name);
            }
Beispiel #30
0
 /// <summary>
 /// Get the config instance for the namespace. </summary>
 /// <param name="namespaceName"> the namespace of the config </param>
 /// <returns> config instance </returns>
 public static IConfig GetConfig(String namespaceName)
 {
     return(s_configManager.GetConfig(namespaceName));
 }