Ejemplo n.º 1
0
        public void ReadValidStringsUntyped_TableArrayMany()
        {
            // Arrange
            var toml = TomlStrings.Valid.TableArrayMany;

            // Act
            var read = Toml.ReadString(toml);

            // Assert
            Assert.Single(read.Rows);
            Assert.Equal(3, read.Get <TomlTableArray>("people").Count);
            var tt = read.Get <TomlTableArray>("people")[0];

            Assert.Equal("Bruce", tt.Get <string>("first_name"));
            Assert.Equal("Springsteen", tt.Get <string>("last_name"));
            tt = read.Get <TomlTableArray>("people")[1];
            Assert.Equal("Eric", tt.Get <string>("first_name"));
            Assert.Equal("Clapton", tt.Get <string>("last_name"));
            tt = read.Get <TomlTableArray>("people")[2];
            Assert.Equal("Bob", tt.Get <string>("first_name"));
            Assert.Equal("Seger", tt.Get <string>("last_name"));
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            Console.WriteLine(string.Join(",", args));
            //run_tuning(0.1, 1.1);

            if (args.Length == 1)
            {
                var config = Toml.ReadFile <Configuration>(args[0]);
                run_search(config);
            }
            else if (args.Length == 2)
            {
                var config = Toml.ReadFile <Configuration>(args[0]);
                run_search(config, Int32.Parse(args[1]));
            }
            else
            {
                Console.WriteLine(
                    "Specify a config file or a config file and trial id."
                    );
            }
        }
Ejemplo n.º 3
0
        public static TomlTable Clone(this TomlTable input)
        {
            input.CheckNotNull(nameof(input));

            TomlTable cloned = Toml.Create(input.Root.Settings);

            cloned.TableType = input.TableType;

            foreach (var r in input.InternalRows)
            {
                switch (r.Value.TomlType)
                {
                case TomlObjectType.Table: cloned.AddRow(r.Key, ((TomlTable)r.Value).Clone()); break;

                case TomlObjectType.ArrayOfTables: cloned.AddRow(r.Key, ((TomlTableArray)r.Value).Clone()); break;

                default: cloned[r.Key.Value] = r.Value; break;
                }
            }

            return(cloned);
        }
Ejemplo n.º 4
0
        // extract deployment config from pyRevitfile inside the clone
        public static List <PyRevitEngine> GetConfiguredEngines(string clonePath)
        {
            var engines = new List <PyRevitEngine>();

            var prFile = GetPyRevitFilePath(clonePath);

            try {
                TomlTable table       = Toml.ReadFile(prFile);
                var       enginesCfgs = table.Get <TomlTable>("engines");
                foreach (var engineCfg in enginesCfgs)
                {
                    logger.Debug("Engine configuration found: {0}", engineCfg.Key);
                    var infoTable = engineCfg.Value as TomlTable;
                    foreach (KeyValuePair <string, TomlObject> entry in infoTable)
                    {
                        logger.Debug("\"{0}\" : \"{1}\"", entry.Key, entry.Value);
                    }

                    engines.Add(
                        new PyRevitEngine(
                            id: engineCfg.Key,
                            engineVer: new PyRevitEngineVersion(infoTable["version"].Get <int>()),
                            runtime: infoTable.TryGetValue("runtime") != null ? infoTable["runtime"].Get <bool>() : true,                                      // be flexible since its a new feature
                            enginePath: Path.Combine(clonePath, infoTable["path"].Get <string>()),
                            assemblyName: infoTable.TryGetValue("assembly") != null? infoTable["assembly"].Get <string>() : PyRevitConsts.LegacyEngineDllName, // be flexible since its a new feature
                            kernelName: infoTable["kernel"].Get <string>(),
                            engineDescription: infoTable["description"].Get <string>(),
                            isDefault: engineCfg.Key.Contains("DEFAULT")
                            )
                        );
                }
            }
            catch (Exception ex) {
                logger.Debug(string.Format("Error parsing clone \"{0}\" engines configs from \"{1}\" | {2}",
                                           clonePath, prFile, ex.Message));
            }

            return(engines);
        }
Ejemplo n.º 5
0
 internal override void LoadConfig()
 {
     if (File.Exists(@"modules/twitch/data/config.tml"))
     {
         TomlTable configTable = Toml.ReadFile(@"modules/twitch/data/config.tml");
         streamAPIClientID = configTable.Get <string>("StreamAPIClientID");
     }
     if (File.Exists(@"modules/twitch/data/channel_ids.json"))
     {
         foreach (KeyValuePair <string, string> guildAndChannel in JsonConvert.DeserializeObject <Dictionary <string, string> >(File.ReadAllText(@"modules/twitch/data/channel_ids.json")))
         {
             try
             {
                 streamChannelIds.Add((ulong)Convert.ToInt64(guildAndChannel.Key), (ulong)Convert.ToInt64(guildAndChannel.Value));
             }
             catch (Exception e)
             {
                 Program.WriteToLog($"Exception when loading stream channel config: {e.Message}");
             }
         }
     }
 }
Ejemplo n.º 6
0
 public R <string> ReadText(string text)
 {
     try
     {
         var table = Toml.ReadString(text);
         var ctx   = new ParseContext();
         RecalculateRights(table, ctx);
         var strb = new StringBuilder();
         foreach (var warn in ctx.Warnings)
         {
             strb.Append("WRN: ").AppendLine(warn);
         }
         if (ctx.Errors.Count == 0)
         {
             strb.Append(string.Join("\n", rules.Select(x => x.ToString())));
             if (strb.Length > 900)
             {
                 strb.Length = 900;
             }
             return(R <string> .OkR(strb.ToString()));
         }
         else
         {
             foreach (var err in ctx.Errors)
             {
                 strb.Append("ERR: ").AppendLine(err);
             }
             if (strb.Length > 900)
             {
                 strb.Length = 900;
             }
             return(R <string> .Err(strb.ToString()));
         }
     }
     catch (Exception ex)
     {
         return(R <string> .Err("The rights file could not be parsed: " + ex.Message));
     }
 }
Ejemplo n.º 7
0
        public void Read_AsDictionary_ReadsTableCorrectly()
        {
            // Arrange
            using (var filename = TestFileName.Create("test", ".toml"))
            {
                File.WriteAllText(filename, exp);

                // Act
                var data   = Toml.ReadFile(filename).ToDictionary();
                var server = (Dictionary <string, object>)data["Server"];
                var client = (Dictionary <string, object>)data["Client"];

                Console.WriteLine("EnableDebug: " + data["EnableDebug"]);
                Console.WriteLine("Timeout: " + server["Timeout"]);
                Console.WriteLine("ServerAddress: " + client["ServerAddress"]);

                // Assert
                data["EnableDebug"].Should().Be(true);
                server["Timeout"].Should().Be(TimeSpan.FromMinutes(1));
                client["ServerAddress"].Should().Be("http://127.0.0.1:8080");
            }
        }
Ejemplo n.º 8
0
        public void ReadValidStringsUntyped_StringEsapces()
        {
            // Arrange
            var toml = TomlStrings.Valid.StringEscapes;

            // Act
            var read = Toml.ReadString(toml);

            // Assert
            Assert.Equal(11, read.Rows.Count());
            Assert.Equal("This string has a \b backspace character.", read.Get <string>("backspace"));
            Assert.Equal("This string has a \t tab character.", read.Get <string>("tab"));
            Assert.Equal("This string has a \n new line character.", read.Get <string>("newline"));
            Assert.Equal("This string has a \f form feed character.", read.Get <string>("formfeed"));
            Assert.Equal("This string has a \r carriage return character.", read.Get <string>("carriage"));
            Assert.Equal("This string has a \" quote character.", read.Get <string>("quote"));
            Assert.Equal("This string has a \\ backslash character.", read.Get <string>("backslash"));
            Assert.Equal("This string does not have a unicode \\u escape.", read.Get <string>("notunicode1"));
            Assert.Equal("This string does not have a unicode \u005Cu escape.", read.Get <string>("notunicode2"));
            Assert.Equal("This string does not have a unicode \\u0075 escape.", read.Get <string>("notunicode3"));
            Assert.Equal("This string does not have a unicode \\\u0075 escape.", read.Get <string>("notunicode4"));
        }
Ejemplo n.º 9
0
        public static LocalConfig Load(string path)
        {
            LocalConfig returnval = new LocalConfig();

            if (File.Exists(path))
            {
                string filestr = File.ReadAllText(path);
                if (!string.IsNullOrEmpty(filestr))
                {
                    var doc = Toml.Parse(filestr);
                    if (doc != null)
                    {
                        var       table   = doc.ToModel();
                        TomlTable MainTbl = (TomlTable)table["AssemblyGenerator"];
                        if (MainTbl != null)
                        {
                            returnval.UnityVersion      = (string)MainTbl["UnityVersion"];
                            returnval.GameAssemblyHash  = (string)MainTbl["GameAssemblyHash"];
                            returnval.DumperVersion     = (string)MainTbl["DumperVersion"];
                            returnval.UnhollowerVersion = (string)MainTbl["UnhollowerVersion"];
                            TomlArray oldfilesarr = (TomlArray)MainTbl["OldFiles"];
                            if (oldfilesarr.Count > 0)
                            {
                                for (int i = 0; i < oldfilesarr.Count; i++)
                                {
                                    string file = (string)oldfilesarr[i];
                                    if (!string.IsNullOrEmpty(file))
                                    {
                                        returnval.OldFiles.Add(file);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(returnval);
        }
Ejemplo n.º 10
0
    public static bool Load(string filepath = "")
    {
        if (!String.IsNullOrEmpty(filepath))
        {
            FilePath = filepath;
        }

        // build defaults
        if (!File.Exists(Defines.ConfigFile))
        {
            CreateConfigFile();
        }

        configTable = Toml.ReadFile(Defines.ConfigFile).ToDictionary();

        if (File.Exists(Defines.LanguageConfig))
        {
            localizationTable = Toml.ReadFile(Defines.LanguageConfig).ToDictionary();
        }

        // Set the localized language for the rest of the run, unless changed in options
        if (configTable.ContainsKey(Defines.GameConfig))
        {
            Dictionary <string, object> gameOpts = (Dictionary <string, object>)configTable["GameConfig"];
            if (gameOpts.ContainsKey("Language"))
            {
                SetLocalizedLanguage(Convert.ToInt32(gameOpts["Language"]));
            }
        }

        if (configTable.ContainsKey(Defines.TouchConfig))
        {
            TouchSettings.SetConfig((Dictionary <string, object>)configTable[Defines.TouchConfig]);
        }

        IsLoaded = true;
        return(true);
    }
Ejemplo n.º 11
0
        // Loading and Parsing

        private RightsRule ReadFile()
        {
            try
            {
                if (!File.Exists(config.Path))
                {
                    Log.Info("No rights file found. Creating default.");
                    using (var fs = File.OpenWrite(config.Path))
                        using (var data = Util.GetEmbeddedFile("TS3AudioBot.Rights.DefaultRights.toml"))
                            data.CopyTo(fs);
                }

                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;
                    needsRecalculation       = false;
                    return(ctx.RootRule);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "The rights file could not be parsed");
            }
            return(null);
        }
Ejemplo n.º 12
0
        Project(string path)
        {
            ProjectDirectory    = new DirectoryInfo(Path.GetDirectoryName(path) !);
            DependencyDirectory = new DirectoryInfo(Path.Combine(ProjectDirectory.FullName, "dep"));
            SourceDirectory     = new DirectoryInfo(Path.Combine(ProjectDirectory.FullName, "src"));
            BuildDirectory      = new DirectoryInfo(Path.Combine(ProjectDirectory.FullName, "bin"));

            // TODO: make this parsing more robust in general, and add error reporting.

            var table   = Toml.ReadFile(path);
            var project = (TomlTable)table.Get("project");

            Type       = (ProjectType)Enum.Parse(typeof(ProjectType), project.Get <string>("type"), true);
            Name       = project.Get <string>("name");
            MainModule = new FileInfo(Path.Combine(SourceDirectory.FullName, Path.ChangeExtension(Name,
                                                                                                  StandardModuleLoader.ModuleFileNameExtension) !));
            ExecutableFileName = table.TryGetValue("executable")?.Get <string>();
            Version            = SemanticVersion.Parse(project.Get <string>("version"));
            License            = project.TryGetValue("license")?.Get <string>();
            Description        = project.TryGetValue("description")?.Get <string>();
            ProjectUri         = project.TryGetValue("url") is TomlObject o1 ? new Uri(o1.Get <string>()) : null;
            DocumentationUri   = project.TryGetValue("url-doc") is TomlObject o2 ? new Uri(o2.Get <string>()) : null;
            SourceUri          = project.TryGetValue("url-src") is TomlObject o3 ? new Uri(o3.Get <string>()) : null;

            var cfg = new SyntaxLintConfiguration();

            if (table.TryGetValue("lints") is TomlTable lints)
            {
                foreach (var kvp in lints)
                {
                    cfg = cfg.Set(kvp.Key, kvp.Value.Get <string>().ToLowerInvariant() switch
                    {
                        LanguageLinter.NoneSeverityName => (SyntaxDiagnosticSeverity?)null,
                        LanguageLinter.SuggestionSeverityName => SyntaxDiagnosticSeverity.Suggestion,
                        LanguageLinter.WarninngSeverityName => SyntaxDiagnosticSeverity.Warning,
                        LanguageLinter.ErrorSeverityName => SyntaxDiagnosticSeverity.Error,
                        _ => throw DebugAssert.Unreachable(),
                    });
Ejemplo n.º 13
0
        public void ReadValidToml_TableArrayNested()
        {
            // Arrange
            var toml = TomlStrings.Valid.TableArrayNested;

            // Act
            var read = Toml.ReadString <AlbumsRoot>(toml);

            // Assert
            Assert.NotNull(read);
            Assert.Equal(2, read.albums.Count);
            Assert.Equal("Born to Run", read.albums[0].name);
            var a0 = read.albums[0];

            Assert.Equal("Jungleland", a0.songs[0].name);
            Assert.Equal("Meeting Across the River", a0.songs[1].name);

            Assert.Equal("Born in the USA", read.albums[1].name);
            var a1 = read.albums[1];

            Assert.Equal("Glory Days", a1.songs[0].name);
            Assert.Equal("Dancing in the Dark", a1.songs[1].name);
        }
Ejemplo n.º 14
0
    public static bool Load(string filepath = "")
    {
        if (!String.IsNullOrEmpty(filepath))
        {
            FilePath = filepath;
        }

        // build defaults
        if (!File.Exists(Defines.ConfigFile))
        {
            CreateConfigFile();
        }

        configTable = Toml.ReadFile(Defines.ConfigFile).ToDictionary();

        if (configTable.ContainsKey(Defines.TouchConfig))
        {
            TouchSettings.SetConfig((Dictionary <string, object>)configTable[Defines.TouchConfig]);
        }

        IsLoaded = true;
        return(true);
    }
Ejemplo n.º 15
0
        public void ReadAdvancedToml_WithArray()
        {
            // Arrange
            var toml = @"
StringArray = [""A"", ""B"", ""C""]
IntArray = [1, 2, 3]
StringList = [""A"", ""B"", ""C""]
IntList = [1, 2, 3]";

            // Act
            var read = Toml.ReadString <WithArray>(toml);

            // Assert
            Assert.NotNull(read);
            Assert.NotNull(read.StringList);
            Assert.Equal(3, read.StringList.Count);
            Assert.NotNull(read.IntList);
            Assert.Equal(3, read.IntList.Count);
            Assert.NotNull(read.StringArray);
            Assert.Equal(3, read.StringArray.Length);
            Assert.NotNull(read.IntArray);
            Assert.Equal(3, read.IntArray.Length);
        }
Ejemplo n.º 16
0
        // Loading and Parsing

        public bool ReadFile()
        {
            try
            {
                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.º 17
0
        /// <summary>
        /// Processes the block file asynchronous.
        /// </summary>
        /// <param name="filesData">The files data.</param>
        /// <returns></returns>
        private static async Task <List <BlockJsonModel> > ProcessBlockFileAsync(IDictionary <string, string> filesData)
        {
            var blocks       = new List <BlockJsonModel>();
            var tomlSettings = TomlFileReader.LoadLowerCaseTomlSettings();

            foreach (var data in filesData)
            {
                var blockReadModel = Toml.ReadString <BlockReadModel>(data.Value, tomlSettings);
                var blockFileName  = Path.GetFileNameWithoutExtension(data.Key);

                var blockTask   = GetBlockAsync(blockReadModel, blockFileName);
                var modulesTask = GetModulesAsync(blockReadModel);

                await Task.WhenAll(blockTask, modulesTask);

                var block = blockTask.Result;
                block.Modules.AddRange(modulesTask.Result);

                blocks.Add(block);
            }

            return(blocks);
        }
Ejemplo n.º 18
0
        private static void LoadConfig()
        {
            string configPath = Path.Combine(Paths.ConfigDirectoryPath, "Interface.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 <InterfaceConfig>(configPath, tomlSettings) : null;

            var version       = oldConfig?.Version ?? AmoebaEnvironment.Version;
            var communication = oldConfig?.Communication ?? CreateDefaultCommunicationConfig();

            Toml.WriteFile(new InterfaceConfig(AmoebaEnvironment.Version, communication), configPath, tomlSettings);
            Config = new InterfaceConfig(version, communication);

            InterfaceConfig.CommunicationConfig CreateDefaultCommunicationConfig()
            {
                return(new InterfaceConfig.CommunicationConfig("tcp:127.0.0.1:4040"));
            }
        }
Ejemplo n.º 19
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 <>))))
            {
                if (enabledModules.TryAdd(type.Name, true) || enabledModules[type.Name])
                {
                    await _commandService.AddModuleAsync(type, _serviceProvider).ConfigureAwait(false);

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

            Toml.WriteFile(enabledModules, Common.ModuleFile);
        }
Ejemplo n.º 20
0
        public void ReadSingleClass_ReadClassCorrectly()
        {
            // Arrange
            var toml = @"
StringProperty = ""Hello world""
IntProperty = 100
DoubleProperty = 2.5
ArrayProperty = [10, 20, 30]
";

            // Act
            var sc = Toml.ReadString <SingleClass>(toml);

            // Assert
            Assert.Equal("Hello world", sc.StringProperty);
            Assert.Equal(100, sc.IntProperty);
            Assert.Equal(2.5, sc.DoubleProperty);
            Assert.NotNull(sc.ArrayProperty);
            Assert.Equal(3, sc.ArrayProperty.Length);
            Assert.Equal(10, sc.ArrayProperty[0]);
            Assert.Equal(20, sc.ArrayProperty[1]);
            Assert.Equal(30, sc.ArrayProperty[2]);
        }
Ejemplo n.º 21
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 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 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.º 22
0
        public void WriteRead_WhenUsingWeirdGenSelectorCombo_WrittenContentsCannotBeReadBackCorrectly()
        {
            // Arrange
            var settings = TomlSettings.Create(s => s
                                               .ConfigurePropertyMapping(m => m
                                                                         .UseTargetPropertySelector(standardSelectors => standardSelectors.Exact)
                                                                         .UseKeyGenerator(standardGenerators => standardGenerators.LowerCase)));
            var obj = new RootTestObject()
            {
                Prop = 3, Sub = new RootTestObject.SubTestObject()
                {
                    SubProp = 4
                }
            };
            var toRead = Toml.WriteString(obj, settings);

            // Act
            var read = Toml.ReadString <RootTestObject>(toRead, settings);

            // Assert
            read.Prop.Should().NotBe(obj.Prop);
            read.Sub.SubProp.Should().NotBe(obj.Sub.SubProp);
        }
Ejemplo n.º 23
0
        private async Task Run()
        {
            // Read config.
            var execDir    = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var configPath = Path.Combine(execDir, "config.toml");

            config = Toml.ReadFile <Configuration>(configPath);

            obs = new OBSWebsocket();
            obs.Connect(config.Connection.URL, config.Connection.Password);

            _activityManager =
                Connection.Session.CreateProxy <IActivities>("org.kde.ActivityManager", "/ActivityManager/Activities");

            try
            {
                await Everything();
            }
            finally
            {
                obs.Disconnect();
            }
        }
Ejemplo n.º 24
0
        public void ReadToml_WhenConfigHasConverter_ConverterGetsUsed()
        {
            // Arrange
            var config = TomlSettings.Create(cfg => cfg
                                             .ConfigureType <TestStruct>(ct => ct
                                                                         .WithConversionFor <TomlInt>(conv => conv
                                                                                                      .FromToml((m, ti) => new TestStruct()
            {
                Value = (int)ti.Value
            })
                                                                                                      .ToToml(ts => ts.Value)
                                                                                                      )
                                                                         )
                                             );

            string toml = @"S = 10";

            // Act
            var co = Toml.ReadString <ConfigObject>(toml, config);

            // Assert
            Assert.Equal(10, co.S.Value);
        }
Ejemplo n.º 25
0
        public KeyManager(string keyName, TomlTable parent, Action flush)
        {
            // Set Mod Name
            KeyName = keyName.PathEscape();

            // Assign TOML Structure
            _parent = parent;
            try
            {
                // Try to get table from existing structure
                _settings = _parent.Get <TomlTable>(KeyName);
            }
            catch (KeyNotFoundException)
            {
                // Create new table if it doesn't exist
                _parent[KeyName] = Toml.Create();
                _settings        = _parent.Get <TomlTable>(KeyName);
            }

            // Define Interfaces
            _getter = new Getter(_settings, flush);
            _setter = new Setter(_settings, flush);
        }
Ejemplo n.º 26
0
        public void Init_WhenMergeSourceIsUsedAndNoManualInitIsDone_BothFilesAreCreatedButOnlyTheFirstHasAllDefaultData()
        {
            using (var main = TestFileName.Create("main", Toml.FileExtension))
                using (var user = TestFileName.Create("user", Toml.FileExtension))
                {
                    // Act
                    var merged = Config.CreateAs()
                                 .MappedToType(() => new TestData.TestAppSettings())
                                 .StoredAs(store => store
                                           .File(main).MergeWith().File(user))
                                 .Initialize();

                    // Assert
                    File.Exists(main).Should().Be(true);
                    File.Exists(user).Should().Be(true);

                    var mainTbl = Toml.ReadFile(main);
                    var usertbl = Toml.ReadFile(user);

                    mainTbl.Count.Should().BeGreaterThan(0);
                    usertbl.Count.Should().Be(0);
                }
        }
Ejemplo n.º 27
0
        static int Main(string[] args)
        {
            TextReader reader  = Console.In;
            TextWriter writer  = Console.Out;
            var        content = reader.ReadToEnd();

            try
            {
                //Debugger.Launch();
                var t    = Toml.ReadString(content);
                var dict = t.ToDictionary();
                var conv = new ToJsonConverter();
                var json = conv.Convert(t);
                writer.Write(json);

                return(0);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.ToString());
                return(1);
            }
        }
Ejemplo n.º 28
0
    public async Task <CreateInvoiceResult> CreateInvoice(Invoice invoice)
    {
        var invoiceToml = Toml.FromModel(invoice, new TomlModelOptions()
        {
            ConvertPropertyName = name => TomlNamingHelper.PascalToCamelCase(name)
        });

        var uri            = new Uri(_baseUri, INVOICE_PATH);
        var requestContent = new StringContent(invoiceToml, null, "application/toml");
        var response       = await _httpClient.PostAsync(uri, requestContent);

        await ExpectResponseCode(response, HttpStatusCode.Created, HttpStatusCode.Accepted);

        var content = await response.Content.ReadAsStringAsync();

        var syntax      = GetTomlSyntax(content);
        var tomlOptions = new TomlModelOptions()
        {
            ConvertPropertyName = name => TomlNamingHelper.PascalToCamelCase(name)
        };

        return(syntax.ToModel <CreateInvoiceResult>(tomlOptions));
    }
Ejemplo n.º 29
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 ?? AmoebaEnvironment.Version;
            var cache   = oldConfig?.Cache ?? CreateDefaultCacheConfig();

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

            EnvironmentConfig.CacheConfig CreateDefaultCacheConfig()
            {
                return(new EnvironmentConfig.CacheConfig("../Config/Cache.blocks"));
            }
        }
Ejemplo n.º 30
0
        public void Load()
        {
            bool exists = File.Exists(_configFileName);

            if (exists)
            {
                Copy(Toml.ReadFile <NESToolConfigurationModel>(_configFileName));
            }
            else
            {
                Save();
            }

            WindowVO vo = new WindowVO()
            {
                SizeX = WindowSizeX, SizeY = WindowSizeY, IsFullScreen = FullScreen
            };

            SignalManager.Get <LoadConfigSuccessSignal>().Dispatch();
            SignalManager.Get <SetUpWindowPropertiesSignal>().Dispatch(vo);

            _loaded = true;
        }