public TestsService(ILoadingProgressController loadingProgressController, IConfigSerializer configSerializer, ILoggingService loggingService, IFarmIntegrator farmIntegrator)
 {
     this.loadingProgressController = loadingProgressController;
     this.configSerializer          = configSerializer;
     this.loggingService            = loggingService;
     this.farmIntegrator            = farmIntegrator;
 }
示例#2
0
        public static Config GenerateDefault(IConfigSerializer configSerializer)
        {
            var result = Validate(new Config());

            configSerializer.SaveConfig(result);
            return(result);
        }
示例#3
0
 public void Save(IConfigSerializer serializer)
 {
     if (!string.IsNullOrWhiteSpace(_filePath))
     {
         Save(_filePath, serializer);
     }
 }
示例#4
0
        public static Config Load(Stream stream, IConfigSerializer serializer)
        {
            Config config;

            using (stream)
                config = serializer.Deserialize(stream);

            return(config);
        }
示例#5
0
 public TestsService(ILoadingProgressController loadingProgressController, IConfigSerializer configSerializer, ILoggingService loggingService, IMinioWorker minioWorker, INotificationService notificationService)
 {
     this.loadingProgressController = loadingProgressController;
     this.configSerializer          = configSerializer;
     this.loggingService            = loggingService;
     this.minioWorker         = minioWorker;
     this.notificationService = notificationService;
     platformProvider         = ServiceLocator.Current.GetInstance <IPlatformProvider>();
 }
示例#6
0
 public SettingsViewModel(IConfigSerializer configSerializer)
 {
     Title = "Settings";
     this.configSerializer = configSerializer;
     Config   = configSerializer.GetConfig();
     Commands = UICommand.GenerateFromMessageButton(MessageButton.OKCancel, new DialogService(), MessageResult.OK, MessageResult.Cancel);
     Commands.Where(c => c.IsDefault).Single().Command = new DelegateCommand(Save, () => !IsAnyRepositoryDownloading());
     Commands.Where(c => c.IsCancel).Single().Command  = new DelegateCommand(Cancel, () => !IsAnyRepositoryDownloading());
 }
示例#7
0
        internal IFeatureManager features;     //Used to access features exposed by other plugins, such as the steamcmdhelper from the SteamCMD plugin


        //ModuleMain is the entry point for a module, it's the first thing that gets called when AMP loads the module.
        public ModuleMain(ILogger log, IConfigSerializer config, SupportedOS currentPlatform, IRunningTasksManager taskManager, IFeatureManager features)
        {
            this.log      = log;
            taskmgr       = taskManager;
            this.config   = config;
            os            = currentPlatform;
            this.features = features;
            settings      = config.Load <FiveMConfig>(); //This will also automatically save your settings for you when the user changes them. You don't need to do anything
        }
示例#8
0
        /// <summary>
        /// Static configuration loader
        /// </summary>
        /// <param name="serializer"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        protected static TConfig Current(IConfigSerializer serializer, string fileName)
        {
            var serialized = LoadFromFile(fileName);

            if (string.IsNullOrEmpty(serialized))
            {
                return(default(TConfig));
            }
            return(serializer.DeserializeObject <TConfig>(serialized));
        }
 public SettingsViewModel(IConfigSerializer configSerializer)
 {
     Title             = "Settings";
     _dispatcher       = Dispatcher.CurrentDispatcher;
     _configSerializer = configSerializer;
     _platformProvider = ServiceLocator.Current.GetInstance <IPlatformProvider>();
     Config            = configSerializer.GetConfig();
     Commands          = UICommand.GenerateFromMessageButton(MessageButton.OKCancel, new DialogService(), MessageResult.OK, MessageResult.Cancel);
     Commands.Single(c => c.IsDefault).Command = new DelegateCommand(Save, AllowDialogButtons);
     Commands.Single(c => c.IsCancel).Command  = new DelegateCommand(Cancel, AllowDialogButtons);
 }
示例#10
0
        /// <summary>Save the given object into a file</summary>
        /// <param name="ConfigObject">The object to save</param>
        /// <param name="Filename">The filename the objects should get</param>
        /// <exception cref="ArgumentException" />
        /// <exception cref="ArgumentNullException" />
        /// <exception cref="ArgumentOutOfRangeException" />
        /// <exception cref="DirectoryNotFoundException" />
        /// <exception cref="FileNotFoundException" />
        /// <exception cref="IOException" />
        /// <exception cref="InvalidOperationException" />
        /// <exception cref="NotSupportedException" />
        /// <exception cref="PathTooLongException" />
        /// <exception cref="UnauthorizedAccessException" />
        /// <exception cref="System.Security.SecurityException" />
        public static void SaveConfig(Object ConfigObject, String Filename)
        {
            //Get file info on the file to save to
            String          Filepath = ConfigOptions.ConfigFolder + Filename + ConfigOptions.ConfigExtension;
            var             FI       = new FileInfo(Filepath);
            EventWaitHandle Lock     = ConfigLoader.GetLock(Filepath);

            //Check parent directory
            DirectoryInfo DI = FI.Directory;

            //Create if missing
            if (!DI.Exists)
            {
                DI.Create();
            }

            //Setup
            IConfigSerializer <Object> serializer = null;
            FileStream writer = null;

            Lock.WaitOne();
#if !DEBUG
            try {
#endif
            //Assign serializer and stream
            serializer = ConfigLoader._SerializerFactory.GetSerializer(ConfigObject.GetType());
            writer     = new FileStream(FI.FullName, FileMode.Create);

            //Serialize object
            serializer.Serialize(ConfigObject, writer);

            //Flush and close
            writer.Flush();
            writer.Close();
#if !DEBUG
        }
#pragma warning disable 168
        catch (Exception ex) {
#pragma warning restore 168
            //Close stream if open
            if (writer != null)
            {
                writer.Close();
            }

            ErrorSaving(Filepath, ex);
        }
#endif

            Lock.Set();
        }
示例#11
0
        /// <summary>
        /// Creates a new instance of <see cref="ConfigService"/>
        /// </summary>
        /// <param name="provider">The provider which will be used to load and store the configurations.</param>
        /// <param name="serializer">The serializer which will be used to serialize and deserialize the configurations.</param>
        public ConfigService(IConfigProvider provider, IConfigSerializer serializer)
        {
            if (provider == null)
            {
                throw new ArgumentNullException(nameof(provider));
            }
            if (serializer == null)
            {
                throw new ArgumentNullException(nameof(serializer));
            }

            this.provider   = provider;
            this.serializer = serializer;
        }
示例#12
0
        public static Config Load(string fileName, IConfigSerializer serializer)
        {
            Config config;

            if (File.Exists(fileName))
            {
                using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                    config = serializer.Deserialize(fs);
            }
            else
            {
                config = new Config();
            }

            config._filePath = fileName;
            return(config);
        }
示例#13
0
 public MainViewModel(INotificationService notificationService,
                      IRegionManager regionManager,
                      ILoggingService loggingService,
                      IFarmIntegrator farmIntegrator,
                      IConfigSerializer configSerializer,
                      ILoadingProgressController loadingProgressController,
                      ITestsService testsService,
                      IGitWorker gitWorker)
 {
     Dispatcher = Dispatcher.CurrentDispatcher;
     this.notificationService  = notificationService;
     this.regionManager        = regionManager;
     this.loggingService       = loggingService;
     this.farmIntegrator       = farmIntegrator;
     this.configSerializer     = configSerializer;
     LoadingProgressController = loadingProgressController;
     TestService = testsService;
     _GitWorker  = gitWorker;
     TestService.PropertyChanged    += TestService_PropertyChanged;
     loggingService.MessageReserved += OnLoggingMessageReserved;
     UpdateConfig();
 }
示例#14
0
 public MainViewModel(INotificationService notificationService,
                      ILoggingService loggingService,
                      IConfigSerializer configSerializer,
                      ILoadingProgressController loadingProgressController,
                      ITestsService testsService,
                      IGitWorker gitWorker,
                      IPlatformProvider platformProvider,
                      IActiveService isActiveService, ITestsService testService)
 {
     dispatcher = Dispatcher.CurrentDispatcher;
     this.notificationService  = notificationService;
     this.loggingService       = loggingService;
     this.configSerializer     = configSerializer;
     this.platformProvider     = platformProvider;
     this.isActiveService      = isActiveService;
     this.testService          = testService;
     this.gitWorker            = gitWorker;
     obsolescenceTracker       = new RepositoryObsolescenceTracker(this.gitWorker, () => _config.Repositories, NoticeRepositoryObsolescenceAsync);
     LoadingProgressController = loadingProgressController;
     testService = testsService;
     testService.PropertyChanged    += TestService_PropertyChanged;
     loggingService.MessageReserved += OnLoggingMessageReserved;
 }
示例#15
0
 public ConfigHandler(IFileSystem fileSystem, IConfigSerializer configSerializer)
 {
     this.fileSystem       = fileSystem;
     this.configSerializer = configSerializer;
 }
 /// <summary>
 /// Deserializes a string to a configuration.
 /// </summary>
 /// <typeparam name="T">The type of the configuration.</typeparam>
 /// <param name="serializer"></param>
 /// <param name="config">The string representation of the configuration.</param>
 /// <returns>The deserialized configuration.</returns>
 public static T Deserialize <T>(this IConfigSerializer serializer, string config) where T : class, IConfig => (T)serializer.Deserialize(config, typeof(T));
示例#17
0
 public void Save(string fileName, IConfigSerializer serializer)
 {
     using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
         serializer.Serialize(fs, this);
 }
示例#18
0
 public AppSettings(IConfigSerializer serializer, ICacheService cacheService) :
     base(serializer, cacheService)
 {
 }
示例#19
0
 public AppSettingsManagerBase(IConfigSerializer <T> serializer)
 {
     _serializer = serializer;
 }
示例#20
0
 protected Configuration(IConfigSerializer serializer, ICacheService cacheService)
     : base(serializer, cacheService)
 {
 }
示例#21
0
        public OverlayAuraModelBase(
            [NotNull] ISharedContext sharedContext,
            [NotNull] IAuraRepository repository,
            [NotNull] IConfigSerializer configSerializer,
            [NotNull] IUniqueIdGenerator idGenerator,
            [NotNull] IFactory <IEyeOverlayViewModel, IOverlayWindowController, IAuraModelController> overlayViewModelFactory,
            [NotNull] IFactory <IOverlayWindowController, IWindowTracker> overlayWindowControllerFactory,
            [NotNull] IFactory <WindowTracker, IStringMatcher> windowTrackerFactory,
            [NotNull][Dependency(WellKnownSchedulers.UI)] IScheduler uiScheduler,
            [NotNull][Dependency(WellKnownSchedulers.Background)] IScheduler bgScheduler)
        {
            defaultAuraName = $"Aura #{Interlocked.Increment(ref GlobalAuraIdx)}";
            Name            = defaultAuraName;
            Id           = idGenerator.Next();
            using var sw = new BenchmarkTimer($"[{Name}({Id})] OverlayAuraModel initialization", Log, nameof(OverlayAuraModelBase));

            var auraTriggers = new ComplexAuraTrigger();

            Triggers = auraTriggers.Triggers;

            var auraActions = new ComplexAuraAction();

            OnEnterActions = auraActions.Actions;

            this.repository       = repository;
            this.configSerializer = configSerializer;
            var matcher       = new RegexStringMatcher().AddToWhitelist(".*");
            var windowTracker = windowTrackerFactory
                                .Create(matcher)
                                .AddTo(Anchors);

            var overlayController = overlayWindowControllerFactory
                                    .Create(windowTracker)
                                    .AddTo(Anchors);

            sw.Step($"Overlay controller created: {overlayController}");

            var overlayViewModel = overlayViewModelFactory
                                   .Create(overlayController, this)
                                   .AddTo(Anchors);

            sw.Step($"Overlay view model created: {overlayViewModel}");

            Overlay = overlayViewModel;
            Observable.Merge(
                overlayViewModel.WhenValueChanged(x => x.AttachedWindow, false).ToUnit(),
                overlayViewModel.WhenValueChanged(x => x.IsLocked, false).ToUnit(),
                this.WhenValueChanged(x => x.IsActive, false).ToUnit())
            .StartWithDefault()
            .Select(
                () => new
            {
                OverlayShouldBeShown = IsActive || !overlayViewModel.IsLocked,
                WindowIsAttached     = overlayViewModel.AttachedWindow != null
            })
            .Subscribe(x => overlayController.IsEnabled = x.OverlayShouldBeShown && x.WindowIsAttached)
            .AddTo(Anchors);
            sw.Step($"Overlay view model initialized: {overlayViewModel}");

            Observable.CombineLatest(
                auraTriggers.WhenAnyValue(x => x.IsActive),
                sharedContext.SystemTrigger.WhenValueChanged(x => x.IsActive))
            .DistinctUntilChanged()
            .Subscribe(x => IsActive = x.All(isActive => isActive), Log.HandleException)
            .AddTo(Anchors);

            auraTriggers.WhenAnyValue(x => x.IsActive)
            .WithPrevious((prev, curr) => new { prev, curr })
            .Where(x => x.prev == false && x.curr)
            .Subscribe(ExecuteOnEnterActions, Log.HandleException)
            .AddTo(Anchors);

            this.repository.KnownEntities
            .ToObservableChangeSet()
            .SkipInitial()
            .Throttle(ModelsReloadTimeout, bgScheduler)
            .ObserveOn(uiScheduler)
            .Subscribe(
                () =>
            {
                var properties = Properties;
                ReloadCollections(properties);
            })
            .AddTo(Anchors);

            var modelPropertiesToIgnore = new[]
            {
                nameof(IAuraTrigger.IsActive),
                nameof(IAuraTrigger.TriggerDescription),
                nameof(IAuraTrigger.TriggerName),
            }.ToImmutableHashSet();

            //FIXME Properties mechanism should have inverted logic - only important parameters must matter
            Observable.Merge(
                this.WhenAnyProperty(x => x.Name, x => x.TargetWindow, x => x.IsEnabled).Select(x => $"[{Name}].{x.EventArgs.PropertyName} property changed"),
                Overlay.WhenAnyProperty().Where(x => !modelPropertiesToIgnore.Contains(x.EventArgs.PropertyName)).Select(x => $"[{Name}].{nameof(Overlay)}.{x.EventArgs.PropertyName} property changed"),
                Triggers.ToObservableChangeSet().Select(x => $"[{Name}({Id})] Trigger list changed, item count: {Triggers.Count}"),
                Triggers.ToObservableChangeSet().WhenPropertyChanged().Where(x => !modelPropertiesToIgnore.Contains(x.EventArgs.PropertyName)).Select(x => $"[{Name}].{x.Sender}.{x.EventArgs.PropertyName} Trigger property changed"),
                OnEnterActions.ToObservableChangeSet().Select(x => $"[{Name}({Id})] Action list changed, item count: {OnEnterActions.Count}"),
                OnEnterActions.ToObservableChangeSet().WhenPropertyChanged().Where(x => !modelPropertiesToIgnore.Contains(x.EventArgs.PropertyName)).Select(x => $"[{Name}].{x.Sender}.{x.EventArgs.PropertyName} Action property changed"))
            .Subscribe(reason => RaisePropertyChanged(nameof(Properties)))
            .AddTo(Anchors);

            Disposable.Create(() =>
            {
                Log.Debug(
                    $"Disposed Aura {Name}({Id}) (aka {defaultAuraName}), triggers: {Triggers.Count}, actions: {OnEnterActions.Count}");
                OnEnterActions.Clear();
                Triggers.Clear();
            }).AddTo(Anchors);
            sw.Step($"Overlay model properties initialized");

            overlayController.RegisterChild(overlayViewModel).AddTo(Anchors);
            sw.Step($"Overlay registration completed: {this}");
        }
示例#22
0
 public AppConfig(IConfigSerializer serializer, ICacheService cacheService)
     : base(serializer, cacheService)
 {
 }
示例#23
0
 public ConfigManager(IConfigSerializer configSerializer, IConfigDeserializer configDeserializer)
 {
     this.configSerializer   = configSerializer;
     this.configDeserializer = configDeserializer;
 }
示例#24
0
 public AppSettingsManager(IConfigSerializer <AppSettings> serializer)
     : base(serializer)
 {
 }
示例#25
0
 public EnvModeSettingsManager(IConfigSerializer serializer, ICacheService cacheService)
     : base(serializer, cacheService)
 {
 }
示例#26
0
 public AppConfig(string configFileName, IConfigSerializer serializer, ICacheService cacheService)
     : base(configFileName, serializer, cacheService)
 {
 }
示例#27
0
        public MainWindowViewModel(
            [NotNull] IFactory <IOverlayAuraViewModel, OverlayAuraProperties> auraViewModelFactory,
            [NotNull] IApplicationUpdaterViewModel appUpdater,
            [NotNull] IClipboardManager clipboardManager,
            [NotNull] IConfigSerializer configSerializer,
            [NotNull] IGenericSettingsViewModel settingsViewModel,
            [NotNull] IMessageBoxViewModel messageBox,
            [NotNull] IHotkeyConverter hotkeyConverter,
            [NotNull] IFactory <HotkeyIsActiveTrigger> hotkeyTriggerFactory,
            [NotNull] IConfigProvider <EyeAurasConfig> configProvider,
            [NotNull] IConfigProvider rootConfigProvider,
            [NotNull] IPrismModuleStatusViewModel moduleStatus,
            [NotNull] IMainWindowBlocksProvider mainWindowBlocksProvider,
            [NotNull] IFactory <IRegionSelectorService> regionSelectorServiceFactory,
            [NotNull] ISharedContext sharedContext,
            [NotNull] IComparisonService comparisonService,
            [NotNull][Dependency(WellKnownSchedulers.UI)] IScheduler uiScheduler)
        {
            using var unused = new OperationTimer(elapsed => Log.Debug($"{nameof(MainWindowViewModel)} initialization took {elapsed.TotalMilliseconds:F0}ms"));

            TabsList     = new ReadOnlyObservableCollection <IEyeAuraViewModel>(sharedContext.AuraList);
            ModuleStatus = moduleStatus.AddTo(Anchors);
            var executingAssemblyName = Assembly.GetExecutingAssembly().GetName();

            Title = $"{(AppArguments.Instance.IsDebugMode ? "[D]" : "")} {executingAssemblyName.Name} v{executingAssemblyName.Version}";
            Disposable.Create(() => Log.Info("Disposing Main view model")).AddTo(Anchors);

            ApplicationUpdater = appUpdater.AddTo(Anchors);
            MessageBox         = messageBox.AddTo(Anchors);
            Settings           = settingsViewModel.AddTo(Anchors);
            StatusBarItems     = mainWindowBlocksProvider.StatusBarItems;

            this.auraViewModelFactory  = auraViewModelFactory;
            this.configProvider        = configProvider;
            this.sharedContext         = sharedContext;
            this.regionSelectorService = regionSelectorServiceFactory.Create();
            this.clipboardManager      = clipboardManager;
            this.configSerializer      = configSerializer;
            this.hotkeyConverter       = hotkeyConverter;
            this.hotkeyTriggerFactory  = hotkeyTriggerFactory;

            CreateNewTabCommand = CommandWrapper.Create(() => AddNewCommandExecuted(OverlayAuraProperties.Default));
            CloseTabCommand     = CommandWrapper
                                  .Create <IOverlayAuraViewModel>(CloseTabCommandExecuted, CloseTabCommandCanExecute)
                                  .RaiseCanExecuteChangedWhen(this.WhenAnyProperty(x => x.SelectedTab));

            DuplicateTabCommand = CommandWrapper
                                  .Create(DuplicateTabCommandExecuted, DuplicateTabCommandCanExecute)
                                  .RaiseCanExecuteChangedWhen(this.WhenAnyProperty(x => x.SelectedTab));
            CopyTabToClipboardCommand = CommandWrapper
                                        .Create(CopyTabToClipboardExecuted, CopyTabToClipboardCommandCanExecute)
                                        .RaiseCanExecuteChangedWhen(this.WhenAnyProperty(x => x.SelectedTab).Select(x => x));

            PasteTabCommand             = CommandWrapper.Create(PasteTabCommandExecuted);
            UndoCloseTabCommand         = CommandWrapper.Create(UndoCloseTabCommandExecuted, UndoCloseTabCommandCanExecute);
            OpenAppDataDirectoryCommand = CommandWrapper.Create(OpenAppDataDirectory);
            SelectRegionCommand         = CommandWrapper.Create(SelectRegionCommandExecuted);

            Observable
            .FromEventPattern <OrderChangedEventArgs>(h => positionMonitor.OrderChanged += h, h => positionMonitor.OrderChanged -= h)
            .Select(x => x.EventArgs)
            .Subscribe(OnTabOrderChanged, Log.HandleUiException)
            .AddTo(Anchors);

            sharedContext
            .AuraList
            .ToObservableChangeSet()
            .ObserveOn(uiScheduler)
            .OnItemAdded(x => SelectedTab = x)
            .Subscribe()
            .AddTo(Anchors);

            this.WhenAnyValue(x => x.SelectedTab)
            .Subscribe(x => Log.Debug($"Selected tab: {x}"))
            .AddTo(Anchors);

            LoadConfig();
            rootConfigProvider.Save();

            if (sharedContext.AuraList.Count == 0)
            {
                CreateNewTabCommand.Execute(null);
            }

            configUpdateSubject
            .Sample(ConfigSaveSamplingTimeout)
            .Subscribe(SaveConfig, Log.HandleException)
            .AddTo(Anchors);

            Observable.Merge(
                this.WhenAnyProperty(x => x.Left, x => x.Top, x => x.Width, x => x.Height)
                .Sample(ConfigSaveSamplingTimeout)
                .Select(x => $"[{x.Sender}] Main window property change: {x.EventArgs.PropertyName}"),
                sharedContext.AuraList.ToObservableChangeSet()
                .Sample(ConfigSaveSamplingTimeout)
                .Select(x => "Tabs list change"),
                sharedContext.AuraList.ToObservableChangeSet()
                .WhenPropertyChanged(x => x.Properties)
                .Sample(ConfigSaveSamplingTimeout)
                .WithPrevious((prev, curr) => new { prev, curr })
                .Select(x => new { x.curr.Sender, ComparisonResult = comparisonService.Compare(x.prev?.Value, x.curr.Value) })
                .Where(x => !x.ComparisonResult.AreEqual)
                .Select(x => $"[{x.Sender.TabName}] Tab properties change: {x.ComparisonResult.DifferencesString}"))
            .Buffer(ConfigSaveSamplingTimeout)
            .Where(x => x.Count > 0)
            .Subscribe(
                reasons =>
            {
                const int maxReasonsToOutput = 50;
                Log.Debug(
                    $"Config Save reasons{(reasons.Count <= maxReasonsToOutput ? string.Empty : $"first {maxReasonsToOutput} of {reasons.Count} items")}:\r\n\t{reasons.Take(maxReasonsToOutput).DumpToTable()}");
                configUpdateSubject.OnNext(Unit.Default);
            },
示例#28
0
 protected ConfigurationReader(IConfigSerializer serializer, ICacheService cacheService)
 {
     _serializer   = serializer;
     _cacheService = cacheService;
 }