public async Task UpdateAppSetting(AppSettingsKey key, string value) { var message = SettingsValidator.Validate(key, value); if (message != "") { throw new ArgumentException(message); } var keyStr = key.ToString(); var appSetting = await _context.AppSettings.FirstOrDefaultAsync(s => s.Key == keyStr).ConfigureAwait(false); if (appSetting == null) { await _context.AppSettings.AddAsync(new AppSetting { Key = keyStr, Value = value, ModifiedDate = DateTime.UtcNow }); await _context.SaveChangesAsync().ConfigureAwait(false); } else { if (appSetting.Value != value) { appSetting.Value = value; appSetting.ModifiedDate = DateTime.UtcNow; await _context.SaveChangesAsync().ConfigureAwait(false); } } }
public void ValidateSettings_should_not_allow_null_RollingStrategy() { new Action(() => SettingsValidator.ValidateSettings(new FileLogSettings { RollingStrategy = null })) .Should().Throw <ArgumentNullException>(); }
public static IUnleashServiceCollection WithMemoryToggleCollectionCache(this IUnleashServiceCollection serviceCollection, Action <MemoryToggleCollectionCacheSettings> settingsConfigurator = null) { if (serviceCollection == null) { throw new ArgumentNullException(nameof(serviceCollection)); } var settings = new MemoryToggleCollectionCacheSettings(); if (serviceCollection.UnleashConfiguration != null) { var section = serviceCollection.UnleashConfiguration.GetSection("Caching:Memory"); section.Bind(settings); } settingsConfigurator?.Invoke(settings); SettingsValidator.Validate(settings); serviceCollection.AddSingleton(settings); serviceCollection.AddMemoryCache(); serviceCollection.WithToggleCollectionCache <MemoryToggleCollectionCache>(); return(serviceCollection); }
public static IUnleashServiceCollection WithNewtonsoftJsonSerializer(this IUnleashServiceCollection serviceCollection, Action <NewtonsoftJsonSerializerSettings> settingsConfigurator = null) { if (serviceCollection == null) { throw new ArgumentNullException(nameof(serviceCollection)); } var settings = new NewtonsoftJsonSerializerSettings(); if (serviceCollection.UnleashConfiguration != null) { var section = serviceCollection.UnleashConfiguration.GetSection("Serialization:NewtonsoftJson"); section.Bind(settings); } settingsConfigurator?.Invoke(settings); SettingsValidator.Validate(settings); serviceCollection.AddSingleton(settings); serviceCollection.WithJsonSerializer <NewtonsoftJsonSerializer>(); return(serviceCollection); }
private void Validate() { if (!HasValue()) { return; } if (!SettingsValidator.BugzillaVersionIsSupported(_bugzillaVersion)) { throw new ApplicationException(string.Format(SettingsValidator.BUGZILLA_VERSION_IS_NOT_SUPPORTED_BY_PLUGIN, _bugzillaVersion)); } if (!SettingsValidator.ScriptSupportsProvidedBugzillaVersion(_bugzillaVersion, _supportedBugzillaVersion)) { throw new ApplicationException(string.Format(SettingsValidator.BUGZILLA_VERSION_IS_NOT_SUPPORTED_BY_TP2_CGI, _bugzillaVersion)); } if (!SettingsValidator.ScriptVersionIsValid(_scriptVersion)) { throw new ApplicationException(string.Format(SettingsValidator.TP2_CGI_IS_NOT_SUPPORTED_BY_THIS_PLUGIN, _scriptVersion)); } }
public void ValidateSettings_should_not_allow_null_EnabledLogLevels() { new Action(() => SettingsValidator.ValidateSettings(new FileLogSettings { EnabledLogLevels = null })) .Should().Throw <ArgumentNullException>(); }
public void ValidateSettings_should_not_allow_null_OutputTemplate() { new Action(() => SettingsValidator.ValidateSettings(new FileLogSettings { OutputTemplate = null })) .Should().Throw <ArgumentNullException>(); }
public void ValidateSettings_should_not_allow_FilePath_pointing_to_a_directory() { new Action(() => SettingsValidator.ValidateSettings(new FileLogSettings { FilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs" + Path.DirectorySeparatorChar) })) .Should().Throw <ArgumentException>(); }
public void ValidateSettings_should_not_allow_invalid_FileOpenMode() { new Action(() => SettingsValidator.ValidateSettings(new FileLogSettings { FileOpenMode = (FileOpenMode)(-1) })) .Should().Throw <ArgumentOutOfRangeException>(); }
public void AreValidIssuerThumbprintsTest() { Assert.IsTrue(SettingsValidator.AreValidIssuerThumbprints("59EC792004C56225DD6691132C713194D28098F1")); Assert.IsTrue(SettingsValidator.AreValidIssuerThumbprints("59EC792004C56225DD6691132C713194D28098F1,59EC792004C56225DD6691132C713194D28098F2")); Assert.IsFalse(SettingsValidator.AreValidIssuerThumbprints("59EC792004C56225DD6691132C713194D28098F1;59EC792004C56225DD6691132C713194D28098F2")); }
private ValidationResult DeserializeAndValidate(string json) { Settings settings = JsonConvert.DeserializeObject <Settings>(json); var settingsValidator = new SettingsValidator(); return(settingsValidator.Validate(settings)); }
public void ValidateSettings_should_not_allow_invalid_RollingStrategy_Period(RollingStrategyType type) { new Action(() => SettingsValidator.ValidateSettings(new FileLogSettings { RollingStrategy = new RollingStrategyOptions { Period = (RollingPeriod)(-1), Type = type } })) .Should().Throw <ArgumentOutOfRangeException>(); }
public void ValidateSettings_should_allow_zero_RollingStrategy_MaxFiles([Values] RollingStrategyType type) { new Action(() => SettingsValidator.ValidateSettings(new FileLogSettings { RollingStrategy = new RollingStrategyOptions { MaxFiles = 0 } })) .Should().NotThrow(); }
public void ValidateSettings_should_not_allow_non_positive_RollingStrategy_MaxSize_for_BySize_and_Hybrid_strategies(int maxSize, RollingStrategyType type) { new Action(() => SettingsValidator.ValidateSettings(new FileLogSettings { RollingStrategy = new RollingStrategyOptions { MaxSize = maxSize, Type = type } })) .Should().Throw <ArgumentOutOfRangeException>(); }
public void ValidateSettings_should_allow_zero_RollingStrategy_MaxSize_for_None_and_ByTime_strategies(RollingStrategyType type) { new Action(() => SettingsValidator.ValidateSettings(new FileLogSettings { RollingStrategy = new RollingStrategyOptions { MaxSize = 0, Type = type } })) .Should().NotThrow(); }
public void ValidateInstanceSettings_should_throw_exception_if_ColorMapping_is_null() { var settings = new ConsoleLogSettings { ColorMapping = null }; new Action(() => SettingsValidator.ValidateInstanceSettings(settings)) .Should().Throw <ArgumentNullException>(); }
public Runner(SettingsValidator validator, BittrexDataProvider dataProvider, AltCoinFinder altCoinFinder) { _validator = validator; _dataProvider = dataProvider; _altCoinFinder = altCoinFinder; _twitterListener.Elapsed += OnTwitterListenerElapsed; }
public void IsValidThumbprintTest() { // copied from powershell Assert.IsTrue(SettingsValidator.IsValidThumbprint("59EC792004C56225DD6691132C713194D28098F1")); // copied from mmc Assert.IsTrue(SettingsValidator.IsValidThumbprint("e9 70 f6 20 4a 54 27 a7 96 1d e1 1d 5a c2 14 f5 bb 18 6b d0")); Assert.IsFalse(SettingsValidator.IsValidThumbprint("59EC792004C56225DD6691132C713194D28098F1;")); }
public void ValidateSettings_should_not_allow_non_positive_OutputBufferSize() { new Action(() => SettingsValidator.ValidateSettings(new FileLogSettings { OutputBufferSize = -1 })) .Should().Throw <ArgumentOutOfRangeException>(); new Action(() => SettingsValidator.ValidateSettings(new FileLogSettings { OutputBufferSize = 0 })) .Should().Throw <ArgumentOutOfRangeException>(); }
public bugzilla_properties CheckConnection(BugzillaProfile profile) { var errors = new PluginProfileErrorCollection(); try { var validators = new Queue <Validator>(); var connectionValidator = new ConnectionValidator(profile); validators.Enqueue(connectionValidator); var scriptValidator = new ScriptValidator(profile); validators.Enqueue(scriptValidator); var responseValidator = new ResponseValidator(profile, scriptValidator); validators.Enqueue(responseValidator); var deserializeValidator = new DeserializeValidator(profile, responseValidator); validators.Enqueue(deserializeValidator); var settingsValidator = new SettingsValidator(profile, deserializeValidator); validators.Enqueue(settingsValidator); var savedQueryValidator = new SavedQueryValidator(profile); validators.Enqueue(savedQueryValidator); while (validators.Count > 0) { var validator = validators.Dequeue(); validator.Execute(errors); } if (errors.Any()) { throw new BugzillaPluginProfileException(profile, errors); } return(deserializeValidator.Data); } catch (BugzillaPluginProfileException) { throw; } catch (Exception ex) { errors.Add(new PluginProfileError { FieldName = BugzillaProfile.ProfileField, Message = string.Format("The connection with {0} is failed. {1}", profile, ex.Message) }); throw new BugzillaPluginProfileException(profile, errors); } }
public void ValidateSettings_should_not_allow_null_or_empty_FilePath() { new Action(() => SettingsValidator.ValidateSettings(new FileLogSettings { FilePath = @"" })) .Should().Throw <ArgumentNullException>(); new Action(() => SettingsValidator.ValidateSettings(new FileLogSettings { FilePath = null })) .Should().Throw <ArgumentNullException>(); }
public void ValidateSettings_should_not_allow_non_positive_EventsBufferCapacity() { new Action(() => SettingsValidator.ValidateSettings(new FileLogSettings { EventsBufferCapacity = -1 })) .Should().Throw <ArgumentOutOfRangeException>(); new Action(() => SettingsValidator.ValidateSettings(new FileLogSettings { EventsBufferCapacity = 0 })) .Should().Throw <ArgumentOutOfRangeException>(); }
public void ValidateSettings_should_not_allow_non_positive_TargetFileUpdateCooldown() { new Action(() => SettingsValidator.ValidateSettings(new FileLogSettings { FileSettingsUpdateCooldown = TimeSpan.FromSeconds(-1) })) .Should().Throw <ArgumentOutOfRangeException>(); new Action(() => SettingsValidator.ValidateSettings(new FileLogSettings { FileSettingsUpdateCooldown = TimeSpan.Zero })) .Should().Throw <ArgumentOutOfRangeException>(); }
public void ValidateGlobalSettings_should_throw_exception_if_EventsTemporaryBufferCapacityy_is_not_positive() { var settings = new ConsoleLogGlobalSettings { EventsTemporaryBufferCapacity = 0 }; new Action(() => SettingsValidator.ValidateGlobalSettings(settings)) .Should().Throw <ArgumentOutOfRangeException>(); settings.EventsTemporaryBufferCapacity = -1; new Action(() => SettingsValidator.ValidateGlobalSettings(settings)) .Should().Throw <ArgumentOutOfRangeException>(); }
public void validation_should_fail_for_no_options() { // Arrange var settings = new Settings(); var target = new SettingsValidator(settings); // Act var result = target.Validate(); // Assert Assert.NotNull(result.ErrorMessages); Assert.Equal(3, result.ErrorMessages.Count); }
internal static IUnleashServiceCollection AddUnleash(this IServiceCollection serviceCollection, Action <UnleashSettings> settingsInitializer, IConfiguration configuration, Action <UnleashSettings> settingsOverrider) { if (serviceCollection == null) { throw new ArgumentNullException(nameof(serviceCollection)); } var result = new UnleashServiceCollection(serviceCollection, configuration); var settings = new UnleashSettings(); settingsInitializer?.Invoke(settings); configuration?.Bind(settings); settingsOverrider?.Invoke(settings); SettingsValidator.Validate(settings); var unleashApiClientRequestHeaders = new UnleashApiClientRequestHeaders { AppName = settings.AppName, CustomHttpHeaders = settings.CustomHttpHeaders, InstanceTag = settings.InstanceTag }; serviceCollection.AddSingleton(settings); serviceCollection.AddSingleton <IRandom>(new UnleashRandom()); serviceCollection.AddSingleton(serviceProvider => serviceProvider.GetService <IEnumerable <IStrategy> >()?.ToArray() ?? Array.Empty <IStrategy>()); // Internal services serviceCollection.AddSingleton <NewtonsoftJsonSerializerSettings>(); serviceCollection.AddSingleton <IJsonSerializer, NewtonsoftJsonSerializer>(); serviceCollection.AddSingleton(unleashApiClientRequestHeaders); serviceCollection.AddSingleton <IHttpClientFactory, DefaultHttpClientFactory>(); serviceCollection.AddSingleton <IUnleashApiClientFactory, DefaultUnleashApiClientFactory>(); serviceCollection.AddSingleton <IUnleashApiClient, UnleashApiClient>(); serviceCollection.AddSingleton <IUnleashServices, UnleashServices>(); // Default: SystemTimer scheduled task manager serviceCollection.AddSingleton <IUnleashScheduledTaskManager, SystemTimerScheduledTaskManager>(); // Default: Disk-based JSON toggle collection cache serviceCollection.AddSingleton <IFileSystem, FileSystem>(); serviceCollection.AddSingleton <IToggleCollectionCache, FileSystemToggleCollectionCache>(); serviceCollection.AddScoped <IUnleashContextProvider, DefaultUnleashContextProvider>(); serviceCollection.AddScoped <IUnleash, Unleash>(); return(result); }
private void OnExecute() { if (!File.Exists(SettingsFile)) { Console.WriteLine($"Can't find file {SettingsFile}"); return; } if (!File.Exists(MovesFile)) { Console.WriteLine($"Can't find file {MovesFile}"); return; } var settingsText = File.ReadAllText(SettingsFile); var movesText = File.ReadAllLines(MovesFile); Settings settings = null; FluentValidation.Results.ValidationResult settingsValidationResult = null; try { var settingsValidator = new SettingsValidator(); settings = JsonConvert.DeserializeObject <Settings>(settingsText); settingsValidationResult = settingsValidator.Validate(settings); if (!settingsValidationResult.IsValid) { foreach (var error in settingsValidationResult.Errors) { Console.WriteLine(error.ErrorMessage); } } } catch (JsonException ex) { Console.WriteLine("The settings file contains an invalid configuration."); Console.WriteLine(ex.Message); } if (settingsValidationResult?.IsValid != true) { return; } var turtleFactory = new TurtleFactory(settings); ProcessMoves(turtleFactory, settings, movesText); }
private void ValidateXMLVersion(string filePath) { var versionControl = new SettingsVersionControl(); var validator = new SettingsValidator(); if (File.Exists(filePath)) { versionControl.UpdateSettingsFile(filePath); bool isValid = validator.ValidateSettingsFile(filePath, true); if (!isValid) { } } }
public void InvalidSettingsNoMinesTest() { string json = @"{ 'board': { 'width': 7, 'height': 6 }, 'startTile':{'x':0,'y':0}, 'exitTile':{'x':6, 'y':5}, 'direction':'North' }"; Settings settings = JsonConvert.DeserializeObject <Settings>(json); var settingsValidator = new SettingsValidator(); Assert.False(settingsValidator.Validate(settings).IsValid); }
public void validation_should_fail_for_filename_which_does_not_follow_convention() { // Arrange var settings = new Settings { EncryptAction = EncryptAction.Decrypt, InputFileName = "wrongname", Password = "******" }; var target = new SettingsValidator(); // Act var result = target.Validate(settings); // Assert Assert.NotNull(result); Assert.Equal(1, result.Count); }
public void validation_should_pass_for_encrypt_option_input_filename_and_password() { // Arrange var settings = new Settings { EncryptAction = EncryptAction.Encrypt, InputFileName = "test", Password = "******" }; var target = new SettingsValidator(); // Act var result = target.Validate(settings); // Assert Assert.NotNull(result); Assert.Equal(0, result.Count); }
public void validation_should_pass_for_minimal_arguments() { // Arrange var settings = new Settings { InputDir = "C:\\", OutputDir = "C:\\", Width = 120 }; var target = new SettingsValidator(settings); // Act var result = target.Validate(); // Assert Assert.NotNull(result); Assert.Equal(0, result.ErrorMessages.Count); }
protected void ValidateXMLVersion(string filePath) { var versionControl = new SettingsVersionControl(); var Validator = new SettingsValidator(); if (File.Exists(filePath)) { versionControl.UpdateSettingsFile(filePath); bool isValid = Validator.ValidateSettingsFile(filePath, false); if (!isValid) { if (Param.Value != null && Param.Value.Count > 0) { this.Close(); } } } }
protected override async void Settings_SettingsChanged(Settings newSettings) { ProxyPanelViewModel proxyPanelViewModel = this; bool flag = SettingsValidator.IsHaveChangeForProxy(proxyPanelViewModel._settigs, newSettings); // ISSUE: reference to a compiler-generated method //proxyPanelViewModel.\U+003C\U+003En__0(newSettings); if (flag) { if (proxyPanelViewModel.StatusVisibility == Visibility.Visible) { proxyPanelViewModel.ShowThisView(); } await proxyPanelViewModel.UpdateProxyInProgram(newSettings, true); proxyPanelViewModel.RestoreSettingsFromProxyConfigAll(newSettings); } proxyPanelViewModel.CalcVisibleProxyList(); }
public FormSettings(Settings settings, SettingsValidator validator) { // // Required for Windows Form Designer support // InitializeComponent(); // Keep track of the validator. this.validator = validator; // This assumes all fonts on the form are the same size. Graphics g = CreateGraphics(); int charWidth = (int)g.MeasureString("H", Font).Width; // Keep a reference to the supplied Settings object. this.settings = settings; // Create a tab page for each settings group. for (int i = 0; i < settings.Count; i++) { Setting setting = settings[i]; int j = 0; while ((j < tabControl.TabPages.Count) && (setting.Group != tabControl.TabPages[j].Text)) j++; if (j >= tabControl.TabPages.Count) { TabPage newPage = new TabPage(); newPage.Text = setting.Group; tabControl.TabPages.Add(newPage); } } // Create a scrollable panel on each tab page. controlPanels = new ScrollablePanel[tabControl.TabPages.Count]; for (int i = 0; i < tabControl.TabPages.Count; i++) { controlPanels[i] = new ScrollablePanel(); controlPanels[i].Location = new Point(0, 0); controlPanels[i].Size = tabControl.TabPages[i].ClientSize; tabControl.TabPages[i].Controls.Add(controlPanels[i]); } // Create controls for each setting. controls = new Control[settings.Count]; settingButtonProperties = new SettingButtonProperties[settings.Count]; int[] controlOffset = new int[tabControl.TabPages.Count]; for (int i = 0; i < settings.Count; i++) { Setting setting = settings[i]; // Assemble the parameters for the setting. int j = 0; System.Collections.Hashtable parameters = new Hashtable(); if (setting.Params.Length % 2 != 0) throw new Exception("Params array does not have an even number of elements"); while (j < setting.Params.Length) { parameters[setting.Params[j]] = setting.Params[j + 1]; j += 2; } // Find the corresponding tab page and panel. j = 0; while ((j < tabControl.TabPages.Count) && (setting.Group != tabControl.TabPages[j].Text)) j++; if (j >= tabControl.TabPages.Count) throw new Exception("Tab page not found. Should be impossible."); ScrollablePanel controlPanel = controlPanels[j]; int maxControlWidth = controlPanel.ContentWidth - 2 * marginLeft; // Add the appropriate control. if (setting.Type == "boolean") { // The caption is part of the check box control. CheckBox checkBox = new CheckBox(); checkBox.Text = setting.Caption; checkBox.Width = maxControlWidth; checkBox.Checked = (bool)setting.Value; controls[i] = checkBox; } else { // Display a caption with the corresponding control underneath it. Label caption = new Label(); caption.Left = marginLeft; caption.Top = marginTop + controlOffset[j]; caption.Width = maxControlWidth; caption.Text = setting.Caption; controlOffset[j] += caption.Height; controlPanel.ContentControls.Add(caption); switch (setting.Type) { case "string": case "integer": case "long": case "double": { int maxLength = parameters.Contains("maxlength") ? (int)parameters["maxlength"] : 0; TextBox textBox = new TextBox(); if (maxLength > 0) { textBox.MaxLength = maxLength; textBox.ClientSize = new Size((maxLength + 1) * charWidth, textBox.ClientSize.Height); if (textBox.Width > maxControlWidth) textBox.Width = maxControlWidth; } else { textBox.Width = maxControlWidth; } textBox.Text = setting.Value.ToString(); textBox.GotFocus += new EventHandler(textBox_GotFocus); textBox.LostFocus += new EventHandler(textBox_LostFocus); controls[i] = textBox; break; } case "updown": { if (! parameters.Contains("min") || ! parameters.Contains("max")) throw new Exception("Missing 'min' and/or 'max' parameter(s)"); int maxLength = parameters.Contains("maxlength") ? (int)parameters["maxlength"] : 0; int min = (int)parameters["min"]; int max = (int)parameters["max"]; NumericUpDown upDown = new NumericUpDown(); upDown.Value = (int)setting.Value; upDown.Minimum = min; upDown.Maximum = max; if (maxLength > 0) { upDown.ClientSize = new Size((maxLength + 1) * charWidth + 30, upDown.ClientSize.Height); if (upDown.Width > maxControlWidth) upDown.Width = maxControlWidth; } else { upDown.Width = maxControlWidth; } controls[i] = upDown; break; } case "comportin": case "comportout": { Button button = new Button(); button.Text = ".."; button.Width = 20; button.Top = marginTop + controlOffset[j]; button.Left = controlPanel.ContentWidth - marginLeft - button.Width; button.Click += new EventHandler(SettingButtonClick); settingButtonProperties[i] = new SettingButtonProperties(button, setting.Value); controlPanel.ContentControls.Add(button); TextBox textBox = new TextBox(); textBox.ReadOnly = true; textBox.Width = button.Left - marginLeft - 2; textBox.Text = GetComPortDescription(setting.Value.ToString()); controls[i] = textBox; break; } case "combobox": { if (! parameters.Contains("items")) throw new Exception("Missing 'items' parameter"); object[] items = (object[])parameters["items"]; ComboBox combo = new ComboBox(); combo.Width = maxControlWidth; for (int k = 0; k < items.Length; k++) combo.Items.Add(items[k]); combo.SelectedItem = setting.Value; controls[i] = combo; break; } case "openfile": case "savefile": case "exefile": { object data = null; if (setting.Type != "exefile") { data = new FileDialogData(parameters.Contains("filter") ? (string)parameters["filter"] : "All Files (*.*)|*.*", parameters.Contains("filterindex") ? (int)parameters["filterindex"] : 1, parameters.Contains("initialdir") ? (string)parameters["initialdir"] : ""); } Button button = new Button(); button.Text = ".."; button.Width = 20; button.Top = marginTop + controlOffset[j]; button.Left = controlPanel.ContentWidth - marginLeft - button.Width; button.Click += new EventHandler(SettingButtonClick); settingButtonProperties[i] = new SettingButtonProperties(button, data); controlPanel.ContentControls.Add(button); TextBox textBox = new TextBox(); textBox.Width = button.Left - marginLeft - 2; textBox.Text = setting.Value.ToString(); textBox.GotFocus += new EventHandler(textBox_GotFocus); textBox.LostFocus += new EventHandler(textBox_LostFocus); controls[i] = textBox; break; } default: { throw new Exception("Unknown setting type: " + setting.Type); } } } controls[i].Left = marginLeft; controls[i].Top = marginTop + controlOffset[j]; controlOffset[j] += controls[i].Height + controlSpacing; controlPanel.ContentControls.Add(controls[i]); } // Set the heights of the control panel contents. for (int i = 0; i < controlPanels.Length; i++) controlPanels[i].ContentHeight = controlOffset[i]; }
public bool ShowSettingsDialog(IExtension sender, Settings settings, SettingsValidator validator) { FormSettings settingsDialog = new FormSettings(settings, validator); try { return settingsDialog.ShowDialog() == DialogResult.OK; } finally { settingsDialog.Dispose(); } }