Ejemplo n.º 1
0
        private static void LoadConfig()
        {
            string configPath = Path.Combine(Paths.ConfigPath, "Config.toml");

            var tomlSettings = TomlSettings.Create(builder => builder
                                                   .ConfigureType <Version>(type => type
                                                                            .WithConversionFor <TomlString>(convert => convert
                                                                                                            .ToToml(tt => tt.ToString())
                                                                                                            .FromToml(ft => Version.Parse(ft.Value)))));

            var oldConfig = File.Exists(configPath) ? Toml.ReadFile <EnvironmentConfig>(configPath, tomlSettings) : null;

            var version = oldConfig?.Version ?? new Version(0, 0, 0);
            var cache   = oldConfig?.Cache ?? CreateDefaultCacheConfig();
            var tor     = oldConfig?.Tor ?? (version <= new Version(5, 0, 28) ? CreateDefaultTorConfig() : null);

            Toml.WriteFile(new EnvironmentConfig(AmoebaEnvironment.Version, cache, tor), configPath, tomlSettings);
            Config = new EnvironmentConfig(version, cache, tor);

            EnvironmentConfig.CacheConfig CreateDefaultCacheConfig()
            {
                return(new EnvironmentConfig.CacheConfig("../Config/Cache.blocks"));
            }

            EnvironmentConfig.TorConfig CreateDefaultTorConfig()
            {
                return(new EnvironmentConfig.TorConfig(@"Assemblies/Tor/tor.exe", "-f tor.config DataDirectory " + @"../../../Work/Tor", @"Assemblies/Tor"));
            }
        }
Ejemplo n.º 2
0
        private void AddAFile(string filepath)
        {
            var theExtension = Path.GetExtension(filepath).ToLowerInvariant();

            theExtension = theExtension == ".gz" ? Path.GetExtension(Path.GetFileNameWithoutExtension(filepath)).ToLowerInvariant() : theExtension;
            switch (theExtension)
            {
            case ".fastq":
                RNASeqFastqDataGrid rnaSeqFastq = new RNASeqFastqDataGrid(filepath);
                RnaSeqFastqCollection.Add(rnaSeqFastq);
                UpdateOutputFolderTextbox();
                break;

            case ".toml":
                TomlTable tomlFile = null;
                try
                {
                    tomlFile = Toml.ReadFile(filepath);
                }
                catch (Exception)
                {
                    break;
                }
                var ye1 = Toml.ReadFile <Options>(filepath);
                AddTaskToCollection(ye1);
                break;
            }
        }
Ejemplo n.º 3
0
        public void ConfigManager_WhenFileDoesntExistYet_WillCreateItInitially()
        {
            string fileName = "autocreated".TestRunUniqueName(Toml.FileExtension);

            try
            {
                // Act
                const int ExpectedIntValue = 3;
                var       cfg = new SingleLevelConfig()
                {
                    IntValue = ExpectedIntValue
                };
                Config.CreateAs()
                .MappedToType(() => cfg)
                .StoredAs(store => store.File(fileName))
                .Initialize();

                // Assert
                File.Exists(fileName).Should().Be(true);
                var read = Toml.ReadFile <SingleLevelConfig>(fileName);
                read.IntValue.Should().Be(ExpectedIntValue);
            }
            finally
            {
                TryDeleteFile(fileName);
            }
        }
Ejemplo n.º 4
0
        private static void UpdateConfig(string configPath, Configuraion newConfig)
        {
            var configFile = Toml.ReadFile(configPath);

            configFile.Update("Configuration", newConfig);
            Toml.WriteFile(configFile, configPath);
        }
Ejemplo n.º 5
0
        // Loading and Parsing

        private RightsRule?ReadFile()
        {
            try
            {
                CreateDefaultConfigIfNotExists();

                var table = Toml.ReadFile(config.Path);
                var ctx   = new ParseContext(registeredRights);
                RecalculateRights(table, ctx);
                foreach (var err in ctx.Errors)
                {
                    Log.Error(err);
                }
                foreach (var warn in ctx.Warnings)
                {
                    Log.Warn(warn);
                }

                if (ctx.Errors.Count == 0)
                {
                    needsAvailableChanGroups = ctx.NeedsAvailableChanGroups;
                    needsAvailableGroups     = ctx.NeedsAvailableGroups;
                    needsPermOverview        = ctx.NeedsPermOverview;
                    needsRecalculation       = false;
                    return(ctx.RootRule);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "The rights file could not be parsed");
            }
            return(null);
        }
Ejemplo n.º 6
0
        public void SetConfigProperty_WhenMultiLevelTypeHasConverter_WritesTheSubPropertyCorrectly()
        {
            using (var fn = TestFileName.Create("file", Toml.FileExtension))
            {
                // Arrange
                var tmlCfg = TomlSettings.Create(c => c
                                                 .ConfigureType <MultiTableConverterObject>(tc => tc
                                                                                            .WithConversionFor <TomlString>(conv => conv
                                                                                                                            .ToToml(o => o.ToString())
                                                                                                                            .FromToml(s => MultiTableConverterObject.Parse(s.Value)))));

                var cfg = Config.CreateAs()
                          .MappedToType(() => new Root())
                          .UseTomlConfiguration(tmlCfg)
                          .StoredAs(s => s.File(fn))
                          .Initialize();

                // Act
                cfg.Set(c => c.ConvertedItem.UnitItem.Unit, "B");

                // Assert
                var tbl = Toml.ReadFile <Root>(fn, tmlCfg);
                tbl.ConvertedItem.UnitItem.Unit.Should().Be("B");
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// PP 5枚の持駒
        /// </summary>
        /// <param name="fv"></param>
        /// <param name="fvDirectory"></param>
        public static void Write_PP_5Mai(IEngineConf engineConf, FeatureVector fv, string fvDirectory)
        {
            var profilePath = System.Configuration.ConfigurationManager.AppSettings["Profile"];
            var toml        = Toml.ReadFile(Path.Combine(profilePath, "Engine.toml"));

            //StringBuilder sb = new StringBuilder();

            {
                PpItem_P1[] p1Items = new PpItem_P1[] {
                    new PpItem_P1(Path.Combine(fvDirectory, engineConf.GetResourceBasename("Fv12PP1pInFvDir")), "1P香", FeatureVectorImpl.CHOSA_KOMOKU_1P + FeatureVectorImpl.CHOSA_KOMOKU_MOTIKYO____),
                    new PpItem_P1(Path.Combine(fvDirectory, engineConf.GetResourceBasename("Fv13PP1pInFvDir")), "1P桂", FeatureVectorImpl.CHOSA_KOMOKU_1P + FeatureVectorImpl.CHOSA_KOMOKU_MOTIKEI____),
                    new PpItem_P1(Path.Combine(fvDirectory, engineConf.GetResourceBasename("Fv14PP1pInFvDir")), "1P銀", FeatureVectorImpl.CHOSA_KOMOKU_1P + FeatureVectorImpl.CHOSA_KOMOKU_MOTIGIN____),
                    new PpItem_P1(Path.Combine(fvDirectory, engineConf.GetResourceBasename("Fv15PP1pInFvDir")), "1P金", FeatureVectorImpl.CHOSA_KOMOKU_1P + FeatureVectorImpl.CHOSA_KOMOKU_MOTIKIN____),
                    new PpItem_P1(Path.Combine(fvDirectory, engineConf.GetResourceBasename("Fv26PP2pInFvDir")), "2P香", FeatureVectorImpl.CHOSA_KOMOKU_2P + FeatureVectorImpl.CHOSA_KOMOKU_MOTIKYO____),
                    new PpItem_P1(Path.Combine(fvDirectory, engineConf.GetResourceBasename("Fv27PP2pInFvDir")), "2P桂", FeatureVectorImpl.CHOSA_KOMOKU_2P + FeatureVectorImpl.CHOSA_KOMOKU_MOTIKEI____),
                    new PpItem_P1(Path.Combine(fvDirectory, engineConf.GetResourceBasename("Fv28PP2pInFvDir")), "2P銀", FeatureVectorImpl.CHOSA_KOMOKU_2P + FeatureVectorImpl.CHOSA_KOMOKU_MOTIGIN____),
                    new PpItem_P1(Path.Combine(fvDirectory, engineConf.GetResourceBasename("Fv29PP2pInFvDir")), "2P金", FeatureVectorImpl.CHOSA_KOMOKU_2P + FeatureVectorImpl.CHOSA_KOMOKU_MOTIKIN____),
                };
                foreach (PpItem_P1 item in p1Items)
                {
                    File.WriteAllText(item.Filepath, Format_FeatureVector_PP_P1Moti.Format_PP_P1Moti_5Mai(fv, item.Title, item.P1_base));
                    //sb.AppendLine(item.Filepath);
                }
            }
        }
Ejemplo n.º 8
0
        // Loading and Parsing

        public bool ReadFile()
        {
            try
            {
                if (!File.Exists(rightsManagerData.RightsFile))
                {
                    Log.Write(Log.Level.Info, "No rights file found. Creating default.");
                    using (var fs = File.OpenWrite(rightsManagerData.RightsFile))
                        using (var data = Util.GetEmbeddedFile("TS3AudioBot.Rights.DefaultRights.toml"))
                            data.CopyTo(fs);
                }

                var table = Toml.ReadFile(rightsManagerData.RightsFile);
                var ctx   = new ParseContext();
                RecalculateRights(table, ctx);
                foreach (var err in ctx.Errors)
                {
                    Log.Write(Log.Level.Error, err);
                }
                foreach (var warn in ctx.Warnings)
                {
                    Log.Write(Log.Level.Warning, warn);
                }
                return(ctx.Errors.Count == 0);
            }
            catch (Exception ex)
            {
                Log.Write(Log.Level.Error, "The rights file could not be parsed: {0}", ex);
                return(false);
            }
        }
Ejemplo n.º 9
0
        private async Task LoadModulesAsync()
        {
            Dictionary <string, bool> enabledModules = new Dictionary <string, bool>();

            if (File.Exists(Common.ModuleFile))
            {
                enabledModules = Toml.ReadFile <Dictionary <string, bool> >(Common.ModuleFile);
            }

            foreach (Type type in Assembly.GetEntryAssembly().GetExportedTypes()
                     .Where(x => typeof(ModuleBase).IsAssignableFrom(x) ||
                            x.IsSubclassOfRawGeneric(typeof(ModuleBase <>))))
            {
                enabledModules.TryAdd(type.Name, true);

                if (enabledModules[type.Name])
                {
                    await _commandService.AddModuleAsync(type, _serviceProvider).ConfigureAwait(false);

                    _logger.LogInformation("Loaded {Module}", type.Name);
                }
            }

            Toml.WriteFile(enabledModules, Common.ModuleFile);
        }
Ejemplo n.º 10
0
        public static MergerConfiguration ParseTOML(string tomlFilePath)
        {
            MergerConfiguration config = Toml.ReadFile <MergerConfiguration>(tomlFilePath);
            bool configOK = true;

            //validate the configuration
            foreach (InputInfo inputInfo in config.input)
            {
                foreach (List <int> region in inputInfo.ps3_regions)
                {
                    //check for a region which is not length 2
                    if (region.Count != 2)
                    {
                        Console.WriteLine($"Error parsing info for {inputInfo.path}: Region should be length 2 but is length {region.Count}");
                        configOK = false;
                        continue;
                    }

                    //check for a region where the start value is greater than the end value
                    if (region[0] > region[1])
                    {
                        Console.WriteLine($"Error parsing info for {inputInfo.path}: Start is greater than end [{region[0]},{region[1]}]");
                        configOK = false;
                        continue;
                    }
                }
            }

            return(configOK ? config : null);
        }
Ejemplo n.º 11
0
        protected static void ModifyFileOnDisk(string fileName, Action <SingleLevelConfig> modify)
        {
            var read = Toml.ReadFile <SingleLevelConfig>(fileName);

            modify(read);
            Toml.WriteFile(read, fileName);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 初期設定。
        /// </summary>
        public void AtBegin(Uc_Main uc_Main)
        {
            var profilePath = System.Configuration.ConfigurationManager.AppSettings["Profile"];
            var toml        = Toml.ReadFile(Path.Combine(profilePath, "Engine.toml"));

            // データの読取「道」
            if (Michi187Array.Load(this.EngineConf.GetResourceFullPath("Michi187")))
            {
            }

            // データの読取「配役」
            Util_Array_KomahaiyakuEx184.Load(this.EngineConf.GetResourceFullPath("Haiyaku185"), Encoding.UTF8);

            // データの読取「強制転成表」 ※駒配役を生成した後で。
            Array_ForcePromotion.Load(this.EngineConf.GetResourceFullPath("InputForcePromotion"), Encoding.UTF8);
#if DEBUG
            {
                File.WriteAllText(this.EngineConf.GetResourceFullPath("OutputForcePromotion"), Array_ForcePromotion.LogHtml());
            }
#endif

            // データの読取「配役転換表」
            Data_KomahaiyakuTransition.Load(this.EngineConf.GetResourceFullPath("InputSyuruiToHaiyaku"), Encoding.UTF8);
#if DEBUG
            {
                File.WriteAllText(this.EngineConf.GetResourceFullPath("OutputSyuruiToHaiyaku"), Data_KomahaiyakuTransition.Format_LogHtml());
            }
#endif

            // ファイルへのパス。
            uc_Main.TxtFvFilepath.Text = Path.GetFullPath(this.EngineConf.GetResourceFullPath("Fv00Komawari"));
            uc_Main.TxtStatus1.Text    = "開くボタンで開いてください。";
        }
Ejemplo n.º 13
0
        internal static PluginConfig?ReadPluginToml(string dir)
        {
            var pluginFilePath = Path.Join(dir, "Plugin.toml");

            if (!File.Exists(pluginFilePath))
            {
                return(null);
            }

            try
            {
                var pluginToml = Toml.ReadFile <PluginTomlConfig>(pluginFilePath);
                return(new PluginConfig(pluginToml));
            }
            catch (IncompleteTomlConfigException e)
            {
                Log.Error(
                    "{toml} is incomplete! There was a problem while reading {property}: " +
                    "{details}",
                    pluginFilePath,
                    e.Property,
                    e.Details);
                return(null);
            }
            catch (Exception e)
            {
                Log.Error(
                    "Directory {dir} looks like a plugin dir, but failed to read/parse {file}: " +
                    "{message}",
                    dir,
                    pluginFilePath,
                    e.Message);
                return(null);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Modifies the local ARCropolis TOML File to match the desired workspace name
        /// </summary>
        /// <param name="WorkspacePath"></param>
        public static void ModifyTouchmARCConfig(string WorkspacePath)
        {
            //Logging setup
            ILog         log      = LogManager.GetLogger("QuasarAppender");
            FileAppender appender = (FileAppender)log.Logger.Repository.GetAppenders()[0];

            appender.File      = Properties.Settings.Default.DefaultDir + "\\Quasar.log";
            appender.Threshold = log4net.Core.Level.Debug;
            appender.ActivateOptions();

            string path = Properties.Settings.Default.DefaultDir + "\\Library\\arcropolis.toml";

            try
            {
                ARCropolisConfiguration config = Toml.ReadFile <ARCropolisConfiguration>(path);
                log.Debug("arc set to " + @"sd:/ultimate/" + WorkspacePath + "/arc");
                config.paths.arc = @"sd:/ultimate/" + WorkspacePath + "/arc";
                log.Debug("umm set to " + @"sd:/ultimate/" + WorkspacePath + "/umm");
                config.paths.umm = @"sd:/ultimate/" + WorkspacePath + "/umm";


                Toml.WriteFile <ARCropolisConfiguration>(config, path);
            }
            catch (Exception e)
            {
                log.Error(e.Message);
            }
        }
Ejemplo n.º 15
0
        public static int Execute(ArgsOptions options)
        {
            var config = Toml.ReadFile(options.EnvFile);
            var xmlDoc = new XmlDocument();

            xmlDoc.Load(options.TemplateFile);

            foreach (var key in config.Keys)
            {
                var tomlBlock = config[key];
                var k         = key.ToLowerInvariant();
                if (k == "connectionstrings")
                {
                    ApplyConnectionStrings(tomlBlock as TomlTable, xmlDoc);
                }
                else if (k == "appsettings")
                {
                    ApplyAppSettings(tomlBlock as TomlTable, xmlDoc);
                }
            }
            if (string.IsNullOrEmpty(options.OutputFile) || options.DryRun)
            {
                Console.WriteLine(Utils.XmlToString(xmlDoc));
            }
            else
            {
                xmlDoc.Save(options.OutputFile);
            }
            return(ErrorCodes.NO_ERROR);
        }
Ejemplo n.º 16
0
        public void SaveMergedConfig_WhenValueInSubTableIsChanged_ValueGetsSavedBackToOriginatorFile()
        {
            string mainFile = null;
            string userFile = null;

            try
            {
                // Arrange
                const string Changed = "ChangedUserName";
                CreateMergedTestAppConfig(out mainFile, out userFile);
                var cfg = Config.CreateAs()
                          .MappedToType(() => new TestData.TestAppSettings())
                          .StoredAs(store =>
                                    store.File(mainFile).MergeWith(
                                        store.File(userFile)))
                          .Initialize();

                // Act
                cfg.Set(c => c.User.UserName, Changed);

                // Assert
                var tml = Toml.ReadFile(userFile);
                ((TomlTable)tml[nameof(TestData.TestAppSettings.User)]).Get <string>(nameof(TestData.TestAppSettings.UserSettings.UserName))
                .Should().Be(Changed);
            }
            finally
            {
                TryDeleteFile(mainFile);
                TryDeleteFile(userFile);
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Initialisierung der ganzen wpf geschichte und einlesen der AppConfiguration.private.toml und
        /// deserialiserung in das Objekt _currentConfiguration
        /// </summary>
        public App()
        {
            AssemblyName myAppName = System.Reflection.Assembly.GetExecutingAssembly().GetName();

            _currentConfiguration = Toml.ReadFile <AppConfiguration.CurrentConfiguration>($"{myAppName.Name}.AppConfiguration.private.toml");
            InitializeComponent();
        }
Ejemplo n.º 18
0
        public void VariantSpecificOutputFiles()
        {
            string thisTaskOutputFolder = Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestVariantFileOutput");

            SearchTask task = Toml.ReadFile <SearchTask>(Path.Combine(TestContext.CurrentContext.TestDirectory, @"VariantSearchTaskConfig.toml"), MetaMorpheusTask.tomlConfig);

            task.SearchParameters.DecoyType = DecoyType.None;

            DbForTask noVariantDb                    = new DbForTask(Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestNoVariantDb.xml"), false);
            DbForTask ambigVariantDb                 = new DbForTask(Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestVariantDb_ambiguous.xml"), false);
            DbForTask frameshiftVariantDb            = new DbForTask(Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestVariantDB_frameshift.xml"), false);
            DbForTask missenseVariantDb              = new DbForTask(Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestVariantDB_missense.xml"), false);
            DbForTask SNVmissenseVariantDb           = new DbForTask(Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestVariantDB_SNVmissense.xml"), false);
            DbForTask stopGainedVariantDb            = new DbForTask(Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestVariantDB_stopGained.xml"), false);
            DbForTask conservativeInsertionVariantDb = new DbForTask(Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestVariantDB_conservativeInsertion.xml"), false);
            DbForTask disruptiveInsertionVariantDb   = new DbForTask(Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestVariantDB_disruptiveInsertion.xml"), false);
            DbForTask conservativeDeletionVariantDb  = new DbForTask(Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestVariantDB_conservativeDeletion.xml"), false);
            DbForTask disruptiveDeletionVariantDb    = new DbForTask(Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestVariantDB_disruptiveDeletion.xml"), false);
            DbForTask stopLossVariantDb              = new DbForTask(Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestVariantDB_stopLoss.xml"), false);

            string raw = Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestVariantPep.mzML");

            EverythingRunnerEngine noVariants = new EverythingRunnerEngine(new List <(string, MetaMorpheusTask)> {
                ("NoVariantOutput", task)
            }, new List <string> {
Ejemplo n.º 19
0
        /// <summary>
        /// Loads settings from specified file.
        /// </summary>
        /// <param name="path">Path to settings file.</param>
        /// <exception cref="System.InvalidOperationException">Settings already loaded.</exception>
        public static AppSettings Load(string path)
        {
            if (Instance != null)
            {
                throw new InvalidOperationException("Settings already loaded.");
            }

            TomlConfig config = TomlConfig.Create((builder) =>
            {
                builder.AllowImplicitConversions(TomlConfig.ConversionLevel.DotNetImplicit);
            });

            AppSettings settings;

            try
            {
                settings = Toml.ReadFile <AppSettings>(path, config);
            }
            catch (Exception)
            {
                settings = new AppSettings();
            }
            settings.Loaded();

            return(settings);
        }
Ejemplo n.º 20
0
        public void SetProperty_InSpecializedScopeForConvertedMultiLevelType_WritesItBackToSpecScope()
        {
            using (var main = TestFileName.Create("main", Toml.FileExtension))
                using (var spec = TestFileName.Create("spec", Toml.FileExtension))
                {
                    // Arrange
                    var tmlCfg = TomlSettings.Create(c => c
                                                     .ConfigureType <MultiTableConverterObject>(tc => tc
                                                                                                .WithConversionFor <TomlString>(conv => conv
                                                                                                                                .ToToml(o => o.ToString())
                                                                                                                                .FromToml(s => MultiTableConverterObject.Parse(s.Value)))));

                    Toml.WriteFile(Toml.Create(), main, tmlCfg);;
                    Toml.WriteFile(Toml.Create(CreateWithUnitItem(2.0, "X")), spec, tmlCfg);

                    var cfg = Config.CreateAs()
                              .MappedToType(() => new Root())
                              .UseTomlConfiguration(tmlCfg)
                              .StoredAs(s => s
                                        .File(main).MergeWith(
                                            s.File(spec)))
                              .Initialize();

                    // Act
                    cfg.Set(c => c.ConvertedItem.UnitItem.Unit, "EX");


                    // Assert
                    var root = Toml.ReadFile <Root>(spec, tmlCfg);
                    root.ConvertedItem.UnitItem.Unit.Should().Be("EX");
                }
        }
Ejemplo n.º 21
0
        private static Configuraion ReadConfig(string configPath)
        {
            var configFile = Toml.ReadFile(configPath);
            var config     = configFile.Get("Configuration");

            return(config.Get <Configuraion>());
        }
Ejemplo n.º 22
0
        // extract deployment config from pyRevitfile inside the clone
        public static List <PyRevitDeployment> GetConfiguredDeployments(string clonePath)
        {
            var deps = new List <PyRevitDeployment>();

            var prFile = GetPyRevitFilePath(clonePath);

            try {
                TomlTable table   = Toml.ReadFile(prFile);
                var       depCfgs = table.Get <TomlTable>("deployments");
                foreach (KeyValuePair <string, TomlObject> entry in depCfgs)
                {
                    logger.Debug("\"{0}\" : \"{1}\"", entry.Key, entry.Value);
                    deps.Add(
                        new PyRevitDeployment(entry.Key,
                                              new List <string>(((TomlArray)entry.Value).To <string>()))
                        );
                }
            }
            catch (Exception ex) {
                logger.Debug(string.Format("Error parsing clone \"{0}\" deployment configs at \"{1}\" | {2}",
                                           clonePath, prFile, ex.Message));
            }

            return(deps);
        }
Ejemplo n.º 23
0
        public void WhenValueChangedInProcess_TheNewConfigGetsAutoSaved()
        {
            string filePath = nameof(this.WhenValueChangedInProcess_TheNewConfigGetsAutoSaved) + Guid.NewGuid() + Toml.FileExtension;

            try
            {
                // Arrange
                const int ExpectedNewValue = 1;
                var       f = new SingleLevelConfig();
                Toml.WriteFile(f, filePath);
                var beforeChangeValue = f.IntValue;
                var cfg = Config.CreateAs()
                          .MappedToType(() => new SingleLevelConfig())
                          .StoredAs(store => store.File(filePath))
                          .Initialize();

                // Act
                cfg.Set(c => c.IntValue, ExpectedNewValue);

                // Assert
                var onDisk = Toml.ReadFile <SingleLevelConfig>(filePath);
                beforeChangeValue.Should().NotBe(onDisk.IntValue, "otherwise the file had the same value as after the change and we would test nothing here");
                onDisk.IntValue.Should().Be(ExpectedNewValue);
            }
            finally
            {
                TryDeleteFile(filePath);
            }
        }
Ejemplo n.º 24
0
        private static async Task <int> run()
        {
            TomlSettings parseSettings = TomlSettings.Create(s =>
                                                             s.ConfigurePropertyMapping(m => m.UseTargetPropertySelector(new SnakeCasePropertySelector()))
                                                             );
            FeedSource feedSource = Toml.ReadFile <FeedSource>(settings.ConfigFilepath, parseSettings);

            if (feedSource == null)
            {
                Console.Error.WriteLine("Error: Somethine went wrong when parsing your settings file :-(");
                return(1);
            }

            if (!string.IsNullOrWhiteSpace(feedSource.Feed.Output))
            {
                settings.OutputFilepath = feedSource.Feed.Output;
            }

            FeedBuilder feedBuilder = new FeedBuilder();

            try {
                await feedBuilder.AddSource(feedSource);
            } catch (ApplicationException error) {
                Console.Error.WriteLine(error.Message);
                return(2);
            }
            await Console.Error.WriteLineAsync($"[Output] Writing feed to {settings.OutputFilepath}");

            File.WriteAllText(settings.OutputFilepath, await feedBuilder.Render());

            return(0);
        }
Ejemplo n.º 25
0
        static GlobalVariables()
        {
            MetaMorpheusVersion = typeof(GlobalVariables).Assembly.GetName().Version.ToString();

            if (MetaMorpheusVersion.Equals("1.0.0.0"))
            {
#if DEBUG
                MetaMorpheusVersion = "Not a release version. DEBUG.";
#else
                MetaMorpheusVersion = "Not a release version.";
#endif
            }
            else
            {
                // as of 0.0.277, AppVeyor appends the build number
                // this is intentional; it's to avoid conflicting AppVeyor build numbers
                // trim the build number off the version number for displaying/checking versions, etc
                var foundIndexes = new List <int>();
                for (int i = 0; i < MetaMorpheusVersion.Length; i++)
                {
                    if (MetaMorpheusVersion[i] == '.')
                    {
                        foundIndexes.Add(i);
                    }
                }
                MetaMorpheusVersion = MetaMorpheusVersion.Substring(0, foundIndexes.Last());
            }

            {
                var pathToProgramFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
                if (!String.IsNullOrWhiteSpace(pathToProgramFiles) && AppDomain.CurrentDomain.BaseDirectory.Contains(pathToProgramFiles) && !AppDomain.CurrentDomain.BaseDirectory.Contains("Jenkins"))
                {
                    DataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "MetaMorpheus");
                }
                else
                {
                    DataDir = AppDomain.CurrentDomain.BaseDirectory;
                }
            }

            ElementsLocation = Path.Combine(DataDir, @"Data", @"elements.dat");
            UsefulProteomicsDatabases.Loaders.LoadElements(ElementsLocation);

            ExperimentalDesignFileName = "ExperimentalDesign.tsv";

            UnimodDeserialized = UsefulProteomicsDatabases.Loaders.LoadUnimod(Path.Combine(DataDir, @"Data", @"unimod.xml")).ToList();
            PsiModDeserialized = UsefulProteomicsDatabases.Loaders.LoadPsiMod(Path.Combine(DataDir, @"Data", @"PSI-MOD.obo.xml"));
            var formalChargesDictionary = UsefulProteomicsDatabases.Loaders.GetFormalChargesDictionary(PsiModDeserialized);
            UniprotDeseralized = UsefulProteomicsDatabases.Loaders.LoadUniprot(Path.Combine(DataDir, @"Data", @"ptmlist.txt"), formalChargesDictionary).ToList();

            foreach (var modFile in Directory.GetFiles(Path.Combine(DataDir, @"Mods")))
            {
                AddMods(UsefulProteomicsDatabases.PtmListLoader.ReadModsFromFile(modFile));
            }
            AddMods(UnimodDeserialized.OfType <ModificationWithLocation>());
            AddMods(UniprotDeseralized.OfType <ModificationWithLocation>());

            GlobalSettings = Toml.ReadFile <GlobalSettings>(Path.Combine(DataDir, @"settings.toml"));
        }
Ejemplo n.º 26
0
 public void ResetGameSettings()
 {
     configTable = Toml.ReadFile(Defines.ConfigFile).ToDictionary();
     if (configTable.ContainsKey(Defines.GameConfig))
     {
         GameSettingsScreen.SetConfig((Dictionary <string, object>)configTable[Defines.GameConfig]);
     }
 }
Ejemplo n.º 27
0
 public void ReadFileT_WithStreamWhenConfigIsNull_ThrowsArgNull()
 {
     using (var s = GetStream())
     {
         Action a = () => Toml.ReadFile <SimpleToml>(s, null);
         a.ShouldThrow <ArgumentNullException>();
     }
 }
Ejemplo n.º 28
0
 public void ReadFile_WhenArgIsFileStreamAndNoConfigGiven_ReadsFileCorrectly()
 {
     using (var s = GetStream())
     {
         var tml = Toml.ReadFile(GetStream());
         tml.Get <int>("X").Should().Be(1);
     }
 }
Ejemplo n.º 29
0
 public void ReadFileT_WhenArgIsFileStreamAndNoConfigGiven_ReadsFileCorrectly()
 {
     using (var s = GetStream())
     {
         var tml = Toml.ReadFile <SimpleToml>(GetStream());
         tml.X.Should().Be(1);
     }
 }
Ejemplo n.º 30
0
        static void Main(string[] args)
        {
            var toml = Toml.ReadFile("conf.toml");

            var struc = toml.Get <TStruc>();

            Toml.WriteFile(toml, "conf_out.toml");
        }