public void TestCustomActivator()
        {
            var serializer = new YamlSerializer();
            var yaml       =
                @"%YAML 1.2
---
!System.Drawing.SolidBrush
Color: Red
...
";

            SolidBrush b = null;

            try {
                b = (SolidBrush)serializer.Deserialize(yaml)[0];
            } catch (MissingMethodException) {
                // SolidBrush has no default constructor!
            }

            var config = new YamlConfig();

            config.AddActivator <SolidBrush>(() => new SolidBrush(Color.Black));
            serializer = new YamlSerializer(config);

            // Now the serializer knows how to activate an instance of SolidBrush.
            b = (SolidBrush)serializer.Deserialize(yaml)[0];

            Assert.AreEqual(b.Color, Color.Red);
        }
Example #2
0
        public static CrashReport ExportReport(string title, Exception cause, bool debugReport = false)
        {
            DateTime time = DateTime.Now;
            string   path = Server.ExecutePath + "/reports/crash";
            string   file = path + "/report-" + time.ToString("yyyy_M_d H_mm_ss") + ".report";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            YamlConfig  report = YamlConfig.Load(file);
            CrashReport data   = null;

            if (debugReport)
            {
                data = new CrashReport(title, cause, time);
            }
            else
            {
                data = new CrashReport(title, cause.ToString(), time);
            }

            report.Set("reportData", data);
            report.Save();

            return(data);
        }
Example #3
0
        public void InstanceAppFromConfigWithSecretsShouldHaveCorrectProperties()
        {
            // ARRANGE
            var config = new YamlConfig(CreateSettings(Path.Combine(ConfigFixturePath, "level2", "level3")));

            IEnumerable <Type> types = new List <Type>()
            {
                typeof(AssmeblyDaemonApp)
            };
            var yamlConfig = @"
        app:
            class: AssmeblyDaemonApp
            test_secret_string: !secret a_secret_string
            test_secret_int: !secret a_secret_int
            test_normal_string: not a secret string
            test_normal_int: 0
        ";
            // ACT
            var instances = new YamlAppConfig(
                types,
                new StringReader(yamlConfig),
                config,
                Path.Combine(ConfigFixturePath, "level2", "level3", "any.cs")
                ).Instances;
            var instance = instances.FirstOrDefault() as AssmeblyDaemonApp;

            // ASSERT
            Assert.Equal("this is a secret string", instance?.TestSecretString);
            Assert.Equal(99, instance?.TestSecretInt);
            Assert.Equal(0, instance?.TestNormalInt);
        }
Example #4
0
        public static void ReloadGameConfigs(bool firstTime = false)
        {
            orig_ReloadGameConfigs(firstTime);

            YamlConfig ServerConfig = GameCore.ConfigFile.ServerConfig;

            announceChaos          = ServerConfig.GetBool("announce_chaos_spawn", true);
            chaosAnnouncement      = ServerConfig.GetString("chaos_announcement", "PITCH_1 ATTENTION ALL PERSONNEL . CHAOS INSURGENCY BREACH IN PROGRESS");
            cassieGlitch           = ServerConfig.GetBool("cassie_glitch", false);
            cassieGlitchDetonation = ServerConfig.GetBool("cassie_glitch_post_detonation", false);
            stickyRound            = ServerConfig.GetBool("fix_sticky_round", true);
            mockCommand            = ServerConfig.GetBool("enable_mock_command", true);
            targetAnnouncement     = ServerConfig.GetBool("notify_096_target", true);
            tutorialTrigger096     = ServerConfig.GetBool("tutorial_triggers_096", false);
            enable008       = ServerConfig.GetBool("scp_008", true);
            detonationTimer = ServerConfig.GetInt("warhead_tminus_start_duration", 90);

            webhookUrl       = ServerConfig.GetString("report_discord_webhook_url", string.Empty);
            webhookName      = ServerConfig.GetString("report_username", "Player Report");
            reportServerName = ServerConfig.GetString("report_server_name", "My SCP:SL Server");
            reportHeader     = ServerConfig.GetString("report_header", "Player Report");
            reportContent    = ServerConfig.GetString("report_content", "Player has just been reported.");
            webhookAvatar    = ServerConfig.GetString("report_avatar_url", string.Empty);
            webhookMessage   = ServerConfig.GetString("report_message_content", string.Empty);
            webhookColour    = ServerConfig.GetInt("report_color", 14423100);

            doorCooldown173 = ServerConfig.GetFloat("scp173_door_cooldown", 25f);

            FFDetector.FFDetector.DetectorEnabled = ServerConfig.GetBool("pheggmod_friendly_fire_detector_enabled", true);
        }
Example #5
0
        public void JSonSerializeShouldBeCorrectForConfig()
        {
            // ARRANGE & ACT
            var secrets = YamlConfig.GetAllSecretsFromPath(ConfigFixturePath);

            // ASSERT
            var x = new HostConfig
            {
                LoggingLevel = LogLevel.Information,
                Token        = "1234",
                Host         = "host",
                Port         = 1234,
                Ssl          = true,
                GenerateEntitiesOnStartup = false,
                SourceFolder = "somefolder"
            };

            var obj = JsonSerializer.Serialize <HostConfig>(x);

            Assert.Contains("log_level", obj);
            Assert.Contains("token", obj);
            Assert.Contains("host", obj);
            Assert.Contains("port", obj);
            Assert.Contains("ssl", obj);
            Assert.Contains("source_folder", obj);
            Assert.Contains("generate_entities", obj);
        }
Example #6
0
        private YamlConfig getDefaultYamlConfig()
        {
            var yamlConfig = new YamlConfig();

            yamlConfig.Port               = 7890;
            yamlConfig.SocksPort          = 7891;
            yamlConfig.AllowLan           = true;
            yamlConfig.Mode               = "Direct"; // Rule / Global/ Direct
            yamlConfig.LogLevel           = "info";   // info / warning / error / debug
            yamlConfig.ExternalController = "127.0.0.1:9090";
            yamlConfig.Secret             = "";
            yamlConfig.ProxyList          = new List <Proxy>();
            yamlConfig.RuleList           = new List <string>();

            yamlConfig.RuleList.Add("DOMAIN-SUFFIX,local,DIRECT");
            yamlConfig.RuleList.Add("IP-CIDR,127.0.0.0/8,DIRECT");
            yamlConfig.RuleList.Add("IP-CIDR,172.16.0.0/12,DIRECT");
            yamlConfig.RuleList.Add("IP-CIDR,192.168.0.0/16,DIRECT");
            yamlConfig.RuleList.Add("IP-CIDR,10.0.0.0/8,DIRECT");
            yamlConfig.RuleList.Add("IP-CIDR,17.0.0.0/8,DIRECT");
            yamlConfig.RuleList.Add("IP-CIDR,100.64.0.0/10,DIRECT");

            yamlConfig.RuleList.Add("DOMAIN-KEYWORD,-cn,DIRECT");
            yamlConfig.RuleList.Add("DOMAIN-SUFFIX,cn,DIRECT");
            yamlConfig.RuleList.Add("GEOIP,CN,DIRECT");
            yamlConfig.RuleList.Add("FINAL,,Proxy");
            return(yamlConfig);
        }
Example #7
0
        public void LoadTest()
        {
            // generate default settings
            var defaultSettings = new
            {
                DatabaseName              = "sqlite.db",
                HistoryTimeSpan           = "1.00:00:00",
                OverrideAndLoadAllHistory = "False",
                HomeUrl = "http://test.com/"
            };

            var serializer = new SerializerBuilder().EmitDefaults().Build();
            var yaml       = serializer.Serialize(defaultSettings);

            using (var sw = new StreamWriter("settings.yaml"))
            {
                sw.WriteLine(yaml);
            }

            // try load settings from disk (or generate new settings)
            var settings = new YamlConfig();

            // assert equality
            Assert.AreEqual(defaultSettings.HomeUrl, settings.HomeUrl);
            Assert.AreEqual(defaultSettings.DatabaseName, settings.DatabaseName);
            Assert.AreEqual(defaultSettings.OverrideAndLoadAllHistory, settings.OverrideAndLoadAllHistory.ToString());
            Assert.AreEqual(defaultSettings.HistoryTimeSpan, settings.HistoryTimeSpan.ToString());
        }
        public void CultureTest()
        {
            var config = new YamlConfig();

            config.Culture = new System.Globalization.CultureInfo("da-DK");
            var    serializer = new YamlSerializer(config);
            object obj        = new System.Drawing.PointF(1.2f, 3.1f);
            var    yaml       = serializer.Serialize(obj);

            Assert.AreEqual(
                BuildResult(
                    "!System.Drawing.PointF",
                    "Y: 3,1",
                    "X: 1,2"
                    ),
                yaml
                );
            var restore = serializer.Deserialize(yaml)[0];

            Assert.AreEqual(obj, restore);

            obj  = new System.Drawing.Point(1, 3);
            yaml = serializer.Serialize(obj);
            Assert.AreEqual(
                BuildResult(
                    "!System.Drawing.Point 1; 3"
                    ),
                yaml
                );
            restore = serializer.Deserialize(yaml)[0];
            Assert.AreEqual(obj, restore);

            YamlNode.DefaultConfig.Culture = System.Globalization.CultureInfo.CurrentCulture;
        }
Example #9
0
 public static void ToYamlFile(this object val, FileInfo file, YamlConfig conf = null)
 {
     using (StreamWriter sw = new StreamWriter(file.FullName))
     {
         sw.Write(val.ToYaml());
     }
 }
 /// <summary>
 /// Construct YAML node tree that represents a given C# object.
 /// </summary>
 /// <param name="node"><see cref="YamlNode"/> to be converted to C# object.</param>
 /// <param name="expected">Expected type for the root object.</param>
 /// <param name="config"><see cref="YamlConfig"/> to customize serialization.</param>
 /// <returns></returns>
 public object NodeToObject(YamlNode node, Type expected, SerializerContext context)
 {
     this.context = context;
     this.config = context.Config;
     var appeared = new Dictionary<YamlNode, object>(TypeUtils.EqualityComparerByRef<YamlNode>.Default);
     return NodeToObjectInternal(node, expected, appeared);
 }
Example #11
0
        private void InitConfig()
        {
            string serverPath = $"{ExecutePath}\\ServerProperties.yml";

            this.serverConfig = YamlStaticConfig.Load <ServerConfig>(serverPath);

            string minePath = $"{ExecutePath}\\MineNET.yml";

            this.mineNETConfig = YamlStaticConfig.Load <MineNETConfig>(minePath);

            LangManager.Lang = this.mineNETConfig.Language;

            string banPath = $"{ExecutePath}\\banned-players.yml";

            this.BanConfig = YamlConfig.Load(banPath);

            string banIpPath = $"{ExecutePath}\\banned-ips.yml";

            this.BanIpConfig = YamlConfig.Load(banIpPath);

            string opPath = $"{ExecutePath}\\ops.yml";

            this.OpsConfig = YamlConfig.Load(opPath);

            string whitelistPath = $"{ExecutePath}\\whitelist.yml";

            this.WhitelistConfig = YamlConfig.Load(whitelistPath);
        }
Example #12
0
        /// <summary>
        /// Construct YAML node tree that represents a given C# object.
        /// </summary>
        /// <param name="node"><see cref="YamlNode"/> to be converted to C# object.</param>
        /// <param name="expected">Expected type for the root object.</param>
        /// <param name="config"><see cref="YamlConfig"/> to customize serialization.</param>
        /// <returns></returns>
        public object NodeToObject(YamlNode node, Type expected, YamlConfig config)
        {
            this.config = config;
            var appeared =
                new Dictionary <YamlNode, object>(TypeUtils.EqualityComparerByRef <YamlNode> .Default);

            return(NodeToObjectInternal(node, expected, appeared));
        }
Example #13
0
        public void TestWriteCategorizedKey()
        {
            var    config = YamlConfig.From("TestFile.yaml");
            Action act    = () => config.Write("Section3:LocalValue1", "Local Value 4");

            act.Should().NotThrow();
            config.Read("Section3:LocalValue1").Should().Be("Local Value 4");
        }
Example #14
0
 public void EnsureYamlConfig()
 {
     if (!File.Exists(CONFIG_FILE_PATH))
     {
         YamlConfig yamlConfig = getDefaultYamlConfig();
         SaveYamlConfigFile(yamlConfig);
     }
 }
Example #15
0
        public void TestUpdateGlobal()
        {
            var config = YamlConfig.From(@"TestFile.yaml");

            config.Write("GlobalKey", "NewGlobalValue", "Global Comment");

            config.Read("GlobalKey").Should().Be("NewGlobalValue");
        }
Example #16
0
        public static T[] ArrayFromYaml <T>(this string yaml)
        {
            YamlSerializer ser = new YamlSerializer();
            YamlConfig     c   = new YamlConfig();

            object[] des = ser.Deserialize(yaml, typeof(T));
            return(des.Each((o) => (T)o));
        }
Example #17
0
        public void TestWriteOrphanKey()
        {
            var    config = YamlConfig.From("TestFile.yaml");
            Action act    = () => config.Write("GlobalSetting3", "Global Value 3");

            act.Should().NotThrow();
            config.Read("GlobalSetting3").Should().Be("Global Value 3");
        }
Example #18
0
        public CodeManager CM(string path)
        {
            var loggerMock = new LoggerMock().Logger;
            var config     = new YamlConfig(CreateSettings(path));

            var(daemonApps, _) = DaemonCompiler.GetDaemonApps(path, loggerMock);
            return(new CodeManager(daemonApps, loggerMock, config));
        }
Example #19
0
 public SerializerContext(YamlConfig config)
 {
     if (config == null)
     {
         throw new ArgumentNullException("config");
     }
     this.config = config;
 }
Example #20
0
        public YamlConfig ConvertToYaml()
        {
            YamlConfig yaml = Convert <YamlConfig>();

            yaml.Settings = Settings.ConvertToYaml();
            yaml.Genre    = Genre.Convert <YamlGenre>();
            return(yaml);
        }
Example #21
0
        static YamlHelper()
        {
            var config = new YamlConfig();

            config.DontUseVerbatimTag = true;
            config.OmitTagForRootNode = true;
            config.EmitYamlVersion    = false;
            serializer = new YamlSerializer(config);
        }
 public void CustomActivator()
 {
     var brush = new YamlMapping("Color", "Blue");
     brush.Tag = "!System.Drawing.SolidBrush";
     Assert.Throws<MissingMethodException>(()=>constructor.NodeToObject(brush, YamlNode.DefaultConfig));
     var config = new YamlConfig();
     config.AddActivator<System.Drawing.SolidBrush>(() => new System.Drawing.SolidBrush(System.Drawing.Color.Black));
     Assert.AreEqual(System.Drawing.Color.Blue, ((System.Drawing.SolidBrush)constructor.NodeToObject(brush, config)).Color);
 }
Example #23
0
        public void TestModifyKey()
        {
            var config = YamlConfig.From(@"TestFile.yaml");

            config.Write("Multi:Escritura", 100, "Primera escritura");
            config.Write("Multi:Escritura", 200, "Segunda escritura");

            config.Read <int>("Multi:Escritura").Should().Be(200);
        }
Example #24
0
 public void Init(ClashProcessManager clashProcessManager)
 {
     this.clashProcessManager = clashProcessManager;
     if (yamlConfig == null)
     {
         yamlConfig = YalmConfigManager.Instance.GetYamlConfig();
     }
     initClashWConfig();
 }
Example #25
0
        public static MapPoint GetMapPoint(this YamlConfig config, string key, MapPoint def = null)
        {
            if (MapPoint.TryParse(config.GetString(key), out var point))
            {
                return(point);
            }

            return(def);
        }
        public void InitSerializer()
        {
            var config = new YamlConfig();

            config.Register(new LegacyTypeConverterFactory());
            config.LookupAssemblies.Add(typeof(System.Drawing.SolidBrush).Assembly);
            config.LookupAssemblies.Add(typeof(YamlSerializerTest).Assembly);
            serializer = new Serializer(config);
        }
Example #27
0
        public void Reload()
        {
            if (!Directory.Exists(FileManager.AppFolder))
            {
                Directory.CreateDirectory(FileManager.AppFolder);
            }

            config = new YamlConfig(config_file);
        }
Example #28
0
 public static void LoadConfig()
 {
     Config           = Plugin.Config;
     StartTime        = Config.GetInt("AWS_StartTime");
     BroadcastTime    = Config.GetUInt("AWS_BroadcastTime");
     WarheadStart     = Config.GetString("AWS_WarheadStart", "");
     AutoWarheadStart = Config.GetString("AWS_AutoWarheadStart", "");
     WarheadCancel    = Config.GetString("AWS_WarheadCancel", "");
     RoundStart       = Config.GetString("AWS_RoundStart", "");
 }
 public YamlNode ObjectToNode(object obj, YamlConfig config)
 {
     this.config = config;
     appeared.Clear();
     if ( config.OmitTagForRootNode ) {
         return ObjectToNode(obj, obj.GetType());
     } else {
         return ObjectToNode(obj, (Type)null);
     }
 }
Example #30
0
        public void SecretsLoadFaultyYamlThrowsException()
        {
            // ARRANGE
            var faultyYaml =
                "yaml: correctLine\n" +
                "yaml_missing: \"missing" +
                "yaml_correct: 10";

            // ACT & ASSERT
            Assert.Throws <SyntaxErrorException>(() => YamlConfig.GetSecretsFromSecretsYaml(new StringReader(faultyYaml)));
        }
Example #31
0
        public static Dictionary <string, string> GetStringDictionary(this YamlConfig config, string key, Dictionary <string, string> defaultValue)
        {
            var dictionary = config.GetStringDictionary(key);

            if (dictionary?.Count == 0)
            {
                return(defaultValue);
            }

            return(dictionary);
        }
Example #32
0
        public void CustomActivator()
        {
            var brush = new YamlMapping("Color", "Blue");

            brush.Tag = "!System.Drawing.SolidBrush";
            Assert.Throws <MissingMethodException>(() => constructor.NodeToObject(brush, YamlNode.DefaultConfig));
            var config = new YamlConfig();

            config.AddActivator <System.Drawing.SolidBrush>(() => new System.Drawing.SolidBrush(System.Drawing.Color.Black));
            Assert.AreEqual(System.Drawing.Color.Blue, ((System.Drawing.SolidBrush)constructor.NodeToObject(brush, config)).Color);
        }
Example #33
0
 public static void ToYamlFile(this object val, FileInfo file, YamlConfig conf = null)
 {
     if (!file.Directory.Exists)
     {
         file.Directory.Create();
     }
     using (StreamWriter sw = new StreamWriter(file.FullName))
     {
         sw.Write(val.ToYaml());
     }
 }
        void AssertSuccessRestored(object obj)
        {
            

            var yaml = serializer.Serialize(obj);
            var nodes = parser.Parse(yaml);
            Assert.AreEqual(1, nodes.Count);
            var yamlConfig = new YamlConfig();
            yamlConfig.LookupAssemblies.Add(typeof(YamlConstructorTest).Assembly);
            var restored = constructor.NodeToObject(nodes[0], new SerializerContext(yamlConfig));
            var yaml2 = serializer.Serialize(restored);
            Assert.AreEqual(yaml, yaml2);
        }
        public YamlNode ObjectToNode(object obj, SerializerContext context)
        {
            if (context == null) throw new ArgumentNullException("context");

            this.context = context;
            this.config = context.Config;

            appeared.Clear();
            if ( config.OmitTagForRootNode ) {
                return ObjectToNode(obj, obj.GetType());
            } else {
                return ObjectToNode(obj, (Type)null);
            }
        }
Example #36
0
 /// <summary>
 /// Convert <see cref="YamlNode"/> to a YAML text.
 /// </summary>
 /// <returns>YAML stream.</returns>
 /// <param name="config"><see cref="YamlConfig">YAML configuration</see> to customize serialization.</param>
 public string ToYaml(YamlConfig config)
 {
     return DefaultPresenter.ToYaml(this, config);
 }
        public void CultureTest()
        {
            var config = new YamlConfig();
            config.Register(new LegacyTypeConverterFactory());
            config.LookupAssemblies.Add(typeof(System.Drawing.PointF).Assembly);

            config.Culture = new System.Globalization.CultureInfo("da-DK");

            var serializer = new Serializer(config);
            object obj = new System.Drawing.PointF(1.2f, 3.1f);
            var yaml = serializer.Serialize(obj);
            Assert.AreEqual(
                BuildResult(
                    "!System.Drawing.PointF",
                    "X: 1,2",
                    "Y: 3,1"
                    ),
                yaml
                );
            var restore = serializer.Deserialize(yaml)[0];
            Assert.AreEqual(obj, restore);

            obj = new System.Drawing.Point(1, 3);
            yaml = serializer.Serialize(obj);
            Assert.AreEqual(
                BuildResult(
                    "!System.Drawing.Point 1; 3"
                    ),
                yaml
                );
            restore = serializer.Deserialize(yaml)[0];
            Assert.AreEqual(obj, restore);

            YamlNode.DefaultConfig.Culture = System.Globalization.CultureInfo.CurrentCulture;
        }
 /// <summary>
 /// Initialize an instance of <see cref="YamlSerializer"/> with custom <paramref name="config"/>.
 /// </summary>
 /// <param name="config">Custom <see cref="YamlConfig"/> to customize serialization.</param>
 public YamlSerializer(YamlConfig config)
 {
     this.config = config;
 }
Example #39
0
 /// <summary>
 /// Convert YAML text <paramref name="yaml"/> to a list of <see cref="YamlNode"/>.
 /// </summary>
 /// <param name="s"><see cref="Stream"/> from which YAML document is read.</param>
 /// <returns>YAML nodes</returns>
 /// <param name="config"><see cref="YamlConfig">YAML configuration</see> to customize serialization.</param>
 public static YamlNode[] FromYaml(Stream s, YamlConfig config)
 {
     using ( var sr = new StreamReader(s) )
         return FromYaml(sr, config);
 }
Example #40
0
 /// <summary>
 /// Convert YAML text <paramref name="yaml"/> to a list of <see cref="YamlNode"/>.
 /// </summary>
 /// <param name="tr"><see cref="TextReader"/> from which YAML document is read.</param>
 /// <returns>YAML nodes</returns>
 /// <param name="config"><see cref="YamlConfig">YAML configuration</see> to customize serialization.</param>
 public static YamlNode[] FromYaml(TextReader tr, YamlConfig config)
 {
     var yaml = tr.ReadToEnd();
     return FromYaml(yaml, config);
 }
Example #41
0
        static YamlNode()
        {
            // Initializing order matters !
            DefaultTagPrefix = "tag:yaml.org,2002:";
            DefaultConfig = new YamlConfig();
            DefaultParser = new YamlParser();
            DefaultPresenter = new YamlPresenter();
            DefaultSerializerContext = new SerializerContext(DefaultConfig);

            foreach (var shortToLongTag in ShortToLongTags)
            {
                LongToShortTags.Add(shortToLongTag.Value, shortToLongTag.Key);
            }


        }
Example #42
0
 /// <summary>
 /// Convert YAML text <paramref name="yaml"/> to a list of <see cref="YamlNode"/>.
 /// </summary>
 /// <param name="yaml">YAML text</param>
 /// <returns>YAML nodes</returns>
 /// <param name="config"><see cref="YamlConfig">YAML configuration</see> to customize serialization.</param>
 public static YamlNode[] FromYaml(string yaml, YamlConfig config)
 {
     return DefaultParser.Parse(yaml, config).ToArray();
 }
 public void InitSerializer()
 {
     var config = new YamlConfig();
     config.Register(new LegacyTypeConverterFactory());
     config.LookupAssemblies.Add(typeof(System.Drawing.SolidBrush).Assembly);
     config.LookupAssemblies.Add(typeof(YamlSerializerTest).Assembly);
     serializer = new Serializer(config);
 }
Example #44
0
        public void TestOmitRootNodesTag()
        {
            var obj = new TestClass();
            obj.list.Add(new ChildClass());
            var serializer = new YamlSerializer();
            var yaml= serializer.Serialize(obj);
            Assert.AreEqual(
                BuildResult(
                    "!YamlSerializerTest.TestClass",
                    "list: ",
                    "  Capacity: 4",
                    "  ICollection.Items: ",
                    "    - !YamlSerializerTest.ChildClass",
                    "      list: ",
                    "        Capacity: 0"
                ), yaml
            );

            var config = new YamlConfig();
            config.OmitTagForRootNode = true;
            serializer = new YamlSerializer(config);
            yaml = serializer.Serialize(obj);
            Assert.AreEqual(
                BuildResult(
                    "list: ",
                    "  Capacity: 4",
                    "  ICollection.Items: ",
                    "    - !YamlSerializerTest.ChildClass",
                    "      list: ",
                    "        Capacity: 0"
                ), yaml
            );
        }
        public void CustomActivator()
        {
            var brush = new YamlMapping("Color", "Blue");
            brush.Tag = "!System.Drawing.SolidBrush";
            var config = new YamlConfig();
            config.Register(new LegacyTypeConverterFactory());

            config.LookupAssemblies.Add(typeof(System.Drawing.SolidBrush).Assembly);
            Assert.Throws<MissingMethodException>(() => constructor.NodeToObject(brush, new SerializerContext(config)));
            config.AddActivator<System.Drawing.SolidBrush>(() => new System.Drawing.SolidBrush(System.Drawing.Color.Black));
            Assert.AreEqual(System.Drawing.Color.Blue, ((System.Drawing.SolidBrush)constructor.NodeToObject(brush, new SerializerContext(config))).Color);
        }
Example #46
0
 /// <summary>
 /// Convert <see cref="YamlNode"/> to a YAML text and save it to the file.
 /// </summary>
 /// <param name="FileName">Name of the file to output</param>
 /// <param name="config"><see cref="YamlConfig">YAML configuration</see> to customize serialization.</param>
 public void ToYamlFile(string FileName, YamlConfig config)
 {
     using ( var s = new FileStream(FileName, FileMode.Create) )
         DefaultPresenter.ToYaml(s, this, config);
 }
Example #47
0
        /// <summary>
        /// Load a gameobject from a file
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="roomToInstantiateIn"></param>
        /// <param name="position"> </param>
        /// <param name="rotation"> </param>
        /// <param name="allowNetworkInstantiateIfHasNetworkView"></param>
        /// <param name="visibleToAll">makes all players in the room subscribed to the object</param>
        /// <param name="owner">owner of the loaded object if network instantiated.  By default, it is the server</param>
        /// <returns></returns>
        public static GameObject Load(string filePath, Room roomToInstantiateIn, bool allowNetworkInstantiateIfHasNetworkView = false, Vector3? position = null, Quaternion? rotation = null, bool visibleToAll = true, Player owner = null)
        {
            var dser = new GameObject();
            dser.Room = roomToInstantiateIn;
            var awakes = new List<Action>();
            var config = new YamlConfig();
            var actualFilePath = Path.Combine(ResourceFolder, filePath + ".prefab");

            config.AddActivator<GameObject>(() =>
            {
                //be returning an object we've already created, the AddComponent will work properly
                return dser;
            });

            //config.AddActivator < List<ComponentTracker>>(() =>
            //{
            //    return dser.components;
            //});

            var trackers = new Stack<GameObject.ComponentTracker>();

            config.AddActivator<GameObject.ComponentTracker>(() =>
            {
                var ntrack = new GameObject.ComponentTracker();
                trackers.Push(ntrack);
                return ntrack;
            });

            foreach (Type t in GetComponentTypes())
            {
                Type tLocal = t;
                if (tLocal == typeof(NetworkView) && !allowNetworkInstantiateIfHasNetworkView)
                {
                    Debug.LogWarning("[Resources.Load] file {0} has a NetworkView component on it, but was run as to not network instantiate. It will not be networked.", actualFilePath);
                }
                GameObject dser1 = dser;
                config.AddActivator(tLocal, () =>
                {
                    Action awake;
                    var ntrack = trackers.Pop();
                    var ret = dser1.DeserializeAddComponent(tLocal, out awake, ntrack);
                    awakes.Add(awake);
                    return ret;
                });
            }

            var serializer = new YamlSerializer(config);
            serializer.DeserializeFromFile(actualFilePath, typeof(GameObject));

            if (dser.Resource == null)
                dser.Resource = filePath;

            if (position.HasValue)
                dser.Position = position.Value;
            if (rotation.HasValue)
                dser.Rotation = rotation.Value;

            roomToInstantiateIn.OnGameObjectAdded(dser);

            foreach (var awake in awakes)
                if (awake != null) awake();
            
            dser.OnComponentAfterDeserialization();

            if (allowNetworkInstantiateIfHasNetworkView && dser.GetComponent<NetworkView>() != null)
                roomToInstantiateIn.ResourceNetworkInstantiate(dser, visibleToAll, owner);

            return dser;
        }
Example #48
0
 static YamlNode()
 {
     // Initializing order matters !
     DefaultTagPrefix = "tag:yaml.org,2002:";
     DefaultConfig = new YamlConfig();
     DefaultParser = new YamlParser();
     DefaultPresenter = new YamlPresenter();
 }
Example #49
0
 /// <summary>
 /// Convert YAML text <paramref name="yaml"/> to a list of <see cref="YamlNode"/>.
 /// </summary>
 /// <param name="FileName">YAML File Name</param>
 /// <returns>YAML nodes</returns>
 /// <param name="config"><see cref="YamlConfig">YAML configuration</see> to customize serialization.</param>
 public static YamlNode[] FromYamlFile(string FileName, YamlConfig config)
 {
     using ( var s = new FileStream(FileName, FileMode.Open) )
         return FromYaml(s, config);
 }
 public SerializerContext(YamlConfig config)
 {
     if (config == null) throw new ArgumentNullException("config");
     this.config = config;
 }
Example #51
0
 /// <summary>
 /// Convert <see cref="YamlNode"/> to a YAML text and save it to <see cref="Stream"/> <paramref name="s"/>.
 /// </summary>
 /// <param name="s"><see cref="Stream"/> to output.</param>
 /// <param name="config"><see cref="YamlConfig">YAML configuration</see> to customize serialization.</param>
 public void ToYaml(Stream s, YamlConfig config)
 {
     DefaultPresenter.ToYaml(s, this, config);
 }
Example #52
0
 /// <summary>
 /// Convert <see cref="YamlNode"/> to a YAML text and save it to <see cref="TextWriter"/> <paramref name="tw"/>.
 /// </summary>
 /// <param name="tw"><see cref="TextWriter"/> to output.</param>
 /// <param name="config"><see cref="YamlConfig">YAML configuration</see> to customize serialization.</param>
 public void ToYaml(TextWriter tw, YamlConfig config)
 {
     DefaultPresenter.ToYaml(tw, this, config);
 }
Example #53
0
        public void TestCustomActivator()
        {
            var serializer = new YamlSerializer();
            var yaml =
              @"%YAML 1.2
---
!System.Drawing.SolidBrush
Color: Red
...
";

            SolidBrush b = null;
            try {
                b = (SolidBrush)serializer.Deserialize(yaml)[0];
            } catch ( MissingMethodException ) {
                // SolidBrush has no default constructor!
            }

            var config = new YamlConfig();
            config.AddActivator<SolidBrush>(() => new SolidBrush(Color.Black));
            serializer = new YamlSerializer(config);

            // Now the serializer knows how to activate an instance of SolidBrush.
            b = (SolidBrush)serializer.Deserialize(yaml)[0];

            Assert.AreEqual(b.Color, Color.Red);
        
        }