public async Task LoadAndGenerateAlarms(RunMode mode)
        {
            if (_hasRun)
            {
                // there is loads of state etc. and you get duplicate alarms
                // shouldn't happen in real life but I discovered it in tests
                throw new InvalidOperationException($"{nameof(LoadAndGenerateAlarms)} can only be called once");
            }

            try
            {
                _hasRun = true;
                _logger.Info($"Starting {mode}");

                var config = _configLoader.LoadConfig();
                ConfigValidator.Validate(config);

                if (mode == RunMode.GenerateAlarms || mode == RunMode.DryRun)
                {
                    await GenerateAlarms(config, mode);
                }

                if (mode == RunMode.GenerateAlarms)
                {
                    await LogOrphanedAlarms();
                }

                _logger.Detail("Done");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Error in run");
                throw;
            }
        }
Exemple #2
0
        public void ShowSummaryWindow(IReadOnlyList <WurmClientIssue> issues)
        {
            if (issues == null || !issues.Any())
            {
                issues = new WurmClientIssue[] { new WurmClientIssue("No issues") }
            }
            ;

            var view = new ValidationResultForm(this);

            view.SetText(String.Join(Environment.NewLine, issues));
            view.Show();
        }

        IEnumerable <WurmClientIssue> AppendAutoruns()
        {
            wurmApi.Autoruns.MergeCommandToAllAutoruns("say /uptime");
            wurmApi.Autoruns.MergeCommandToAllAutoruns("say /time");
            return(new WurmClientIssue[0]);
        }

        IEnumerable <WurmClientIssue> CheckAllConfigs()
        {
            var issues  = new List <WurmClientIssue>();
            var configs = wurmApi.Configs.All;

            foreach (var wurmConfig in configs)
            {
                var validator = new ConfigValidator(wurmConfig);
                validator.Validate();
                issues.AddRange(validator.GetIssues());
            }
            return(issues);
        }
Exemple #3
0
    /// <summary>
    /// Configure App
    /// </summary>
    /// <param name="ctx">HostBuilderContext</param>
    /// <param name="config">IConfigurationBuilder</param>
    public virtual void ConfigureApp(HostBuilderContext ctx, IConfigurationBuilder config)
    {
        // Shortcut for environment
        var env = ctx.HostingEnvironment;

        // Validate main configuration file
        var path = $"{env.ContentRootPath}/jeebsconfig.json";

        if (File.Exists(path))
        {
            _ = ConfigValidator.Validate(path);
        }

        // Add Jeebs config - keeps Jeebs config away from app settings
        _ = config
            .AddJsonFile($"{env.ContentRootPath}/jeebsconfig.json", optional: true)
            .AddJsonFile($"{env.ContentRootPath}/jeebsconfig-secrets.json", optional: true);

        // Add environment-specific Jeebs config
        _ = config
            .AddJsonFile($"{env.ContentRootPath}/jeebsconfig.{env.EnvironmentName}.json", optional: true)
            .AddJsonFile($"{env.ContentRootPath}/jeebsconfig-secrets.{env.EnvironmentName}.json", optional: true);

        // Add config from Azure Key Vault
        var vault = config.Build().GetSection <KeyVaultConfig>(KeyVaultConfig.Key, false);

        if (vault.IsValid)
        {
            _ = config.AddAzureKeyVault(vault.GetUri(), vault.GetCredential());
        }
    }
        public async Task <IList <ProvisioningReport> > GetReports()
        {
            try
            {
                Console.WriteLine("Starting");

                var config = _configLoader.LoadConfig();
                ConfigValidator.Validate(config);
                foreach (var alertingGroup in config.AlertingGroups)
                {
                    await _tableNamePopulator.PopulateDynamoTableNames(alertingGroup);
                }

                var groupsRequiringReports = config.AlertingGroups
                                             .Where(x => x.ReportTargets.Any());

                var provisioningReports = new List <ProvisioningReport>();
                foreach (var alertingGroup in groupsRequiringReports)
                {
                    var report = await GenerateAlertingGroupReport(alertingGroup);

                    provisioningReports.Add(report);
                }

                Console.WriteLine("Finished Reading Reports");

                return(provisioningReports);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.ToString());
                throw;
            }
        }
Exemple #5
0
        protected void Application_Start()
        {
            LogService.Debug("Application starting...");
            LogService.Debug("Machine: {0}", Environment.MachineName);

            LogService.Debug("Validating configuration...");
            ConfigValidator.Validate();

            LogService.Debug("Registering areas...");
            AreaRegistration.RegisterAllAreas();

            LogService.Debug("Registering global filters...");
            RegisterGlobalFilters(GlobalFilters.Filters);

            LogService.Debug("Registering routes...");
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            LogService.Debug("Bootstrap setup...");
            new WebBootstrap().Setup();

            LogService.Debug("Loading achievements provider assembly...");
            var dummy = typeof(AchievementProviderBase);

            LogService.Debug("{0} assembly loaded.", dummy.Assembly.GetName().Name);

            LogService.Debug("Registering FluentUI...");
            FluentUIConfig.Register();

            LogService.Debug("Application started.");
        }
Exemple #6
0
        /// <summary>
        /// Click event handler for saving the new config file. Validates prior to saving.  Displays the error/save message box.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveFile_Click(object sender, EventArgs e)
        {
            try
            {
                var formProcessor = new FormProcessor(ContentFlow);

                var cv = new ConfigValidator(ConfigPath, SchemaPath);
                if (cv.Validate(true) != 0)
                {
                    throw new InvalidDataException("XSD-based Validation Failed.  Check for errors.");
                }

                var cf = new ConfigWriter(ConfigPath);
                cf.Write();
                Saved.Text      = "Saved newrelic.config successfully";
                Saved.BackColor = Color.FromArgb(244, 144, 0);
                Saved.Visible   = true;
                _savedTimer.Start();
            }
            catch (Exception ex)
            {
                log.Error("01 - " + ex.Message);
                Saved.Text      = ex.Message;
                Saved.BackColor = Color.DarkRed;
                Saved.Visible   = true;
                _savedTimer.Start();
            }
        }
Exemple #7
0
 /// <summary>
 /// Applications the start.
 /// </summary>
 protected void Application_Start()
 {
     ConfigValidator.Validate();
     AreaRegistration.RegisterAllAreas();
     GlobalConfiguration.Configure(WebApiConfig.Register);
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
 }
Exemple #8
0
        public void TestInvalidFormat()
        {
            var config = CreateConfig();

            config.Format.Returns("invalid");
            var exception = Assert.Throws <InvalidConfigException>(() => ConfigValidator.Validate(config));

            Assert.Equal("http-stream is the only supported format", exception.Message);
        }
Exemple #9
0
        public void TestUnknownSocketType()
        {
            var config = CreateConfig();

            config.ListenerSocketType.Returns(SocketType.Unknown);
            config.Listener.Returns("foobar");
            var exception = Assert.Throws <InvalidConfigException>(() => ConfigValidator.Validate(config));

            Assert.Equal("Invalid listener: foobar", exception.Message);
        }
Exemple #10
0
        /// <summary>
        /// The Create instance.
        /// </summary>
        /// <param name="server">the server name.</param>
        /// <returns>The config.</returns>
        public static IMono <Config> Create(string server)
        {
            var validator  = new ConfigValidator();
            var config     = new Config(server);
            var validation = validator.Validate(config);

            return(validation.IsValid
                       ? Mono.Just(config)
                       : Mono.Error <Config>(new ArgumentException(string.Join(", ", validation.Errors))));
        }
Exemple #11
0
        public void TestDoesNotAllowUnixSocketOnWindows()
        {
            Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows));

            var config = CreateConfig();

            config.ListenerSocketType.Returns(SocketType.Unix);
            var exception = Assert.Throws <InvalidConfigException>(() => ConfigValidator.Validate(config));

            Assert.Equal("UNIX sockets are not supported on Windows", exception.Message);
        }
        public void LoadConfig_DuplicateGroupNames_Throws()
        {
            var loader = GetLoader($"data\\duplicates\\duplicateGroups".ToCrossPlatformPath());

            var config = loader();

            var caught = Assert.Throws <ConfigException>(() => ConfigValidator.Validate(config));

            Assert.That(caught, Is.Not.Null);
            Assert.That(caught.Message, Contains.Substring("The following alerting group names exist in multiple config files"));
            Assert.That(caught.Message, Contains.Substring("TestGroupName"));
        }
        private bool ValidateConfiguration()
        {
            _configValidator = new ConfigValidator(GlobalConfig);
            var messages = _configValidator.Validate();

            if (messages == string.Empty)
            {
                return(true);
            }

            MessageBox.Show("Errores de configuración", "Error config", MessageBoxButton.OK, MessageBoxImage.Error);
            return(false);
        }
Exemple #14
0
        public void TestConfigurationIsValid()
        {
            XmlDocument textDoc = new XmlDocument();

            textDoc.Load(File.OpenRead(@"Resources\\empty_main.xml"));
            ConfigParser configParser = new ConfigParser(textDoc);

            ConfigValidator configValidator = new ConfigValidator();

            Assert.AreNotEqual(configValidator.Validate(), "", "Config should not be valid");

            foreach (string mandatoryConst in ConfigConsts.ReportMandatory)
            {
                configParser.SetStringValue("//Config/" + mandatoryConst, "StringValue");
            }

            Assert.AreEqual(configValidator.Validate(), "", "Config should be valid");

            CheckSetConfig(configParser, "abc", "123");
            CheckSetConfig(configParser, "Url", @"https://uri.com.br/api/v1/installer?userId=0&programId=49730&status=init");

            configParser.SetStringValue("//Config/" + ConfigConsts.URL_ANALYTICS, "");
            Assert.AreNotEqual(configValidator.Validate(), "", "Config should not be valid");
        }
Exemple #15
0
        public bool TryLoadAndValidateConfig(out Config?config)
        {
            config = null;

            if (!_configfile.IsExisting)
            {
                _log.Info("No bookgen.json config found.");
                return(false);
            }

            config = _configfile.DeserializeJson <Config>(_log);

            if (config == null)
            {
                _log.Critical("bookgen.json deserialize error. Invalid config file");
                return(false);
            }

            if (config.Version < Program.CurrentState.ConfigVersion)
            {
                _configfile.CreateBackup(_log);
                config.UpgradeTo(Program.CurrentState.ConfigVersion);
                _configfile.SerializeJson(config, _log, true);
                _log.Info("Configuration file migrated to new version.");
                _log.Info("Review configuration then run program again");
                return(false);
            }

            ConfigValidator validator = new ConfigValidator(config, _workdir);

            validator.Validate();

            if (!validator.IsValid)
            {
                _log.Warning("Errors found in configuration: ");
                foreach (var error in validator.Errors)
                {
                    _log.Warning(error);
                }
                return(false);
            }

            return(true);
        }
Exemple #16
0
        /// <summary>
        /// Click event handler for saving the new config file to a new location. Validates prior to saving.  Displays the error/save message box.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveFileAs_Click(object sender, EventArgs e)
        {
            try
            {
                var formProcessor = new FormProcessor(ContentFlow);

                var cv = new ConfigValidator(ConfigPath, SchemaPath);
                if (cv.Validate(true) != 0)
                {
                    throw new InvalidDataException("XSD-based Validation Failed.  Check for errors.");
                }

                var cf = new ConfigWriter();

                var safeFile = new SaveFileDialog();
                safeFile.Title            = "Select the new location for the newrelic.config file";
                safeFile.FileName         = "newrelic.config";
                safeFile.Filter           = "config files (*.config)|*.config|All files (*.*)|*.*";
                safeFile.FilterIndex      = 0;
                safeFile.RestoreDirectory = true;

                if (safeFile.ShowDialog() == DialogResult.OK)
                {
                    cf.Write(safeFile.FileName);
                }

                Saved.Text      = "Saved newrelic.config successfully";
                Saved.BackColor = Color.FromArgb(244, 144, 0);
                Saved.Visible   = true;
                _savedTimer.Start();
            }
            catch (Exception ex)
            {
                log.Error(ex);
                Saved.Text      = ex.Message;
                Saved.BackColor = Color.DarkRed;
                Saved.Visible   = true;
                _savedTimer.Start();
            }
        }
Exemple #17
0
        public async Task LoadAndGenerateAlarms(RunMode mode)
        {
            try
            {
                _logger.Info($"Starting {mode}");

                var config = _configLoader.LoadConfig();
                ConfigValidator.Validate(config);

                if (mode == RunMode.GenerateAlarms || mode == RunMode.DryRun)
                {
                    await GenerateAlarms(config, mode);
                }

                _logger.Detail("Done");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Error in run");
                throw;
            }
        }
        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(TbDataBase.Text.Trim()) || string.IsNullOrEmpty(TbPathPendingBills.Text.Trim()) ||
                string.IsNullOrEmpty(TbEmail.Text.Trim()) || string.IsNullOrEmpty(TbPassWord.Password.Trim()) ||
                string.IsNullOrEmpty(TbPathSentBills.Text.Trim()) || string.IsNullOrEmpty(TbShippingTime.Text.Trim()) ||
                string.IsNullOrEmpty(TbIntervalos.Text.Trim()) || string.IsNullOrEmpty(TbEmailServer.Text.Trim()) ||
                string.IsNullOrEmpty(TbEmailServerPort.Text.Trim()))
            {
                MessageBox.Show(Properties.Resources.MUST_WRITE_ANY_CONFIG, Properties.Resources.INCOMPLETE_CONFIG, MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            var config = new Global
            {
                DataBasePath           = TbDataBase.Text,
                PendingBillPath        = TbPathPendingBills.Text,
                SentBillPath           = TbPathSentBills.Text,
                Email                  = TbEmail.Text,
                EmailPassWord          = TbPassWord.Password,
                EmailSever             = TbEmailServer.Text,
                EmailSeverPort         = int.Parse(TbEmailServerPort.Text),
                ShippingTime           = TbShippingTime.Text,
                ShippingInterval       = TbIntervalos.Text,
                LastShipmentWithErrors = _config.LastShipmentWithErrors
            };

            var configValidate = new ConfigValidator(config);

            var messages = configValidate.Validate();

            if (messages != string.Empty)
            {
                MessageBox.Show(messages, Properties.Resources.CONFIG_ERRORS, MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            Repositorio.Save(config);
            MessageBox.Show(Properties.Resources.CORRECT_SAVE, Properties.Resources.SAVE_CONFIG, MessageBoxButton.OK, MessageBoxImage.Asterisk);
        }
Exemple #19
0
        /// <summary>
        /// Click event handler for the Validate button on the main form. Uses the error/save dialog.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValidateXml_Click(object sender, EventArgs e)
        {
            var cv         = new ConfigValidator(ConfigPath, SchemaPath);
            int errorCount = cv.Validate();

            if (errorCount > 0)
            {
                Saved.Text      = errorCount + " errors found, see validation.txt";
                Saved.BackColor = Color.DarkRed;
            }
            else if (errorCount == 0)
            {
                Saved.Text      = "Valid";
                Saved.BackColor = Color.FromArgb(244, 144, 0);
            }
            else if (errorCount == -1)
            {
                Saved.Text      = "Trouble reading the config or xsd files.";
                Saved.BackColor = Color.DarkRed;
            }

            Saved.Visible = true;
            _savedTimer.Start();
        }
        public static void NotValid(WatchmanConfiguration config, string expectedMessage)
        {
            var ex = Assert.Throws <ConfigException>(() => ConfigValidator.Validate(config));

            Assert.That(ex.Message, Is.EqualTo(expectedMessage));
        }
Exemple #21
0
        public void TestValidConfig()
        {
            var config = CreateConfig();

            ConfigValidator.Validate(config);
        }
        /// <summary>
        /// Click event handler for the Validate button on the main form. Uses the error/save dialog.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ValidateXml_Click(object sender, EventArgs e)
        {
            var cv = new ConfigValidator();
            int errorCount = cv.Validate();
            if (errorCount > 0)
            {
                Saved.Text = errorCount + " errors found, see validation.txt";
                Saved.BackColor = Color.DarkRed;
            }
            else if (errorCount == 0)
            {
                Saved.Text = "Valid";
                Saved.BackColor = Color.FromArgb(244, 144, 0);
            }
            else if (errorCount == -1)
            {
                Saved.Text = "Trouble reading the config or xsd files.";
                Saved.BackColor = Color.DarkRed;
            }

            Saved.Visible = true;
            _savedTimer.Start();
        }
        /// <summary>
        /// Click event handler for saving the new config file. Validates prior to saving.  Displays the error/save message box.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveFile_Click(object sender, EventArgs e)
        {
            try
            {
                var reader = new FormReader(ContentFlow);

                var cv = new ConfigValidator();
                if (cv.Validate(true) != 0)
                {
                    throw new InvalidDataException("XSD-based Validation Failed.  Check for errors.");
                }

                var cf = new ConfigWriter();
                cf.Write();
                Saved.Text = "Saved newrelic.config successfully";
                Saved.BackColor = Color.FromArgb(244, 144, 0);
                Saved.Visible = true;
                _savedTimer.Start();
            }
            catch (Exception ex)
            {
                log.Error("01 - " + ex.Message);
                Saved.Text = ex.Message;
                Saved.BackColor = Color.DarkRed;
                Saved.Visible = true;
                _savedTimer.Start();
            }
        }
Exemple #24
0
        static void InitializeSettings()
        {
            var cm = new ConfigManager();

            if (cm.FileExists())
            {
                _config = cm.Read();

                if (_config.Version != App.SettingsVersion)
                {
                    Console.WriteLine("Your settings file is outdated, press [Enter] to back up the old version so you may fill out the new one.");
                    Console.ReadLine();
                    cm.Save(_config, "Config_OLD");
                    cm.Save(new Config {
                        Version = App.SettingsVersion
                    });
                    if (!Platform.IsUnix)
                    {
                        SelectFile(Files.ConfigFile);
                    }
                    Console.WriteLine("Press [Enter] to continue.");
                    Console.ReadLine();
                    Console.WriteLine();

                    _config = cm.Read();
                }

                var validator = new ConfigValidator();
                var results   = validator.Validate(_config);
                if (!results.IsValid)
                {
                    Console.WriteLine("Your config file is not valid:");
                    foreach (var error in results.Errors)
                    {
                        string message = error.ErrorMessage;
                        Console.BackgroundColor = ConsoleColor.Red;
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.WriteLine(" - {0}", message);
                        Console.ResetColor();
                    }
                    Console.WriteLine("Please fix the above errors.");
                    Console.WriteLine("Press [Enter] to exit.");
                    Console.ReadLine();
                    Environment.Exit(0);
                }
            }
            else
            {
                cm.Save(new Config {
                    Version = App.SettingsVersion
                });

                Console.WriteLine("A default config file has been created at {0}", Files.ConfigFile);
                Console.WriteLine("Documentation for the settings file can be found at {0}", "https://github.com/depthbomb/Scraps/blob/master/SETTINGS.md");
                Console.WriteLine("Please fill it out and press [Enter] to continue.");
                Console.ReadLine();
                Console.WriteLine();

                _config = cm.Read();
            }
        }
        /// <summary>
        /// Click event handler for saving the new config file to a new location. Validates prior to saving.  Displays the error/save message box.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SaveFileAs_Click(object sender, EventArgs e)
        {
            try
            {
                var reader = new FormReader(ContentFlow);

                var cv = new ConfigValidator();
                if (cv.Validate(true) != 0)
                {
                    throw new InvalidDataException("XSD-based Validation Failed.  Check for errors.");
                }

                var cf = new ConfigWriter();

                var safeFile = new SaveFileDialog();
                safeFile.Title = "Select the new location for the newrelic.config file";
                safeFile.FileName = "newrelic.config";
                safeFile.Filter = "config files (*.config)|*.config|All files (*.*)|*.*";
                safeFile.FilterIndex = 0;
                safeFile.RestoreDirectory = true;

                if (safeFile.ShowDialog() == DialogResult.OK)
                {
                    cf.Write(safeFile.FileName);
                }

                Saved.Text = "Saved newrelic.config successfully";
                Saved.BackColor = Color.FromArgb(244, 144, 0);
                Saved.Visible = true;
                _savedTimer.Start();
            }
            catch (Exception ex)
            {
                log.Error(ex);
                Saved.Text = ex.Message;
                Saved.BackColor = Color.DarkRed;
                Saved.Visible = true;
                _savedTimer.Start();
            }
        }
 public static void IsValid(WatchmanConfiguration config)
 {
     ConfigValidator.Validate(config);
     Assert.That(config, Is.Not.Null);
 }