Exemplo n.º 1
0
        public void IsSectionLessKeyLessFileParsed()
        {
            // Arrange
            var redisConfig  = RealWorldConfigFiles.FirstOrDefault(f => f.EndsWith("redis.conf", StringComparison.OrdinalIgnoreCase));
            var configParser = new ConfigParser(
                redisConfig,
                new ConfigParserSettings
            {
                MultiLineValues   = MultiLineValues.AllowValuelessKeys | MultiLineValues.AllowEmptyTopSection,
                KeyValueSeparator = " ",
            }
                );

            // Act
            var clientBufferLimitValue = configParser.NullSection.GetValue("client-output-buffer-limit");

            // Assert
            Assert.Equal("normal 0 0 0", clientBufferLimitValue, ignoreCase: true);
        }
Exemplo n.º 2
0
        public void NonExistingFileWorks()
        {
            ConfigParser configFileFromMem = null;

            try
            {
                var notExistingFilePath = $"{Path.GetTempFileName()}.conf";
                configFileFromMem = new ConfigParser(notExistingFilePath, new ConfigParserSettings
                {
                    MultiLineValues = MultiLineValues.Simple | MultiLineValues.QuoteDelimitedValues,
                    Encoding        = new UTF8Encoding(false, false),
                    NewLine         = "\n"
                });
            }
            finally
            {
                Assert.NotNull(configFileFromMem);
            }
        }
Exemplo n.º 3
0
        public void MultilineValuesAreParsedCorrectly()
        {
            var multiLineDelimitedFilePath = StructureSampleFiles.FirstOrDefault(f =>
                                                                                 f.EndsWith("multi-line.ini", StringComparison.OrdinalIgnoreCase));

            Assert.NotNull(multiLineDelimitedFilePath);

            var configFile = new ConfigParser(multiLineDelimitedFilePath, new ConfigParserSettings
            {
                MultiLineValues = MultiLineValues.Simple,
            });
            var multiLineDelimitedValue = configFile.GetValue("Multiline Values", "chorus", string.Empty);

            Assert.Equal(
                "I'm a lumberjack, and I'm okay\n" +
                "    I sleep all night and I work all day",
                multiLineDelimitedValue
                );
        }
Exemplo n.º 4
0
 public bool Initialize(string workdir)
 {
     logger.Debug("Initialize: " + workdir);
     if (ConfigParser.Load(directory: workdir, config: Config))
     {
         _valid = true;
         Config.WorkDirectory = workdir;
         if ((Config.RoomList?.Count ?? 0) > 0)
         {
             Config.RoomList.ForEach((r) => AddRoom(r.Roomid, r.Enabled));
         }
         ConfigParser.Save(Config.WorkDirectory, Config);
         return(true);
     }
     else
     {
         return(false);
     }
 }
Exemplo n.º 5
0
        private void setLocalIgnoreFileSetting(string file)
        {
            var parser       = new ConfigParser("");
            var globalConfig = parser.Parse();

            if (globalConfig.IgnoreFile.Exists && globalConfig.IgnoreFile.Item.File == file)
            {
                _writer.SetIgnoreFilePath("");
            }
            else
            {
                _writer.SetIgnoreFilePath(file);
            }

            if (_writer.Configuration.IgnoreFile.Exists && File.Exists(Path.Combine(_writer.Configuration.IgnoreFile.Item.ContentPath, file)))
            {
                readPatterns(file);
            }
        }
Exemplo n.º 6
0
        //private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static int Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            Directory.SetCurrentDirectory(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location));

            // Check if the webroot is already defined
            if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("WEBROOT")))
            {
                // Use the webroot in the target folder, if any
                if (Directory.Exists("webroot"))
                {
                    Environment.SetEnvironmentVariable("WEBROOT", Path.GetFullPath("webroot"));
                }
#if DEBUG
                // In debug mode, assume we are in ./bin/Debug,
                // so move back and find webroot in the project folder
                else
                {
                    Environment.SetEnvironmentVariable("WEBROOT", Path.GetFullPath("../../webroot"));
                }
#endif
            }

            // Set a default listen port
            if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("LISTEN_PORT")))
            {
                Environment.SetEnvironmentVariable("LISTEN_PORT", "8080");
            }

            if (args == null || args.Length == 0)
            {
                args = new string[] { "config.txt" }
            }
            ;

            // Try to parse the config file so we can report the settings
            var config = ConfigParser.ParseTextFile(args[0]);
            Console.WriteLine("Listening to port {0}, serving {1}", config.HttpPort, config.Routes.Where(x => x.Assembly == "Ceen.Httpd" && x.Classname == "Ceen.Httpd.Handler.FileHandler").Select(x => ConfigParser.ExpandEnvironmentVariables(x.ConstructorArguments.FirstOrDefault())).FirstOrDefault());

            return(Ceen.Httpd.Cli.Program.Main(args));
        }
    }
Exemplo n.º 7
0
        internal ModifyData(string path)
        {
            var st = path.LastIndexOf('\\') + 1;
            var ed = path.LastIndexOf(".config.ini");

            if (st > 0 && ed > st)
            {
                this.FileName = path.Substring(st, ed - st);
            }
            else
            {
                this.FileName = "Unknown";
            }

            this.Data = new Dictionary <string, string>();
            var parser = ConfigParser.ReadIniFile(path);

            if (parser["info"] != null)
            {
                this.Data.Add("ship_name", parser["info"]["ship_name"]);
            }
            else
            {
                this.Data.Add("ship_name", null);
            }
            if (parser["graph"] != null)
            {
                var modList = new string[] { "boko_n", "boko_d",
                                             "kaisyu_n", "kaisyu_d",
                                             "kaizo_n", "kaizo_d",
                                             "map_n", "map_d",
                                             "ensyuf_n", "ensyuf_d",
                                             "ensyue_n",
                                             "battle_n", "battle_d",
                                             "weda", "wedb" };
                foreach (var mod in modList)
                {
                    this.Data.Add(mod + "_left", parser["graph"][mod + "_left"]);
                    this.Data.Add(mod + "_top", parser["graph"][mod + "_top"]);
                }
            }
        }
Exemplo n.º 8
0
        internal static void ProcessConfigFile(
            ProjectMetadata projectMetadata,
            string filename,
            string extension,
            string content)
        {
            _logger.Trace("Entering");

            // ReSharper disable once PossibleNullReferenceException
            if (filename.StartsWith("app.", StringComparison.CurrentCultureIgnoreCase)
                &&
                extension.EndsWith("config", StringComparison.CurrentCultureIgnoreCase))
            {
                var configFile = ConfigParser.ParseAppConfigFileContent(content, filename);
                projectMetadata.AppSettings.AddRange(configFile.ApplicationSettings);
            }
            else if (filename.StartsWith("web.", StringComparison.CurrentCultureIgnoreCase)
                     &&
                     extension.Equals(".config", StringComparison.CurrentCultureIgnoreCase))
            {
                var configFile = ConfigParser.ParseWebConfigFileContent(content, filename);
                projectMetadata.AppSettings.AddRange(configFile.AppSettings);
            }
            else if (filename.StartsWith("dataConfiguration", StringComparison.CurrentCultureIgnoreCase)
                     &&
                     extension.Equals(".config", StringComparison.CurrentCultureIgnoreCase))
            {
                var configFile = ConfigParser.ParseDataConfigurationFileContent(content, filename);
                projectMetadata.ConnectionStrings = configFile.ConnectionStrings;
                projectMetadata.DatabaseInstances = configFile.DatabaseInstances;
                projectMetadata.DatabaseTypes     = configFile.DatabaseTypes;
            }
            else if (filename.StartsWith("appSettings", StringComparison.CurrentCultureIgnoreCase)
                     &&
                     extension.Equals(".json", StringComparison.CurrentCultureIgnoreCase))
            {
                var configFile = ConfigParser.ParseAppSettingsJsonFileContent(content);
                projectMetadata.ConnectionStrings = configFile.GetConnectionStrings().ToList();
                projectMetadata.DatabaseInstances = null;
                projectMetadata.DatabaseTypes     = null;
            }
        }
Exemplo n.º 9
0
        public OptLayout(Panel layout, int blinkMax)
        {
            pnlLayout                 = layout;
            optIn                     = pnlLayout.Controls.Find("txtOptIn", true).FirstOrDefault() as CheckBox;
            smOptInY                  = pnlLayout.Controls.Find("txtSmOptInY", true).FirstOrDefault() as RadioButton;
            smOptInN                  = pnlLayout.Controls.Find("txtSmOptInN", true).FirstOrDefault() as RadioButton;
            smOptInText               = pnlLayout.Controls.Find("txtSmOptIn", true).FirstOrDefault() as RichTextBoxEx;
            smOptInBg                 = pnlLayout.Controls.Find("imgSmOpInBg", true).FirstOrDefault() as PictureBoxEx;
            txtTitle                  = pnlLayout.Controls.Find("txtTitle", true).FirstOrDefault() as RichTextBoxEx;
            darkenProductOverlay      = pnlLayout.Controls.Find("pnlDarkenOverlay", true).FirstOrDefault() as Panel;
            darkenProductOverlay.Size = pnlLayout.Size;

            imgDarkenOverlay = new PictureBox
            {
                Anchor   = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right,
                Location = pnlLayout.Location,
                Name     = "imgDarkenOverlay",
                Size     = pnlLayout.Size,
                TabStop  = false,
                Visible  = false
            };
            pnlLayout.Controls.Add(imgDarkenOverlay);

            string opt = ConfigParser.GetConfig().GetStringValue("//RemoteConfiguration/FlowSettings/OptType", OptType.IN);

            if (opt == OptType.SMART && (smOptInText == null || string.IsNullOrEmpty(smOptInText.Text))) // Fallback if the remote config not relevant
            {
                opt = OptType.IN;
            }
            if (opt == OptType.IN)
            {
                optIn.Visible = true;
            }
            else if (opt == OptType.SMART)
            {
                smOptInY.Visible = true;
                smOptInN.Visible = true;
            }
            this.opt      = opt;
            this.blinkMax = blinkMax;
            InitTimer();
        }
Exemplo n.º 10
0
        protected async override System.Threading.Tasks.Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            if (await GetServiceAsync(typeof(IMenuCommandService)) is OleMenuCommandService commandService)
            {
                ThreadHelper.Generic.BeginInvoke(DispatcherPriority.ContextIdle, () =>
                {
                    if (commandService != null)
                    {
                        var extentionPath = Path.GetDirectoryName(this.GetType().Assembly.Location);
                        var dllPath       = Path.Combine(extentionPath, Constants.CLIFolderName, Constants.CLIName);
                        var configPath    = Path.Combine(extentionPath, Constants.CLIFolderName, Constants.ConfigFileName);

                        CliDownloader.SetUp(dllPath);

                        var fileInfo = new FileInfo(configPath);

                        if (!fileInfo.Exists)
                        {
                            var args    = string.Format("{0} config", Constants.CLIName);
                            var process = new Process();
                            process.StartInfo.WorkingDirectory       = fileInfo.DirectoryName;
                            process.StartInfo.RedirectStandardOutput = true;
                            process.StartInfo.UseShellExecute        = false;
                            process.StartInfo.CreateNoWindow         = true;
                            process.StartInfo.FileName  = Constants.DotNetCoreProcessName;
                            process.StartInfo.Arguments = args;
                            process.Start();
                            process.WaitForExit();
                        }

                        this.configParser        = new ConfigParser(configPath);
                        var dynamicCommandRootId = new CommandID(PackageGuids.guidPackageCommandSet, PackageIds.DynamicCommandId);
                        var dynamicCommand       = new DynamicCommand(dynamicCommandRootId, IsValidDynamicItem, OnInvokedDynamicItem, OnBeforeQueryStatusDynamicItem);
                        commandService.AddCommand(dynamicCommand);

                        var aboutCommandRootId = new CommandID(PackageGuids.guidPackageCommandSet, PackageIds.AboutCommandId);
                        var aboutCommand       = new AboutCommand(OnInvokeAboutCommand, aboutCommandRootId, dllPath);
                        commandService.AddCommand(aboutCommand);
                    }
                });
            }
        }
Exemplo n.º 11
0
        public bool Load(TextReader reader, IErrorReporter reporter, ICodeGeneratorEnv environment)
        {
            var wrapper = new ReporterWrapper(reporter);

            _loadStart       = null;
            _parseDone       = null;
            _calculationDone = null;
            _tableDone       = null;

            _loadStart = DateTime.Now;

            var parser = new ConfigParser(wrapper);
            var config = parser.Parse(new ConfigScanner(reader.ReadToEnd()));

            _parseDone = DateTime.Now;

            if (wrapper.HasError)
            {
                _config = null;
                return(false);
            }

            SyntaxTreeDecorator.Decorate(config, wrapper);
            _calculationDone = DateTime.Now;

            if (wrapper.HasError)
            {
                _config = null;
                return(false);
            }

            _data      = TableGenerator.GenerateTables(config);
            _tableDone = DateTime.Now;

            if (!config.Manager.SuppressTableEmbedding)
            {
                config.TableResourceName = environment.GetResourceName(ParserTableFile.Suffix);
            }

            _config = config;
            return(true);
        }
Exemplo n.º 12
0
        public void JoinMultilineValueWorks()
        {
            // Set up
            var settings = new ConfigParserSettings {
                MultiLineValues = MultiLineValues.Simple
            };
            var configFile = new ConfigParser(
                @"[Advanced]
ExampleValue = Lorem ipsum dolor sit amet
consectetur adipiscing elit
sed do eiusmod tempor incididunt
                ",
                settings);

            // Act
            var multiLineJoint = configFile.JoinMultilineValue("Advanced", "ExampleValue", " ");

            // Assert
            Assert.Equal("Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt", multiLineJoint);
        }
Exemplo n.º 13
0
        public void FetchConfig_CustomActionParameter_IsDeserialized()
        {
            var config   = ConfigParser.ParseFromJson(@"
{
	""fetchConfig"": {
		""parameters"": [
			{
				""name"": ""test"",
				""type"": ""string""
			}
		]
	}
}
");
            var oneParam = config.FetchConfig.Parameters[0];

            Assert.AreEqual(ParameterKind.Custom, oneParam.Kind);
            Assert.AreEqual("test", oneParam.Name);
            Assert.AreEqual("string", oneParam.Type);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Adds a new keybind and updates the keybind listbox. Overwrites the config file
        /// </summary>
        private void buttonNewKeybind_Click(object sender, EventArgs e)
        {
            //Make this new one the selected one
            foreach (KeybindSound bind in config.KeybindSounds)
            {
                bind.IsSelected = false;
            }
            config.KeybindSounds.Add(new KeybindSound {
                IsSelected = true
            });

            //Update the listbox
            UpdateKeybindListboxAndControls();

            //Register the HotkeyTriggered event
            selectedKeybind.HotkeyTriggered += Bind_HotkeyTriggered;

            //Overwrite the config file
            ConfigParser.SaveFile(Useful.pathToConfig, config);
        }
Exemplo n.º 15
0
        public void IndexAccessWorks()
        {
            var indentedFilePath =
                StructureSampleFiles.FirstOrDefault(f =>
                                                    f.EndsWith("indented.ini", StringComparison.OrdinalIgnoreCase));

            Assert.NotNull(indentedFilePath);

            var configFile = new ConfigParser(indentedFilePath, new ConfigParserSettings
            {
                MultiLineValues = MultiLineValues.Simple
            });
            var valueReadUsingIndexing =
                configFile["Sections Can Be Indented"]["can_values_be_as_well"] ?? string.Empty;

            Assert.Equal(
                "True",
                valueReadUsingIndexing
                );
        }
Exemplo n.º 16
0
        public void GetRuleSetWithSingleRule()
        {
            // Arrange
            var badConfigFile = @"TestConfigFiles\TestConfig_ProjectAlphaSingleRule.xml";
            var project       = "ProjectAlpha";

            // Act
            var ruleset = ConfigParser.GetRuleSetForProject(badConfigFile, project);

            // Assert
            Assert.IsNotNull(ruleset);
            Assert.IsTrue(ruleset.IsRules);
            Assert.AreEqual(1, ruleset.Rules.Count);

            var actRule = ruleset.Rules[0] as MultiRefRule;

            Assert.IsNotNull(actRule);
            Assert.AreEqual(RuleType.OnlyLocalReferences, actRule.Type);
            Assert.AreEqual(0, actRule.Refs.Count);
        }
Exemplo n.º 17
0
        ///<summary>
        ///Reads the configuration from "%USERPROFILE%/.SwapQL.conf" and parses its content.
        ///</summary>
        ///<exception cref="System.IO.FileNotFoundException"></exception>
        public static void ReadConfig()
        {
            var path = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

            if (!File.Exists($"{path}/.SwapQL.conf"))
            {
                throw new FileNotFoundException("Config file not found!", $"{path}/.SwapQL.conf");
            }

            var parser = new ConfigParser($"{path}/.SwapQL.conf",
                                          new ConfigParserSettings()
            {
                MultiLineValues = MultiLineValues.Simple | MultiLineValues.AllowEmptyTopSection
            });

            Target = new AccessInfo(parser["target"]);
            Source = new AccessInfo(parser["source"]);

            PrintConfig(parser);
        }
Exemplo n.º 18
0
        public void SaveQuickSettings(object sender, EventArgs e)
        {
            if (!quickSettingsInitialized)
            {
                return;
            }

            if (Program.busy)
            {
                LoadQuickSettings();    // Discard any changes if busy
            }
            ConfigParser.SaveGuiElement(maxVidHeight, ConfigParser.StringMode.Int);
            ConfigParser.SaveComboxIndex(dedupMode);
            ConfigParser.SaveComboxIndex(mpdecimateMode);
            ConfigParser.SaveGuiElement(dedupThresh);
            ConfigParser.SaveGuiElement(enableLoop);
            ConfigParser.SaveGuiElement(scnDetect);
            ConfigParser.SaveGuiElement(scnDetectValue);
            ConfigParser.SaveGuiElement(maxFps);
        }
Exemplo n.º 19
0
        private void saveDisableAnonFeedback()
        {
            if (_anonFeedbackOriginalValue == checkBoxAnalytics.Checked)
            {
                return;
            }
            if (!_isLocal)
            {
                _writer.Configuration.AnonFeedback.Exists = true;
                _writer.Configuration.AnonFeedback.Item   = checkBoxAnalytics.Checked;
                return;
            }
            var config = new ConfigParser("").ParseGlobal();

            config.AnonFeedback.Exists = true;
            config.AnonFeedback.Item   = checkBoxDisableAll.Checked;
            var content = new ConfigWriter().Transform(config);

            saveConfiguration(config.ConfigurationFullpath, content);
        }
Exemplo n.º 20
0
        public static void ParseAppSettingsJsonFileContent_ReturnsExpectedValues()
        {
            var content = Helpers.ReadEmbeddedResourceFile("AppSettings.tok.json.txt");

            var result = ConfigParser.ParseAppSettingsJsonFileContent(content);

            Assert.That(result, Is.Not.Null);

            Assert.Multiple(() =>
            {
                Assert.That(result.AppSettings?.Count, Is.EqualTo(12), nameof(result.AppSettings) + " count");
                Assert.That(result.AppSettings?["EnableSwagger"], Is.EqualTo("%{ENABLE_SWAGGER}%"),
                            nameof(result.AppSettings) + " - EnableSwagger");

                Assert.That(result.ConnectionStrings, Is.Not.Null, nameof(result.ConnectionStrings));
                Assert.That(result.ConnectionStrings?.Count, Is.EqualTo(4),
                            nameof(result.ConnectionStrings) + " count");
                Assert.That(result.ConnectionStrings?["RedisConnection"], Is.EqualTo("%{REDIS_CONNECTION}%"),
                            nameof(result.ConnectionStrings) + " - RedisConnection");

                Assert.That(result.CoreMonitoringSettingsConfiguration?.Count, Is.EqualTo(2),
                            nameof(result.CoreMonitoringSettingsConfiguration) + " count");

                Assert.That(result.CoreServiceBusConfiguration?.Count, Is.EqualTo(9),
                            nameof(result.CoreServiceBusConfiguration) + " count");

                Assert.That(result.CorePersistenceSettingsConfiguration?.Count, Is.EqualTo(1),
                            nameof(result.CorePersistenceSettingsConfiguration) + " count");
                Assert.That(result.CorePersistenceSettingsConfiguration?["DbConnectionName"], Is.Not.Null,
                            nameof(result.CorePersistenceSettingsConfiguration) + " - DbConnectionName");

                Assert.That(result.OAuth2?.Count, Is.EqualTo(2), nameof(result.OAuth2) + " count");
                Assert.That(result.OAuth2?["Authority"], Is.EqualTo("%{AZURE_AD_AUTHORITY}%"),
                            nameof(result.OAuth2) + " - Authority");
                Assert.That(result.OAuth2?["ApplicationId"], Is.EqualTo("%{AZURE_AD_APP_ID}%"),
                            nameof(result.OAuth2) + " - ApplicationId");
            }
                            );

            // todo Do more asserts here?
        }
Exemplo n.º 21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Ceen.Httpd.Cli.UnixSpawn.SpawnedServer"/> class.
        /// </summary>
        /// <param name="usessl">If set to <c>true</c> usessl.</param>
        /// <param name="configfile">Configfile.</param>
        /// <param name="storage">Storage.</param>
        public SpawnedServer(bool usessl, string configfile, IStorageCreator storage)
        {
            //// Mono version
            //var safeSocketHandleType = Type.GetType("System.Net.Sockets.SafeSocketHandle");
            //var safeSocketHandleConstructor = safeSocketHandleType?.GetConstructor(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic, null, new Type[] { typeof(IntPtr), typeof(bool) }, null);
            //var socketConstructorSafeSocketHandle = safeSocketHandleType == null ? null : typeof(System.Net.Sockets.Socket).GetConstructor(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic, null, new Type[] { typeof(AddressFamily), typeof(SocketType), typeof(ProtocolType), safeSocketHandleType }, null);

            //// .Net Core version
            //var safeCloseSocketType = Type.GetType("System.Net.Sockets.SafeCloseSocket");
            //var safeCloseSocketConstructor = safeCloseSocketType?.GetMethod("CreateSocket", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static, null, new Type[] { typeof(IntPtr) }, null);
            //var socketConstructorSafeCloseSocket = safeCloseSocketType == null ? null : typeof(System.Net.Sockets.Socket).GetConstructor(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic, null, new Type[] { safeCloseSocketType }, null);

            //if (safeSocketHandleConstructor != null && socketConstructorSafeSocketHandle != null)
            //    m_createSocket = (handle) => (Socket)Activator.CreateInstance(typeof(Socket), AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp, Activator.CreateInstance(safeSocketHandleType, new IntPtr(handle), false));
            //else if (safeCloseSocketConstructor != null && socketConstructorSafeCloseSocket != null)
            //    m_createSocket = (handle) => (Socket)Activator.CreateInstance(typeof(Socket), safeCloseSocketConstructor.Invoke(null, new object[] { new IntPtr(handle) }));
            //else
            //throw new Exception("Unable to find a method to create sockets from handles ....");

            var config = ConfigParser.ValidateConfig(ConfigParser.ParseTextFile(configfile));

            config.Storage = storage ?? new MemoryStorageCreator();

            try
            {
                m_pollhandler = new SockRock.KqueueHandler();
            }
            catch (Exception e1)
            {
                try
                {
                    m_pollhandler = new SockRock.EpollHandler();
                }
                catch (Exception e2)
                {
                    throw new PlatformNotSupportedException("Unable to create kqueue or epoll instance", new AggregateException(e1, e2));
                }
            }

            base.Setup(usessl, config);
        }
Exemplo n.º 22
0
        static object GenerateScanGraph(string text)
        {
            var errorReporter = new Mock <IErrorReporter>(MockBehavior.Strict);

            var parser = new ConfigParser(errorReporter.Object);
            var config = parser.Parse(new ConfigScanner(text));
            var state  = config.States[0];

            var nfa   = new Graph.Builder();
            var start = nfa.NewState(true, new NodeData(0, null));

            for (var i = 0; i < state.Rules.Count; i++)
            {
                var rule    = state.Rules[i];
                var element = ReParser.Parse(rule.Regex.Text);

                element.GenerateNFA(nfa, start, nfa.NewState(false, new NodeData(null, i)));
            }

            return(FATools.CreateDfa(nfa.Graph));
        }
Exemplo n.º 23
0
        public void TestInit()
        {
            textDoc = new XmlDocument();
            textDoc.Load(File.OpenRead(@"Resources\\empty_main.xml"));

            XmlDocument responseDoc = new XmlDocument();

            responseDoc.Load(File.OpenRead(@"Resources\\response_example.xml"));

            XmlDocument customDataDoc = new XmlDocument();

            customDataDoc.Load(File.OpenRead(@"Resources\\custom_data_example.xml"));

            configParser = new ConfigParser(textDoc);
            foreach (XmlNode productNode in responseDoc.SelectNodes("//RemoteConfiguration/Products/Product/StaticData"))
            {
                XmlParser.SetNode(responseDoc, productNode.SelectSingleNode("//CustomData"), customDataDoc.SelectSingleNode("//CustomData/CustomVars"));
                XmlParser.SetNode(textDoc, textDoc.SelectSingleNode("//Products/Product"), productNode);
                configParser.EvalCustomVariables(textDoc.SelectSingleNode("//Products/Product/StaticData/CustomData/CustomVars"));
            }
        }
Exemplo n.º 24
0
        public ApiHandler()
        {
            _httpClientHandler = new HttpClientHandler();
            _httpClientHandler.AllowAutoRedirect     = false;
            _httpClientHandler.UseDefaultCredentials = true;

            _httpClient             = new HttpClient(_httpClientHandler);
            _httpClient.BaseAddress = new Uri(ConfigParser.getInstance("").getApiUrl());
            _httpClient.MaxResponseContentBufferSize = 256000;
            TimeSpan timeout = TimeSpan.FromSeconds(20);

            _httpClient.Timeout = timeout;
            _httpClient.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/apng,*/*;q=0.8");
            _httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
            _httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
            _httpClient.DefaultRequestHeaders.Add("Accept-Language", "en-GB,en;q=0.9,en-US;q=0.8");
            _httpClient.DefaultRequestHeaders.Add("Connection", "keep-alive");
            _httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
            _httpClient.DefaultRequestHeaders.Add("Pragma", "no-cache");
            _httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko; Google Page Speed Insights) Chrome/27.0.1453 Safari/537.36");
        }
Exemplo n.º 25
0
        static void Main(string[] args)
        {
            //Jei dar tobulinant tai tikriausiai padaryciau:
            //gudresni failu eiles pasirinkima kad nereiketu atsidayt kodo ir perkompiliuot
            //Parameter klaseje optiona nurodyti kokio tipo tai value.
            //Parametro access galbut padaryti pagal pilna path rakta ("Section", "SubSection","Key")
            var configParser = new ConfigParser("Data/Base_Config.txt", "Data/Project_Config.txt");
            var parameters   = configParser.LoadAllParameters();
            var printer      = new Printer();

            printer.PrintAllParameters(parameters);
            printer.PrintParameter(
                parameters, new List <string>()
            {
                "NumberOfSystems",
                "OrdersPerHour",
                "OrderLinesPerOrder",
                "ResultStartTime"
            });
            Console.ReadKey();
        }
Exemplo n.º 26
0
        public async Task OnExecute(CommandContext command)
        {
            if (!ConfigParser.IsCommandChannel(command.Channel.Id))
            {
                return;
            }
            if (!ConfigParser.ValidatePermission(command))
            {
                return;
            }

            Interface.MessageWrapper message = new Interface.MessageWrapper
            {
                ListCommand = new Interface.ListCommand
                {
                    ChannelID = command.Channel.Id
                }
            };
            NetworkSystem.SendMessage(message);
            Logger.Debug("Sending '" + command.Message.Content + "' to plugin from " + command.Member.Username + "#" + command.Member.Discriminator, LogID.Discord);
        }
Exemplo n.º 27
0
        /// <summary>
        /// 加载插件设置
        /// </summary>
        public static void Load()
        {
            filePath = Directory.GetCurrentDirectory() + @"\Plugins\KanColleCacher.ini";

            if (!File.Exists(filePath))
            {
                var path = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                    "grabacr.net",
                    "KanColleViewer",
                    "KanColleCacher.ini"
                    );
                if (File.Exists(path))
                {
                    filePath = path;
                }
            }

            if (File.Exists(filePath))
            {
                var _Parser = ConfigParser.ReadIniFile(filePath);
                Current = _Parser.DeserializeObject <Settings>("Settings");

                try
                {
                    Directory.CreateDirectory(Current.CacheFolder);
                }
                catch (Exception ex)
                {
                    Current.CacheFolder = Directory.GetCurrentDirectory() + @"\MyCache";
                    Log.Exception(ex.InnerException, ex, "设置文件中CacheFolder不存在,试图创建时发生异常");
                }
            }
            else
            {
                //设置文件丢失
            }

            Current = Current ?? new Settings();
        }
Exemplo n.º 28
0
        /// <summary>
        /// Loads the config file data from a stream.
        /// </summary>
        /// <param name="stream">The stream to read.</param>
        /// <inheritdoc />
        public override void Load(Stream stream)
        {
            var data = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            using (var reader = new StreamReader(stream))
            {
                var configFileContent = reader.ReadToEnd();
                var configParser      = new ConfigParser(configFileContent);
                foreach (var section in configParser.Sections)
                {
                    var sectionPrefix = $"{section.SectionName}{ConfigurationPath.KeyDelimiter}";
                    foreach (var key in section.Keys)
                    {
                        var keyName = $"{sectionPrefix}{key.Name}";
                        var value   = section[key.Name];
                        data.Add(keyName, value);
                    }
                }
            }

            Data = data;
        }
Exemplo n.º 29
0
        public void Excute(string scriptContent, string includeDir = null)
        {
            var parser = new ConfigParser(CommandManage.Commands.Select(c => c.Key).ToList(), includeDir);
            var root   = parser.Parse(scriptContent);

            ErrorNode = null;
            try
            {
                var br     = false;
                var result = Excute(root, ref br);
                if (!result.Success)
                {
                    Log($"错误:{result.PipelineOutput.ToString()}");
                    Log($"Command:{ErrorNode.Name}, 行{ErrorNode.Line}");
                }
            }
            catch (ConfigParseException ex)
            {
                Log(ex.ToString());
                return;
            }
        }
Exemplo n.º 30
0
        public bool Load(TextReader reader, IErrorReporter reporter, ICodeGeneratorEnv environment)
        {
            var wrapper = new ReporterWrapper(reporter);

            _loadStart       = null;
            _parseDone       = null;
            _calculationDone = null;
            _writeStart      = null;
            _writeDone       = null;

            _loadStart = DateTime.Now;

            var parser = new ConfigParser(wrapper);
            var config = parser.Parse(new ConfigScanner(reader.ReadToEnd()));

            _parseDone = DateTime.Now;

            if (wrapper.HasError)
            {
                return(false);
            }

            config.TableResourceNameFormat = environment.GetResourceName(".{0}.table");

            SyntaxTreeDecorator.Decorate(config, wrapper);

            _calculationDone = DateTime.Now;

            if (wrapper.HasError)
            {
                _config = null;
                return(false);
            }
            else
            {
                _config = config;
                return(true);
            }
        }
Exemplo n.º 31
0
 public static void Reset()
 {
     gameplaySettings = new ConfigParser<GameplaySettingsStore>(new GameplaySettingsStore(), Path.Combine(Server.configDirectory, "GameplaySettings.txt"));
 }
Exemplo n.º 32
0
		static void ProcessSettingFile(string filepath, out string cachefolder)
		{
			var doc = XDocument.Load(filepath);
			var parser = new ConfigParser();
			var section = parser["Settings"] = new Section();
			parser.SerializeObject<Settings>(new Settings(), "Settings");

			foreach (var elm in doc.Root.Elements())
			{
				var name = elm.Name.ToString();
				var val = elm.Value;

				if (!String.IsNullOrEmpty(val))
				{
					section[name] = val;
				}
			}

			section["SaveApiStart2"] = section["PrintGraphList"];
			section["PrintGraphList"] = null;

			parser.SaveIniFile(filepath.Substring(0, filepath.Length - 3) + "ini");
			cachefolder = section["CacheFolder"];
		}
Exemplo n.º 33
0
 /// <summary>
 /// Initializes a new instance of <see cref="BifrostConfigHandler"/>
 /// </summary>
 /// <param name="parser"><see cref="ConfigParser"/> to use for parsing</param>
 public BifrostConfigHandler(ConfigParser parser)
 {
     _parser = parser;
 }
Exemplo n.º 34
0
 public static void Reset()
 {
     serverSettings = new ConfigParser<SettingsStore>(new SettingsStore(), Path.Combine(Server.configDirectory, "Settings.txt"));
 }