Esempio n. 1
0
    public static void SetupSerializers()
    {
		//
		ConfigFilePath = Application.dataPath + @"\Binds";
		defaultBindsSerializer = new ConfigSerializer(ConfigFilePath + @"\DefaultBindings.txt");
		keyBindsSerializer = new ConfigSerializer(ConfigFilePath + @"\KeyBindings.txt");
    }
        public void ShouldReturnCorrectConfig()
        {
            // Arrange
            var testConfig = new TestConfig();

            // System under Test
            var configSerializer = new ConfigSerializer();

            // Act
            configSerializer.SetDeserializedConfigs(XDocument.Parse(CONFIG_XML), new IConfigSection[] { testConfig });

            // Assert
            Assert.AreEqual("6fa5a650-25f3-4c86-a515-37e3163a54e9", testConfig.TestVar1);
        }
        public void ShouldReturnCorrectXml()
        {
            // Arrange
            var testConfig = new TestConfig { TestVar1 = "6fa5a650-25f3-4c86-a515-37e3163a54e9" };

            // System under Test
            var configSerializer = new ConfigSerializer();

            // Act
            var xmlDocument = configSerializer.GetSerializedConfigs(new IConfigSection[] { testConfig });

            // Assert
            Assert.AreEqual(CONFIG_XML.Replace(" ", ""), xmlDocument.ToString().Replace("\r\n", "").Replace(" ", ""));
        }
Esempio n. 4
0
        private void Write()
        {
            ConfigSerializer serializer = new ConfigSerializer();

            ConfigManager.Instance.SetSerializer(serializer);
            ConfigManager.Instance.ReloadConfigReaderModule(new XmlConfigReaderModule(PathManager.Instance.ExternalXmlConfigFolder, readXmlThread));

            using (BinWriter o = new BinWriter(PlatformManager.Instance.OpenWrite(PathManager.Instance.ExternalBinaryConfig), Encoding.UTF8))
            {
                ConfigManager.Instance.LoadAllConfig();
                if (serializer.Validate())
                {
                    serializer.WriteToBinary(o);
                }
            }
            PlatformManager.Instance.ClearDirectory(PathManager.Instance.ExternalXmlExampleFolder);
            new ConfigExampleBuilder().WriteExampleConfig(serializer, PathManager.Instance.ExternalXmlExampleFolder);
        }
Esempio n. 5
0
    public void Init(string workingDirectory)
    {
        var configFilePath       = this.configFileLocator.GetConfigFilePath(workingDirectory);
        var currentConfiguration = this.configFileLocator.ReadConfig(workingDirectory);

        var config = this.configInitWizard.Run(currentConfiguration, workingDirectory);

        if (config == null || configFilePath == null)
        {
            return;
        }

        using var stream = this.fileSystem.OpenWrite(configFilePath);
        using var writer = new StreamWriter(stream);
        this.log.Info("Saving config file");
        ConfigSerializer.Write(config, writer);
        stream.Flush();
    }
        public void Should_WriteSample_Multiline_String_Values()
        {
            // Given
            var builder = new StringBuilder();

            // When
            using (var writer = new StringWriter(builder))
            {
                ConfigSerializer.WriteSample(writer);
            }

            var text = builder.ToString();

            // Then
            var expectedText = string.Format("#  footer-content: >-{0}#    You can download this release from{0}#{0}#    [chocolatey](https://chocolatey.org/packages/chocolateyGUI/{{milestone}})", Environment.NewLine);

            Assert.That(text, Contains.Substring(expectedText));
        }
        public void Should_Write_Default_Boolean_Values()
        {
            // Given
            var config = new Config();

            config.Create.IncludeFooter = false; // Just to be sure it is a false value

            // When
            var builder = new StringBuilder();

            using (var writer = new StringWriter(builder))
            {
                ConfigSerializer.Write(config, writer);
            }

            // Then
            Assert.That(builder.ToString(), Contains.Substring("include-footer: false"));
        }
        public void Load()
        {
            ConfigSerializer.LoadConfig(this, FilePath);
            if (TwitchChannel.Length > 0)
            {
                TwitchChannel = TwitchChannel.ToLower().Replace(" ", "");
            }
            //else {
            //TwitchChannel = TwitchUsername;
            //}
            if (BackgroundPadding < 0)
            {
                BackgroundPadding = 0;
            }

            if (MaxMessages < 1)
            {
                MaxMessages = 1;
            }
        }
Esempio n. 9
0
        protected UnityConfigurationSection SerializeAndLoadConfig(string filename, Action <ContainerElement> containerInitializer)
        {
            var serializer = new ConfigSerializer(filename);
            var section    = new UnityConfigurationSection();

            section.SectionExtensions.Add(new SectionExtensionElement()
            {
                TypeName = typeof(InterceptionConfigurationExtension).AssemblyQualifiedName
            });

            var container = new ContainerElement();

            section.Containers.Add(container);

            containerInitializer(container);

            serializer.Save("unity", section);

            return((UnityConfigurationSection)serializer.Load().GetSection("unity"));
        }
        private static string GetOverrideConfigHash(Config overrideConfig)
        {
            if (overrideConfig == null)
            {
                return(string.Empty);
            }

            // Doesn't depend on command line representation and
            // includes possible changes in default values of Config per se.
            var stringBuilder = new StringBuilder();

            using (var stream = new StringWriter(stringBuilder))
            {
                ConfigSerializer.Write(overrideConfig, stream);
                stream.Flush();
            }
            var configContent = stringBuilder.ToString();

            return(GetHash(configContent));
        }
        public void Should_Read_Label_Aliases()
        {
            // Given
            var text = Resources.Default_Configuration_Yaml;

            using (var stringReader = new StringReader(text))
            {
                // When
                var config = ConfigSerializer.Read(stringReader);

                // Then
                Assert.AreEqual(2, config.LabelAliases.Count);
                Assert.AreEqual("Bug", config.LabelAliases[0].Name);
                Assert.AreEqual("Foo", config.LabelAliases[0].Header);
                Assert.AreEqual("Bar", config.LabelAliases[0].Plural);
                Assert.AreEqual("Improvement", config.LabelAliases[1].Name);
                Assert.AreEqual("Baz", config.LabelAliases[1].Header);
                Assert.AreEqual("Qux", config.LabelAliases[1].Plural);
            }
        }
Esempio n. 12
0
        public void Test_Serialize_SingleFieldType()
        {
            ExampleSingleFieldConfig configInstance = new ExampleSingleFieldConfig
            {
                firstField = new ExampleSingleFieldConfig.SingleFieldType1 {
                    secondField = new ExampleSingleFieldConfig.SingleFieldType2 {
                        a = 1, b = 2
                    }
                }
            };
            const string         expectedResult = @"
- a = 1
- b = 2
";
            IEnumerable <string> lines          = new ConfigSerializer(
                new ConfigOptions {
                keyFormatOption   = EFormatOption.QuoteValue,
                valueFormatOption = EFormatOption.QuoteValue
            }).Serialize(configInstance);

            Assert.AreEqual(expectedResult.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries), lines.ToArray());
        }
Esempio n. 13
0
        public Config(string filePath)
        {
            FilePath = filePath;

            if (!Directory.Exists(Path.GetDirectoryName(FilePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(FilePath));
            }

            if (File.Exists(FilePath))
            {
                Load();
                var text = File.ReadAllText(FilePath);
                if (!text.Contains("fitToCanvas") && Path.GetFileName(FilePath) == "cameraplus.cfg")
                {
                    fitToCanvas = true;
                }
                if (text.Contains("rotx"))
                {
                    var oldRotConfig = new OldRotConfig();
                    ConfigSerializer.LoadConfig(oldRotConfig, FilePath);

                    var euler = new Quaternion(oldRotConfig.rotx, oldRotConfig.roty, oldRotConfig.rotz, oldRotConfig.rotw).eulerAngles;
                    angx = euler.x;
                    angy = euler.y;
                    angz = euler.z;
                }
            }
            Save();

            _configWatcher = new FileSystemWatcher(Path.GetDirectoryName(FilePath))
            {
                NotifyFilter        = NotifyFilters.LastWrite,
                Filter              = Path.GetFileName(FilePath),
                EnableRaisingEvents = true
            };
            _configWatcher.Changed += ConfigWatcherOnChanged;
        }
Esempio n. 14
0
        public RootConfig(string filePath)
        {
            FilePath = filePath;

            if (!Directory.Exists(Path.GetDirectoryName(FilePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(FilePath));
            }

            if (File.Exists(FilePath))
            {
                ConfigSerializer.LoadConfig(this, FilePath);
            }

            PluginConfig.Instance.ProfileSceneChange    = ProfileSceneChange;
            PluginConfig.Instance.MenuProfile           = MenuProfile;
            PluginConfig.Instance.GameProfile           = GameProfile;
            PluginConfig.Instance.RotateProfile         = RotateProfile;
            PluginConfig.Instance.MultiplayerProfile    = MultiplayerProfile;
            PluginConfig.Instance.ProfileLoadCopyMethod = ProfileLoadCopyMethod;
            PluginConfig.Instance.CameraQuadLayer       = CameraQuadLayer;
            PluginConfig.Instance.ScreenFillBlack       = ScreenFillBlack;
        }
Esempio n. 15
0
        public virtual ActionResult UploadPhoto(string name, long id, HttpPostedFileBase file)
        {
            var al = Album.GetCountChange(id, 1);

            if (al == null)
            {
                return(HttpNotFound("album not found"));
            }
            var p = new Photo {
                Title = name, AlbumId = id, AddTime = DateTime.Now, UserId = WebUser.UserId
            };
            var f = new ImageUpload(file,
                                    WebContext,
                                    ConfigSerializer.Load <List <string> >("AllowImageExt")
                                    , p.AddTime,
                                    ConfigSerializer.Load <List <ThumbnailPair> >("ThumbnailSize")
                                    );

            f.Upload();
            p.Summary = f.Ext;
            Photo.Add(p);
            return(RedirectToAction("details", new{ id }));
        }
Esempio n. 16
0
        public override IEnumerable <string> Serialize(ConfigSerializer serializer, FieldInfo fieldInfo, SerializationInfo serializationInfo, int currentIndentation, int currentObjectDepth,
                                                       EFormatOption keyFormatOption, EFormatOption valueFormatOption)
        {
            IEnumerable <string> dataLines;

            keyFormatOption   = GetKeyFormatOption(keyFormatOption);
            valueFormatOption = GetValueFormatOption(valueFormatOption);

            if (serializationInfo.eDataType.IsSingleValueType())
            {
                string declarationString = ConfigSerializer.SerializeValueAssignmentDeclaration(name ?? fieldInfo.Name, currentIndentation + indentation, currentObjectDepth, keyFormatOption);
                string dataString        = ConfigSerializer.SerializeSingleValueType(serializationInfo, valueFormatOption);
                dataLines = new[] { declarationString + dataString };
            }
            else
            {
                string declarationString = ConfigSerializer.SerializeObjectAssignmentDeclaration(name ?? fieldInfo.Name, currentIndentation + indentation, currentObjectDepth, keyFormatOption);
                dataLines = new[] { declarationString }
                .Concat(serializer.SerializeMultiValueType(serializationInfo, currentIndentation + indentation, currentObjectDepth + 1, keyFormatOption, valueFormatOption));
            }
            return(Enumerable.Repeat("", emptyLinesAbove)
                   .Concat(comments.Select(comment => new string('\t', currentIndentation + indentation) + SpecialCharacters.singleLineComment + " " + comment))
                   .Concat(dataLines));
        }
Esempio n. 17
0
        public Config(string filePath)
        {
            FilePath = filePath;

            if (File.Exists(FilePath))
            {
                Load();
                var text = File.ReadAllText(FilePath);
                if (text.Contains("rotx"))
                {
                    var oldRotConfig = new OldRotConfig();
                    ConfigSerializer.LoadConfig(oldRotConfig, FilePath);

                    var euler = new Quaternion(oldRotConfig.rotx, oldRotConfig.roty, oldRotConfig.rotz,
                                               oldRotConfig.rotw)
                                .eulerAngles;
                    angx = euler.x;
                    angy = euler.y;
                    angz = euler.z;

                    Save();
                }
            }
            else
            {
                Save();
            }

            _configWatcher = new FileSystemWatcher(Environment.CurrentDirectory)
            {
                NotifyFilter        = NotifyFilters.LastWrite,
                Filter              = "cameraplus.cfg",
                EnableRaisingEvents = true
            };
            _configWatcher.Changed += ConfigWatcherOnChanged;
        }
Esempio n. 18
0
        private void CoreUI_FormClosing(object sender, FormClosingEventArgs e)
        {
            Globals.AttackOn   = false;
            Globals.AttackMode = false;
            Globals.Terminate  = true;

            if (RoomsPanel.Rooms.Count > 0)
            {
                RegistryUtil.Save();
                IniWriter.Save();
                ConfigSerializer.WriteFile("config.xml", Settings);
            }

            // clean up notifyicon
            if (mNotifyIcon != null)
            {
                mNotifyIcon.Visible = false;
                mNotifyIcon.Dispose();
                mNotifyIcon = null;
            }

            Application.Exit();
            Process.GetCurrentProcess().Kill();
        }
Esempio n. 19
0
        /// <summary>
        /// Loads a config from a file.
        /// If an instance is provided, the config will be loaded to that instance
        /// otherwise a new instance is created
        /// </summary>
        /// <param name="pathToFile">absolute path to the config file. '/' will be replaced with the DirectorySeparatorChar</param>
        /// <param name="instance">optional - instance of the existing config</param>
        /// <param name="configOptions">use this to configure the de/serializer</param>
        /// <typeparam name="TConfigType">type of the config to load</typeparam>
        /// <returns>instance of the loaded config</returns>
        public static TConfigType LoadConfigFile <TConfigType>(string pathToFile, [CanBeNull] TConfigType instance, ConfigOptions configOptions = null)
        {
            pathToFile = pathToFile.Replace('/', Path.DirectorySeparatorChar);
            if (!File.Exists(pathToFile))
            {
                if (instance == null)
                {
                    instance = (TConfigType)Activator.CreateInstance(typeof(TConfigType));
                }
                IEnumerable <string> lines = new ConfigSerializer(configOptions).Serialize(instance);

                using (StreamWriter writer = new StreamWriter(pathToFile, false)) {
                    foreach (string line in lines)
                    {
                        writer.WriteLine(line);
                    }
                }
                return(instance);
            }

            try {
                using (StreamReader reader = File.OpenText(pathToFile)) {
                    List <string> lines = new List <string>();
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null)
                        {
                            lines.Add(line);
                        }
                    }
                    ConfigDeserializer <TConfigType> deserializer = new ConfigDeserializer <TConfigType>(DeserializerUtils.Tokenize(lines).ToList(), configOptions);
                    return(instance == null?deserializer.Deserialize() : deserializer.Deserialize(instance));
                }
            } catch (Exception e) {
                Debug.LogError("Failed to load config at path: '" + pathToFile + "', caught exception: " + e);
                return(default);
Esempio n. 20
0
 public void Save()
 {
     _saving = true;
     ConfigSerializer.SaveConfig(this, FilePath);
     _saving = false;
 }
Esempio n. 21
0
 public void Load()
 {
     ConfigSerializer.LoadConfig(this, FilePath);
 }
 public abstract IEnumerable <string> Serialize(ConfigSerializer serializer, FieldInfo fieldInfo, SerializationInfo serializationInfo, int currentIndentation, int currentObjectDepth,
                                                EFormatOption keyFormatOption, EFormatOption valueFormatOption);
Esempio n. 23
0
    public static void SetupSerializers()
    {
		ConfigFilePath =  @"D:\TempDelete\Assets\Binds";
		defaultBindsSerializer = new ConfigSerializer(ConfigFilePath + @"\DefaultBindings.txt");
		keyBindsSerializer = new ConfigSerializer(ConfigFilePath + @"\KeyBindings.txt");
    }
 public void Load()
 {
     ConfigSerializer.LoadConfig(this, FilePath);
     CompileChargeCostString();
 }
Esempio n. 25
0
 private void ExportOnClick(object sender, RoutedEventArgs e)
 {
     _control.Config.Text = ConfigSerializer.ToJson(_config);
 }
Esempio n. 26
0
        public void Load()
        {
            ConfigSerializer.LoadConfig(this, FilePath);

            CorrectConfigSettings();
        }
Esempio n. 27
0
        static int Main(string[] argv)
        {
            bool        help        = false;
            bool        version     = false;
            bool        once        = false;
            StartClient startClient = StartClient.No;
            var         config      = new TypeCobolConfiguration();

            config.CommandLine = string.Join(" ", argv);
            var pipename = "TypeCobol.Server";

            var p = TypeCobolOptionSet.GetCommonTypeCobolOptions(config);

            //Add custom options for CLI
            p.Add(string.Format("USAGE\n {0} [OPTIONS]... [PIPENAME]\n VERSION:\n {1} \n DESCRIPTION: \n Run the TypeCObol parser server", PROGNAME, PROGVERSION));
            p.Add("k|startServer:",
                  "Start the server if not already started, and executes commandline.\n" + "By default the server is started in window mode\n" + "'{hidden}' hide the window.",
                  v =>
            {
                if ("hidden".Equals(v, StringComparison.InvariantCultureIgnoreCase))
                {
                    startClient = StartClient.HiddenWindow;
                }
                else
                {
                    startClient = StartClient.NormalWindow;
                }
            });
            p.Add("1|once", "Parse one set of files and exit. If present, this option does NOT launch the server.", v => once = (v != null));
            p.Add("h|help", "Output a usage message and exit.", v => help = (v != null));
            p.Add("V|version", "Output the version number of " + PROGNAME + " and exit.", v => version = (v != null));


            //Add DefaultCopies to running session
            var folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);

            config.CopyFolders.Add(folder + @"\DefaultCopies\");

            try {
                List <string> args;
                try {
                    args = p.Parse(argv);
                } catch (OptionException ex) {
                    return(exit(ReturnCode.FatalError, ex.Message));
                }

                if (help)
                {
                    p.WriteOptionDescriptions(Console.Out);
                    return(0);
                }
                if (version)
                {
                    Console.WriteLine(PROGVERSION);
                    return(0);
                }
                if (config.Telemetry)
                {
                    AnalyticsWrapper.Telemetry.DisableTelemetry = false; //If telemetry arg is passed enable telemetry
                }

                if (config.OutputFiles.Count == 0 && config.ExecToStep >= ExecutionStep.Generate)
                {
                    config.ExecToStep = ExecutionStep.SemanticCheck; //If there is no given output file, we can't run generation, fallback to SemanticCheck
                }
                if (config.OutputFiles.Count > 0 && config.InputFiles.Count != config.OutputFiles.Count)
                {
                    return(exit(ReturnCode.OutputFileError, "The number of output files must be equal to the number of input files."));
                }

                if (args.Count > 0)
                {
                    pipename = args[0];
                }


                //"startClient" will be true when "-K" is passed as an argument in command line.
                if (startClient != StartClient.No && once)
                {
                    pipename = "TypeCobol.Server";
                    using (NamedPipeClientStream namedPipeClient = new NamedPipeClientStream(pipename))
                    {
                        try {
                            namedPipeClient.Connect(100);
                        } catch (TimeoutException tEx) {
                            System.Diagnostics.Process          process   = new System.Diagnostics.Process();
                            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                            if (startClient == StartClient.NormalWindow)
                            {
                                startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                            }
                            else
                            {
                                startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                            }
                            startInfo.FileName  = "cmd.exe";
                            startInfo.Arguments = @"/c " + folder + Path.DirectorySeparatorChar + "TypeCobol.CLI.exe";
                            process.StartInfo   = startInfo;
                            process.Start();

                            namedPipeClient.Connect(1000);
                        }

                        namedPipeClient.WriteByte(68);

                        ConfigSerializer configSerializer = new ConfigSerializer();
                        var configBytes = configSerializer.Serialize(config);

                        namedPipeClient.Write(configBytes, 0, configBytes.Length);
                        //Wait for the response "job is done"
                        var returnCode = namedPipeClient.ReadByte(); //Get running server ReturnCode
                        return(exit((ReturnCode)returnCode, ""));
                    }
                }

                //option -1
                else if (once)
                {
                    var returnCode = CLI.runOnce(config);
                    if (returnCode != ReturnCode.Success)
                    {
                        return(exit(returnCode, "Operation failled"));
                    }
                }
                else
                {
                    runServer(pipename);
                }
            }
            catch (Exception e) {
                AnalyticsWrapper.Telemetry.TrackException(e);
                return(exit(ReturnCode.FatalError, e.Message));
            }

            return(exit((int)ReturnCode.Success, "Success"));
        }
Esempio n. 28
0
 protected override void OnAttached()
 {
     base.OnAttached();
     AssociatedObject.EditValue       = ConfigSerializer.GetConfig().KeyGesture;
     AssociatedObject.PreviewKeyDown += OnPreviewKeyDown;
 }
Esempio n. 29
0
        public ChatConfig()
        {
            Instance       = this;
            _configWatcher = new FileSystemWatcher();
            Task.Run(() =>
            {
                while (!Directory.Exists(Path.GetDirectoryName(FilePath)))
                {
                    Thread.Sleep(100);
                }

                Plugin.Log("FilePath exists! Continuing initialization!");

                string oldFilePath   = Path.Combine(Environment.CurrentDirectory, "UserData", "EnhancedTwitchChat.ini");
                string newerFilePath = Path.Combine(Globals.DataPath, "EnhancedTwitchChat.ini");
                if (File.Exists(newerFilePath))
                {
                    // Append the data to the blacklist, if any blacklist info exists, then dispose of the old config file.
                    AppendToBlacklist(newerFilePath);
                    if (!File.Exists(FilePath))
                    {
                        File.Move(newerFilePath, FilePath);
                    }
                    else
                    {
                        File.Delete(newerFilePath);
                    }
                }
                else if (File.Exists(oldFilePath))
                {
                    // Append the data to the blacklist, if any blacklist info exists, then dispose of the old config file.
                    AppendToBlacklist(oldFilePath);
                    if (!File.Exists(FilePath))
                    {
                        File.Move(oldFilePath, FilePath);
                    }
                    else
                    {
                        File.Delete(oldFilePath);
                    }
                }

                if (File.Exists(FilePath))
                {
                    Load();

                    var text = File.ReadAllText(FilePath);
                    if (text.Contains("TwitchUsername="******"{Plugin.ModuleName.Replace(" ", "")}.ini";
                _configWatcher.EnableRaisingEvents = true;

                _configWatcher.Changed += ConfigWatcherOnChanged;
            });
        }
Esempio n. 30
0
 public void WriteXml_NoFile_NoError()
 {
     ConfigSerializer.ReadXml(_testFilePath, new TestObject());
 }
Esempio n. 31
0
        public void Test_Serialize_SpecialCharOptions()
        {
            const string normalString           = "asdf";
            string       specialCharacterString = "" + SpecialCharacters.objectDepth + SpecialCharacters.valueAssignment + SpecialCharacters.objectAssignment
                                                  + SpecialCharacters.nullChar + SpecialCharacters.stringChar + SpecialCharacters.escapeChar;

            ExampleNullableConfig exampleNullableConfig = new ExampleNullableConfig {
                stringValue  = normalString,
                stringValue2 = specialCharacterString,
                stringList   = new List <string> {
                    normalString, specialCharacterString
                },
                subClassList = new List <ExampleNullableConfig.ExampleNullableSubClass> {
                    new ExampleNullableConfig.ExampleNullableSubClass {
                        a = normalString
                    },
                    new ExampleNullableConfig.ExampleNullableSubClass {
                        a = specialCharacterString
                    }
                },
                stringDict = new Dictionary <string, string> {
                    { normalString, normalString },
                    { specialCharacterString, specialCharacterString }
                },
                subClassDict = new Dictionary <string, ExampleNullableConfig.ExampleNullableSubClass> {
                    { normalString, new ExampleNullableConfig.ExampleNullableSubClass {
                          a = normalString
                      } },
                    { specialCharacterString, new ExampleNullableConfig.ExampleNullableSubClass {
                          a = specialCharacterString
                      } }
                }
            };

            string[] ExpectedLines(EFormatOption keyOpt, EFormatOption valueOpt)
            {
                return(new[] {
                    $"- {SpecialCharacters.FormatStringValue("intValue", keyOpt)} = {SpecialCharacters.FormatStringValue("1", valueOpt)}",
                    $"- {SpecialCharacters.FormatStringValue("stringValue", keyOpt)} = {SpecialCharacters.FormatStringValue(normalString, valueOpt)}",
                    $"- {SpecialCharacters.FormatStringValue("stringValue2", keyOpt)} = {SpecialCharacters.FormatStringValue(specialCharacterString, valueOpt)}",
                    $"- {SpecialCharacters.FormatStringValue("intList", keyOpt)} :",
                    $"-- {SpecialCharacters.FormatStringValue("1", valueOpt)}",
                    $"-- {SpecialCharacters.FormatStringValue("1", valueOpt)}",
                    $"- {SpecialCharacters.FormatStringValue("stringList", keyOpt)} :",
                    $"-- {SpecialCharacters.FormatStringValue(normalString, valueOpt)}",
                    $"-- {SpecialCharacters.FormatStringValue(specialCharacterString, valueOpt)}",
                    $"- {SpecialCharacters.FormatStringValue("subClassList", keyOpt)} :",
                    "-- :",
                    $"--- {SpecialCharacters.FormatStringValue("a", keyOpt)} = {SpecialCharacters.FormatStringValue(normalString, valueOpt)}",
                    $"--- {SpecialCharacters.FormatStringValue("b", keyOpt)} = {SpecialCharacters.FormatStringValue("1", valueOpt)}",
                    "-- :",
                    $"--- {SpecialCharacters.FormatStringValue("a", keyOpt)} = {SpecialCharacters.FormatStringValue(specialCharacterString, valueOpt)}",
                    $"--- {SpecialCharacters.FormatStringValue("b", keyOpt)} = {SpecialCharacters.FormatStringValue("1", valueOpt)}",
                    $"- {SpecialCharacters.FormatStringValue("intDict", keyOpt)} :",
                    $"-- {SpecialCharacters.FormatStringValue("1", keyOpt)} = {SpecialCharacters.FormatStringValue("1", valueOpt)}",
                    $"-- {SpecialCharacters.FormatStringValue("2", keyOpt)} = {SpecialCharacters.FormatStringValue("2", valueOpt)}",
                    $"- {SpecialCharacters.FormatStringValue("stringDict", keyOpt)} :",
                    $"-- {SpecialCharacters.FormatStringValue(normalString, keyOpt)} = {SpecialCharacters.FormatStringValue(normalString, valueOpt)}",
                    $"-- {SpecialCharacters.FormatStringValue(specialCharacterString, keyOpt)} = {SpecialCharacters.FormatStringValue(specialCharacterString, valueOpt)}",
                    $"- {SpecialCharacters.FormatStringValue("subClassDict", keyOpt)} :",
                    $"-- {SpecialCharacters.FormatStringValue(normalString, keyOpt)} :",
                    $"--- {SpecialCharacters.FormatStringValue("a", keyOpt)} = {SpecialCharacters.FormatStringValue(normalString, valueOpt)}",
                    $"--- {SpecialCharacters.FormatStringValue("b", keyOpt)} = {SpecialCharacters.FormatStringValue("1", valueOpt)}",
                    $"-- {SpecialCharacters.FormatStringValue(specialCharacterString, keyOpt)} :",
                    $"--- {SpecialCharacters.FormatStringValue("a", keyOpt)} = {SpecialCharacters.FormatStringValue(specialCharacterString, valueOpt)}",
                    $"--- {SpecialCharacters.FormatStringValue("b", keyOpt)} = {SpecialCharacters.FormatStringValue("1", valueOpt)}",
                });
            }

            foreach (EFormatOption keyOpt in (EFormatOption[])Enum.GetValues(typeof(EFormatOption)))
            {
                foreach (EFormatOption valueOpt in (EFormatOption[])Enum.GetValues(typeof(EFormatOption)))
                {
                    string[] resultLines = new ConfigSerializer(
                        new ConfigOptions {
                        keyFormatOption   = keyOpt,
                        valueFormatOption = valueOpt
                    }).Serialize(exampleNullableConfig).ToArray();
                    Assert.AreEqual(ExpectedLines(keyOpt, valueOpt), resultLines, "keyOpt: {0}, valueOpt: {1}", keyOpt, valueOpt);
                }
            }
        }
Esempio n. 32
0
        public void Test_Serialize_Implicitly()
        {
            /* Scenarios to check:
             *  - explicit by default, no override
             *    + implicit by default, override both types
             *  - explicit by default, override outer type
             *    + implicit by default, override inner type
             *  - explicit by default, override inner type
             *    + implicit by default, override outer type
             *  - explicit by default, override both types
             *    + implicit by default, no override
             */

            IEnumerable <string> GetLines(bool outerIsExplicit, bool innerIsExplicit)
            {
                if (!outerIsExplicit)
                {
                    yield return("- a = 3");
                }
                yield return("- b = 4");

                if (!outerIsExplicit)
                {
                    yield return("- subClass :");

                    if (!innerIsExplicit)
                    {
                        yield return("-- a = 5");
                    }
                    yield return("-- b = 6");
                }
            }

            ImplicitConfig configToSerialize = new ImplicitConfig(3, 4, new ImplicitConfig.SubClass(5, 6));

            void RunTest(bool outerIsExplicit, bool innerIsExplicit, ConfigOptions configOptions)
            {
                ConfigSerializer configDeserializer = new ConfigSerializer(configOptions);

                string[] resultLines   = configDeserializer.Serialize(configToSerialize).ToArray();
                string[] expectedLines = GetLines(outerIsExplicit, innerIsExplicit).ToArray();
                bool     areEqual      = resultLines.Length == expectedLines.Length && !resultLines.Except(expectedLines).Any();

                Assert.True(areEqual, "Expected lines: '{0}', Received Lines: '{1}'", string.Join("', '", expectedLines), string.Join("', '", resultLines));
            }

            Type outerType = typeof(ImplicitConfig);
            Type innerType = typeof(ImplicitConfig.SubClass);

            RunTest(true, true, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Explicit
            });
            RunTest(true, true, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Implicit, explicitTypes = new List <Type> {
                    outerType, innerType
                }
            });
            RunTest(false, true, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Explicit, implicitTypes = new List <Type> {
                    outerType
                }
            });
            RunTest(false, true, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Implicit, explicitTypes = new List <Type> {
                    innerType
                }
            });
            RunTest(true, false, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Explicit, implicitTypes = new List <Type> {
                    innerType
                }
            });
            RunTest(true, false, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Implicit, explicitTypes = new List <Type> {
                    outerType
                }
            });
            RunTest(false, false, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Explicit, implicitTypes = new List <Type> {
                    outerType, innerType
                }
            });
            RunTest(false, false, new ConfigOptions {
                fieldSelectorOption = EFieldSelectorOption.Implicit
            });
        }
Esempio n. 33
0
        public CoreUI()
        {
            InitializeComponent();

            // silver vs2008 toolstrip look
            TanColorTable colorTable = new TanColorTable();

            colorTable.UseSystemColors = true;
            toolStrip.Renderer         = new ToolStripProfessionalRenderer(colorTable);

            // fill panels
            AccountsPanel      = new AccountsPanel(this);
            AccountsPanel.Dock = DockStyle.Fill;
            splitLeftRight.Panel1.Controls.Add(AccountsPanel);

            LogPanel      = new LogPanel();
            LogPanel.Dock = DockStyle.Fill;
            splitTopBottom.Panel1.Controls.Add(LogPanel);

            mAttackPanel      = new AttackPanel(this);
            mAttackPanel.Dock = DockStyle.Fill;
            tabs.TabPages[TABINDEX_ATTACK].Controls.Add(mAttackPanel);

            /*
             * MainPanel = new MainPanel(this);
             * MainPanel.Dock = DockStyle.Fill;
             * splitLeftRight2.Panel1.Controls.Add(MainPanel);
             */

            mFiltersPanel      = new FiltersPanel(this);
            mFiltersPanel.Dock = DockStyle.Fill;
            tabs.TabPages[TABINDEX_FILTERS].Controls.Add(mFiltersPanel);

            RoomsPanel      = new RoomsPanel(this);
            RoomsPanel.Dock = DockStyle.Fill;
            tabs.TabPages[TABINDEX_ROOMS].Controls.Add(RoomsPanel);

            MobsPanel      = new MobsPanel(this);
            MobsPanel.Dock = DockStyle.Fill;
            tabs.TabPages[TABINDEX_MOBS].Controls.Add(MobsPanel);

            RaidsPanel      = new RaidsPanel(this);
            RaidsPanel.Dock = DockStyle.Fill;
            tabs.TabPages[TABINDEX_RAIDS].Controls.Add(RaidsPanel);

            SpawnsPanel      = new SpawnsPanel(this);
            SpawnsPanel.Dock = DockStyle.Fill;
            tabs.TabPages[TABINDEX_SPAWNS].Controls.Add(SpawnsPanel);

            mTrainPanel      = new TrainPanel(this);
            mTrainPanel.Dock = DockStyle.Fill;
            tabs.TabPages[TABINDEX_TRAINER].Controls.Add(mTrainPanel);

            mTalkPanel      = new TalkPanel(this);
            mTalkPanel.Dock = DockStyle.Fill;
            tabs.TabPages[TABINDEX_TALK].Controls.Add(mTalkPanel);

            ChatPanel      = new ChatUI(this);
            ChatPanel.Dock = DockStyle.Fill;
            tabs.TabPages[TABINDEX_CHAT].Controls.Add(ChatPanel);

            Instance = this;
            Settings = ConfigSerializer.ReadFile("config.xml");

            this.Text = "Typpo's DC Tool - [www.typpo.us] - v" + Version.Id;

            foreach (string s in Server.NamesList)
            {
                ListViewGroup grp = new ListViewGroup(s);
                AccountsPanel.Groups.Add(grp);
            }
        }
Esempio n. 34
0
        public void Test_SerializeNullValues()
        {
            ExampleNullableConfig exampleNullableConfig = new ExampleNullableConfig {
                stringValue  = null,
                stringValue2 = "~",
                stringList   = new List <string> {
                    null, "~"
                },
                subClassList = new List <ExampleNullableConfig.ExampleNullableSubClass> {
                    new ExampleNullableConfig.ExampleNullableSubClass {
                        a = null
                    },
                    new ExampleNullableConfig.ExampleNullableSubClass {
                        a = "~"
                    }
                },
                stringDict = new Dictionary <string, string> {
                    { "str1", null },
                    { "~", "~" }
                },
                subClassDict = new Dictionary <string, ExampleNullableConfig.ExampleNullableSubClass> {
                    { "str1", new ExampleNullableConfig.ExampleNullableSubClass {
                          a = null
                      } },
                    { "~", new ExampleNullableConfig.ExampleNullableSubClass {
                          a = "~"
                      } }
                }
            };

            const string expectedResult = @"
- intValue = 1
- stringValue = ~
- stringValue2 = ""~""
- intList :
-- 1
-- 1
- stringList :
-- ~
-- ""~""
- subClassList :
-- :
--- a = ~
--- b = 1
-- :
--- a = ""~""
--- b = 1
- intDict :
-- 1 = 1
-- 2 = 2
- stringDict :
-- str1 = ~
-- ""~"" = ""~""
- subClassDict :
-- str1 :
--- a = ~
--- b = 1
-- ""~"" :
--- a = ""~""
--- b = 1
";

            IEnumerable <string> lines = new ConfigSerializer(
                new ConfigOptions {
                keyFormatOption   = EFormatOption.QuoteValue,
                valueFormatOption = EFormatOption.QuoteValue
            }).Serialize(exampleNullableConfig);

            Assert.AreEqual(expectedResult.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries), lines.ToArray());
        }