public void Do() { var nameValueCollection = new NameValueCollection { { "urn:milou-deployer:target", "instance1" }, { "urn:milou-deployer:target:instance1:id", "myId1" }, { "urn:milou-deployer:target:instance1:name", "myName1" }, { "urn:milou-deployer:target:instance1:packageId", "myAllowedPackageId1.1" }, { "urn:milou-deployer:target:instance1:allow-Prerelease", "true" }, { "urn:milou-deployer:target:instance1:allowed-Package-Names", "myAllowedPackageId1.1" }, { "urn:milou-deployer:target:instance1:uri", "http://www.google.se" }, { "urn:milou-deployer:target:instance2:id", "myId2" }, { "urn:milou-deployer:target:instance2:name", "myName2" }, { "urn:milou-deployer:target:instance2:packageId", "myAllowedPackageId2.1" }, { "urn:milou-deployer:target:instance2:allow-Prerelease", "false" } }; var key_value_configuration = new InMemoryKeyValueConfiguration(nameValueCollection); var targets = key_value_configuration.GetInstances <DeploymentTarget>(); Console.WriteLine(JsonConvert.SerializeObject(targets, Formatting.Indented)); Assert.NotEqual(default, targets);
public async Task IpClaimMissingShouldMarkContextSucceeded() { ILogger logger = Logger.None; var nameValueCollection = new NameValueCollection { [DeployerAppConstants.AllowedIpNetworks] = "192.168.0.0/24" }; var configuration = new InMemoryKeyValueConfiguration(nameValueCollection); var handler = new DefaultAuthorizationHandler(configuration, logger, ImmutableArray <AllowedEmail> .Empty, ImmutableArray <AllowedEmailDomain> .Empty); IEnumerable <Claim> claims = ImmutableArray <Claim> .Empty; var user = new ClaimsPrincipal(new ClaimsIdentity(claims)); var authorizationHandlerContext = new AuthorizationHandlerContext( new IAuthorizationRequirement[] { new DefaultAuthorizationRequirement() }, user, null); await handler.HandleAsync(authorizationHandlerContext); Assert.False(authorizationHandlerContext.HasSucceeded); }
public void ItShouldUseValuesDefined() { var inMemoryKeyValueConfiguration = new InMemoryKeyValueConfiguration(new NameValueCollection { { "a:b:d", "234" } }); IConfigurationRoot configurationRoot = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary <string, string> { ["a:b:c"] = "123" }) .AddKeyValueConfigurationSource(inMemoryKeyValueConfiguration).Build(); IConfigurationSection configurationSection = configurationRoot.GetSection("a"); Assert.Equal("a", configurationSection.Key); Assert.Equal("a", configurationSection.Path); IConfigurationSection subSection = configurationSection.GetSection("b"); Assert.Equal("b", subSection.Key); Assert.Equal("a:b", subSection.Path); IConfigurationSection subSubSection = subSection.GetSection("c"); Assert.Equal("c", subSubSection.Key); Assert.Equal("a:b:c", subSubSection.Path); Assert.Equal("123", subSubSection.Value); IConfigurationSection subSubSectionD = subSection.GetSection("d"); Assert.Equal("d", subSubSectionD.Key); Assert.Equal("a:b:d", subSubSectionD.Path); Assert.Equal("234", subSubSectionD.Value); }
public async Task IpClaimInRangeForMultipleAllowedNetworksShouldMarkContextSucceeded() { ILogger logger = Logger.None; var nameValueCollection = new NameValueCollection { { DeployerAppConstants.AllowedIpNetworks, "192.168.0.0/24" }, { DeployerAppConstants.AllowedIpNetworks, "192.168.0.0/16" } }; Assert.Equal(2, nameValueCollection.GetValues(DeployerAppConstants.AllowedIpNetworks)?.Length); var configuration = new InMemoryKeyValueConfiguration(nameValueCollection); var handler = new DefaultAuthorizationHandler(configuration, logger, ImmutableArray <AllowedEmail> .Empty, ImmutableArray <AllowedEmailDomain> .Empty); IEnumerable <Claim> claims = new[] { new Claim(CustomClaimTypes.IpAddress, "192.168.0.2") }; var user = new ClaimsPrincipal(new ClaimsIdentity(claims)); var authorizationHandlerContext = new AuthorizationHandlerContext( new IAuthorizationRequirement[] { new DefaultAuthorizationRequirement() }, user, null); await handler.HandleAsync(authorizationHandlerContext); Assert.True(authorizationHandlerContext.HasSucceeded); }
public AppVersion( [NotNull] DeploymentTarget target, string message, IReadOnlyCollection <PackageVersion> availablePackages) { Properties = new InMemoryKeyValueConfiguration(new NameValueCollection()); Target = target; Message = message; AvailablePackageVersions = availablePackages.SafeToImmutableArray(); Status = GetStatus(); }
public static void Execute() { var collection = new NameValueCollection { { string.Empty, string.Empty }, { null, null }, { null, string.Empty }, { string.Empty, null }, { "\t", "\t" }, { "urn:test:key", "a-test-value" }, { "urn:test:KEY", "second-test-value" }, { "urn:another-key", "another-test-value" } }; IKeyValueConfiguration appSettingsKeyValueConfiguration = new InMemoryKeyValueConfiguration(collection); KeyValueConfigurationManager.Add(appSettingsKeyValueConfiguration).Build(); var goodKeys = new List <string> { "a-non-existing-key", "urn:test:key", "urn:TEST:key", "urn:test:KEY", "urn:another-key" }; var keys = Specials.Special.ToList(); keys.AddRange(goodKeys.Select(goodKey => new KeyValuePair <string, string?>(goodKey, goodKey))); var builder = new StringBuilder(); foreach (var pair in keys) { builder.Append("Key: ").AppendLine(pair.Key); string?value = appSettingsKeyValueConfiguration.ValueOrDefault(pair.Value !); string displayValue = Specials.GetDisplayValue(value !); builder.Append("\t Instance: ").AppendLine(displayValue); string staticValue = StaticKeyValueConfigurationManager.AppSettings[pair.Value]; string staticDisplayValue = Specials.GetDisplayValue(staticValue); builder.Append("\t Static: ").AppendLine(staticDisplayValue); } Console.WriteLine(builder.ToString()); }
private static AppSettingsBuilder AddLoggingSettings(this AppSettingsBuilder builder) { var loggingSettings = new NameValueCollection { { "Logging:LogLevel:Default", "Warning" }, { "Logging:LogLevel:System.Net.Http.HttpClient", "Warning" }, { "LogLevel:System.Net.Http.HttpClient", "Warning" } }; var memoryKeyValueConfiguration = new InMemoryKeyValueConfiguration(loggingSettings); return(builder.Add(memoryKeyValueConfiguration)); }
public static void Execute() { var collection = new NameValueCollection { { "urn:test:key", "a" }, { "urn:another-key", "b" }, { "urn:yet-another-key", "c" } }; IKeyValueConfiguration appSettingsKeyValueConfiguration = new InMemoryKeyValueConfiguration(collection); KeyValueConfigurationManager.Add(appSettingsKeyValueConfiguration).Build(); bool succeeded = true; Parallel.For( 1, 1001, index => { Console.WriteLine("Loop index {0} on thread {1}", index, Thread.CurrentThread.ManagedThreadId); string a = StaticKeyValueConfigurationManager.AppSettings["urn:test:key"]; if (a != "a") { Console.WriteLine("WRONG a in index {0}, value {1}", index, a); succeeded = false; } string b = StaticKeyValueConfigurationManager.AppSettings["urn:another-key"]; if (b != "b") { Console.WriteLine("WRONG b in index {0}, value {1}", index, b); succeeded = false; } string c = StaticKeyValueConfigurationManager.AppSettings["urn:yet-another-key"]; if (c != "c") { Console.WriteLine("WRONG c in index {0}, value {1}", index, c); succeeded = false; } }); Console.WriteLine(succeeded ? "OK" : "Failed"); }
public void ItShouldResolveSingleInstanceFromUrn() { var inMemoryKeyValueConfiguration = new InMemoryKeyValueConfiguration(new NameValueCollection { { "urn:test:simple:instance:name", "John" }, { "urn:test:simple:instance:age", "42" } }); IConfigurationRoot configurationRoot = new ConfigurationBuilder() .AddKeyValueConfigurationSource(inMemoryKeyValueConfiguration).Build(); SimpleCtorType?simpleCtorType = configurationRoot.ToKeyValueConfigurator().GetInstance <SimpleCtorType>(); Assert.NotNull(simpleCtorType); Assert.Equal("John", simpleCtorType.Name); Assert.Equal(42, simpleCtorType.Age); }
public BenchmarkBindConfigurationKey() { var keys = new NameValueCollection { { "urn:required:type:with:validation:instance:name", "abc" }, { "urn:required:type:with:validation:instance:value", "123" } }; var configuration = new InMemoryKeyValueConfiguration(keys); var configurationRegistrations = configuration.GetRegistrations(typeof(ValidatableRequired)); var configurationInstanceHolder = configurationRegistrations.CreateHolder(); _serviceProvider = new ServiceCollection() .AddConfigurationInstanceHolder(configurationInstanceHolder) .BuildServiceProvider(); }
public void ItShouldResolveMultipleInstancesFromUrn() { var inMemoryKeyValueConfiguration = new InMemoryKeyValueConfiguration(new NameValueCollection { { "urn:test:simple:instance:name", "John" }, { "urn:test:simple:instance:age", "42" } }); IConfigurationRoot configurationRoot = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary <string, string> { ["urn:test:simple:agent:name"] = "James", ["urn:test:simple:agent:age"] = "50" }) .AddKeyValueConfigurationSource(inMemoryKeyValueConfiguration).Build(); ImmutableArray <SimpleCtorType> simpleCtorType = configurationRoot.ToKeyValueConfigurator().GetInstances <SimpleCtorType>(); Assert.NotEmpty(simpleCtorType); Assert.Contains(new SimpleCtorType("John", 42), simpleCtorType, SimpleCtorType.NameAgeComparer); Assert.Contains(new SimpleCtorType("James", 50), simpleCtorType, SimpleCtorType.NameAgeComparer); }
public static IKeyValueConfiguration ToKeyValueConfiguration(this IEnumerable <string> args) { var nameValueCollection = new NameValueCollection(StringComparer.OrdinalIgnoreCase); foreach (string arg in args.Where(a => a.Count(c => c == SplitChar) == 1 && a.Length >= 3)) { var parts = arg.Split(VariableAssignmentCharacter, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 2) { continue; } string key = parts[0]; string value = parts[1]; nameValueCollection.Add(key, value); } var inMemoryKeyValueConfiguration = new InMemoryKeyValueConfiguration(nameValueCollection); return(inMemoryKeyValueConfiguration); }
public static MultiSourceKeyValueConfiguration InitializeConfiguration( IReadOnlyList <string> args, [NotNull] Func <string, string> basePath, ILogger logger, IReadOnlyCollection <Assembly> scanAssemblies, string contentBasePath) { if (basePath == null) { throw new ArgumentNullException(nameof(basePath)); } string environmentBasedSettingsPath = Environment.GetEnvironmentVariable(ConfigurationConstants.JsonSettingsFile); string environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"; AppSettingsBuilder appSettingsBuilder = KeyValueConfigurationManager .Add(new InMemoryKeyValueConfiguration(new NameValueCollection())); foreach (Assembly currentAssembly in scanAssemblies.OrderBy(assembly => assembly.FullName)) { appSettingsBuilder = appSettingsBuilder.Add( new ReflectionKeyValueConfiguration(currentAssembly)); } var loggingSettings = new NameValueCollection { { "Logging:LogLevel:Default", "Warning" }, { "Logging:LogLevel:System.Net.Http.HttpClient", "Warning" }, { "LogLevel:System.Net.Http.HttpClient", "Warning" } }; FileInfo MachineSpecificConfig(DirectoryInfo directoryInfo) { return(directoryInfo.GetFiles($"settings.{Environment.MachineName}.json").SingleOrDefault()); } string MachineSpecificFile() { var baseDirectory = new DirectoryInfo(basePath(null)); FileInfo machineSpecificConfig = null; DirectoryInfo currentDirectory = baseDirectory; while (machineSpecificConfig is null && currentDirectory != null) { try { machineSpecificConfig = MachineSpecificConfig(currentDirectory); currentDirectory = currentDirectory.Parent; } catch (Exception ex) when(!ex.IsFatal()) { logger.Warning(ex, "Could not find machine specific config file in any parent directory starting with base directory {BaseDirectory}", baseDirectory.FullName); return(null); } } return(machineSpecificConfig?.FullName); } appSettingsBuilder = appSettingsBuilder .Add(new InMemoryKeyValueConfiguration(loggingSettings)) .Add(new JsonKeyValueConfiguration(basePath("settings.json"), false)) .Add(new JsonKeyValueConfiguration(basePath($"settings.{environmentName}.json"), false)); string machineSpecificFile = MachineSpecificFile(); if (!string.IsNullOrWhiteSpace(machineSpecificFile)) { appSettingsBuilder = appSettingsBuilder.Add(new JsonKeyValueConfiguration(machineSpecificFile)); } if (environmentBasedSettingsPath.HasValue() && File.Exists(environmentBasedSettingsPath)) { appSettingsBuilder = appSettingsBuilder.Add(new JsonKeyValueConfiguration(environmentBasedSettingsPath, true)); logger.Information("Added environment based configuration from key '{Key}', file '{File}'", ConfigurationConstants.JsonSettingsFile, environmentBasedSettingsPath); } var nameValueCollection = new NameValueCollection(StringComparer.OrdinalIgnoreCase); const char variableAssignmentCharacter = '='; foreach (string arg in args.Where(a => a.Count(c => c == variableAssignmentCharacter) == 1 && a.Length >= 3)) { string[] parts = arg.Split(variableAssignmentCharacter, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 2) { Console.WriteLine($"arg {arg} has length {parts.Length}"); continue; } string key = parts[0]; string value = parts[1]; nameValueCollection.Add(key, value); } var inMemoryKeyValueConfiguration = new InMemoryKeyValueConfiguration(nameValueCollection); MultiSourceKeyValueConfiguration multiSourceKeyValueConfiguration = appSettingsBuilder .Add(new JsonKeyValueConfiguration(Path.Combine(contentBasePath, "config.user"), throwWhenNotExists: false)) .Add(new EnvironmentVariableKeyValueConfigurationSource()) .Add(inMemoryKeyValueConfiguration) .DecorateWith(new ExpandKeyValueConfigurationDecorator()) .Build(); logger.Information("Configuration done using chain {Chain}", multiSourceKeyValueConfiguration.SourceChain); return(multiSourceKeyValueConfiguration); }