/// <summary> /// Loads the Assembly's Configuration and other Configurations based on the type. /// </summary> /// <param name="type"></param> private static void BootstrapConfiguration(Type type) { var builder = new ConfigurationBuilder(); builder.AddUserSecrets(Assembly.GetAssembly(type), false, true); if (File.Exists("./settings.json")) { builder.AddJsonFile($"./settings.json"); Log($"Loading : ./settings.json"); } if (File.Exists("./appsettings.json")) { builder.AddJsonFile($"./appsettings.json"); Log($"Loading : ./appsettings.json"); } foreach (IConfigurationSource configurationSource in builder.Sources) { JsonConfigurationSource source = (JsonConfigurationSource)configurationSource; if (source != null) { //source.ReloadOnChange = true; Log($@"Loading Source: {source.Path} Reloads on Change:{source.ReloadOnChange}"); } } foreach (KeyValuePair <string, object> builderProperty in builder.Properties) { Log($@"{builderProperty.Key}:{builderProperty.Value.GetType()}"); } _configuration = builder.Build(); }
public JsonCriptoConfigurationProvider(JsonConfigurationSource source, byte[] key, byte[] iv) : base(source) { Aes aes = Aes.Create(); Decryptor = aes.CreateDecryptor(key, iv); Encryptor = aes.CreateEncryptor(key, iv); }
/// <summary> /// Добавление всех конфигурационных файлов в конфигурацию. /// Файлы конфигурации определяются параметром <paramref name="searchPatterns"/> /// </summary> /// <param name="builder">ConfigurationBuilder в который добавляются конфигурации.</param> /// <param name="configurationPath">Директория для поиска файлов конфигурации.</param> /// <param name="searchPatterns">Паттерны для поиска файлов.</param> /// <returns>Итоговый ConfigurationBuilder.</returns> public static IConfigurationBuilder AddConfigurationFiles(this IConfigurationBuilder builder, string configurationPath, string[] searchPatterns) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } foreach (var searchPattern in searchPatterns) { foreach (var file in Directory.EnumerateFiles(configurationPath, searchPattern, SearchOption.TopDirectoryOnly)) { var extension = Path.GetExtension(file)?.ToLower(); if (extension == ".xml") { builder = builder.AddXmlFile(file, optional: false, reloadOnChange: true); } if (extension == ".json") { // Создадим провайдер Json и обернем его в свой декоратор. var jsonConfigurationSource = new JsonConfigurationSource { Path = file.PathNormalize(), Optional = false, ReloadOnChange = true }; jsonConfigurationSource.ResolveFileProvider(); var statelessEvaluators = builder.Properties.GetValue(BuilderContext.Key.StatelessEvaluators) ?? Array.Empty <IValueEvaluator>(); builder.Add(new ProcessIncludesConfigurationSource(jsonConfigurationSource, configurationPath.PathNormalize(), statelessEvaluators)); } } } return(builder); }
public static AppSettingsFacade LoadFromJsonFile(string appConfigFilePath) { AppSettingsFacade appSettingsFacade; IConfigurationBuilder configurationBuilder; JsonConfigurationSource configurationSource; IConfigurationProvider configurationProvider; IConfigurationRoot configurationRoot; if ((object)appConfigFilePath == null) { throw new ArgumentNullException(nameof(appConfigFilePath)); } configurationBuilder = new ConfigurationBuilder(); configurationSource = new JsonConfigurationSource() { Optional = false, Path = appConfigFilePath }; configurationProvider = new JsonConfigurationProvider(configurationSource); configurationBuilder.Add(configurationSource); configurationRoot = configurationBuilder.Build(); appSettingsFacade = new AppSettingsFacade(configurationRoot); return(appSettingsFacade); }
public void PropertiesAreSortedByNumberOnlyFirst() { var json = @"{ ""setting"": { ""hello"": ""a"", ""bob"": ""b"", ""42"": ""c"", ""4"":""d"", ""10"": ""e"", ""1text"": ""f"" } }"; var jsonConfigSource = new JsonConfigurationSource { FileProvider = TestStreamHelpers.StringToFileProvider(json) }; var configurationBuilder = new ConfigurationBuilder(); configurationBuilder.Add(jsonConfigSource); var config = configurationBuilder.Build(); var configurationSection = config.GetSection("setting"); var indexConfigurationSections = configurationSection.GetChildren().ToArray(); Assert.Equal(6, indexConfigurationSections.Count()); Assert.Equal("4", indexConfigurationSections[0].Key); Assert.Equal("10", indexConfigurationSections[1].Key); Assert.Equal("42", indexConfigurationSections[2].Key); Assert.Equal("1text", indexConfigurationSections[3].Key); Assert.Equal("bob", indexConfigurationSections[4].Key); Assert.Equal("hello", indexConfigurationSections[5].Key); }
static void Main(string[] args) { JsonConfigurationSource source = new JsonConfigurationSource() { Path = "settings.json", }; var builder = new ConfigurationBuilder(); builder.Add(source); var configuration = builder.Build(); Console.WriteLine($" ClassNo = { configuration["ClassNo"] }"); Console.WriteLine($" ClassDesc = { configuration["ClassDesc"] }"); Console.WriteLine("Students :"); Console.Write(configuration["Students:0:name"]); Console.WriteLine($" age: { configuration["Students:0:age"]}"); Console.Write(configuration["Students:1:name"]); Console.WriteLine($" age: { configuration["Students:1:age"]}"); Console.Write(configuration["Students:2:name"]); Console.WriteLine($" age: { configuration["Students:2:age"]}"); Console.ReadLine(); }
public void EmptyArrayNotIgnored() { var json = @"{ ""ip"": { ""array"": [ ], ""object"":{ } } }"; var jsonConfigSource = new JsonConfigurationSource { FileProvider = TestStreamHelpers.StringToFileProvider(json) }; var configurationBuilder = new ConfigurationBuilder(); configurationBuilder.Add(jsonConfigSource); var config = configurationBuilder.Build(); var configurationSection = config.GetSection("ip"); var ipSectionChildren = configurationSection.GetChildren().ToArray(); Assert.Equal(1, config.GetChildren().Count()); Assert.Equal(2, ipSectionChildren.Count()); Assert.Equal("array", ipSectionChildren[0].Key); Assert.Null(ipSectionChildren[0].Value); Assert.Equal("object", ipSectionChildren[1].Key); Assert.Null(ipSectionChildren[1].Value); Assert.Equal(0, ipSectionChildren[0].GetChildren().Count()); Assert.Equal(0, ipSectionChildren[1].GetChildren().Count()); }
public void PropertiesAreSortedByNumberOnlyFirst() { var json = @"{ 'setting': { 'hello': 'a', 'bob': 'b', '42': 'c', '4':'d', '10': 'e', '1text': 'f', } }"; var jsonConfigSource = new JsonConfigurationSource { FileProvider = TestStreamHelpers.StringToFileProvider(json) }; var configurationBuilder = new ConfigurationBuilder(); configurationBuilder.Add(jsonConfigSource); var config = configurationBuilder.Build(); var configurationSection = config.GetSection("setting"); var indexConfigurationSections = configurationSection.GetChildren().ToArray(); Assert.Equal(6, indexConfigurationSections.Count()); Assert.Equal("4", indexConfigurationSections[0].Key); Assert.Equal("10", indexConfigurationSections[1].Key); Assert.Equal("42", indexConfigurationSections[2].Key); Assert.Equal("1text", indexConfigurationSections[3].Key); Assert.Equal("bob", indexConfigurationSections[4].Key); Assert.Equal("hello", indexConfigurationSections[5].Key); }
/// <summary> /// JSON配置文件 /// </summary> public void GetJsonConfig() { string path = Path.Combine(AppContext.BaseDirectory, "configs\\config.json"); //方式一 var builder = new ConfigurationBuilder(); var config = builder.AddJsonFile(path).Build(); Console.WriteLine("配置文件port:one值:" + config["port:one"]); //方式二 //Console.WriteLine($"config.json 的内容:{File.ReadAllText(path)}"); var source = new JsonConfigurationSource() { Optional = false, ReloadOnChange = false }; var provider = new JsonConfigurationProvider(source); provider.Load(new FileStream(path, FileMode.Open)); provider.TryGet("url", out var url); Console.WriteLine($"url={url}"); provider.TryGet("port:one", out var one); Console.WriteLine($"port-one={one}"); provider.TryGet("port:two", out var two); Console.WriteLine($"port0two={two}"); }
/// <summary> /// Adds a JSON configuration source to <paramref name="builder"/>. /// </summary> /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param> /// <param name="provider">The <see cref="IFileProvider"/> to use to access the file.</param> /// <param name="path">Path to the base path stored in /// <see cref="IConfigurationBuilder.Properties"/> of <paramref name="builder"/>.</param> /// <param name="optional">Whether the file is optional.</param> /// <param name="reloadOnChange">Whether the configuration should be reloaded if the file changes.</param> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddJsonFileFromAbsolutePath(this IConfigurationBuilder builder, IFileProvider provider, string path, bool optional, bool reloadOnChange) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (string.IsNullOrEmpty(path)) { throw new ArgumentException(ChimpLab.Extensions.Configuration.Json.Resources.Error_InvalidFilePath, nameof(path)); } if (provider == null) { var directoryName = Path.GetDirectoryName(path); if (!ShouldDirectoryExist(optional, reloadOnChange) && !Directory.Exists(directoryName)) { return(builder); } provider = new PhysicalFileProvider(directoryName); path = Path.GetFileName(path); } var source = new JsonConfigurationSource { FileProvider = provider, Path = path, Optional = optional, ReloadOnChange = reloadOnChange }; builder.Add(source); return(builder); }
private static IConfiguration GetConfiguration() { Mock <IConfiguration> mockedConfig = new Mock <IConfiguration>(); mockedConfig.Setup(x => x.GetSection(It.IsAny <string>())).Returns <string>(s => { if (s == "appSettings") { JsonConfigurationSource configurationSource = new JsonConfigurationSource { Path = "appsettings.json", FileProvider = new PhysicalFileProvider("d:\\Git\\SportsStoreCore\\SportsStore\\SportsStore.Tests"), Optional = false, ReloadOnChange = true }; ConfigurationRoot configRoot = new ConfigurationRoot(new List <IConfigurationProvider> { new JsonConfigurationProvider(configurationSource) }); ConfigurationSection section = new ConfigurationSection(configRoot, "appSettings"); return(section); } return(null); }); return(mockedConfig.Object); }
public void ArraysAreKeptInFileOrder() { var json = @"{ 'setting': [ 'b', 'a', '2' ] }"; var jsonConfigSource = new JsonConfigurationSource(TestStreamHelpers.ArbitraryFilePath); jsonConfigSource.Load(TestStreamHelpers.StringToStream(json)); var builder = new ConfigurationBuilder(); builder.Add(jsonConfigSource, load: false); var config = builder.Build(); var configurationSection = config.GetConfigurationSection("setting"); var indexConfigurationSections = configurationSection.GetConfigurationSections().ToArray(); Assert.Equal(3, indexConfigurationSections.Count()); Assert.Equal("b", indexConfigurationSections[0].Value.Get(null)); Assert.Equal("a", indexConfigurationSections[1].Value.Get(null)); Assert.Equal("2", indexConfigurationSections[2].Value.Get(null)); }
public ConfigurationCenterProvider() { var jsonConfigurationSource = new JsonConfigurationSource(); jsonConfigurationSource.FileProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory()); jsonConfigurationSource.Path = "appsettings.json"; var jsonConfigurationProvider = new JsonConfigurationProvider(jsonConfigurationSource); jsonConfigurationProvider.Load(); jsonConfigurationProvider.TryGet("ConfigurationCenter:Host", out _remoteAddress); jsonConfigurationProvider.TryGet("ConfigurationCenter:Environment", out _environment); jsonConfigurationProvider.TryGet("ConfigurationCenter:AppId", out _appId); if (string.IsNullOrEmpty(_remoteAddress)) { throw new Exception("Can not find configurationCenter remote address from appsettings.json"); } if (string.IsNullOrEmpty(_environment)) { throw new Exception("Can not find configurationCenter environment address from appsettings.json"); } if (string.IsNullOrEmpty(_appId)) { throw new Exception("Can not find configurationCenter appid address from appsettings.json"); } }
public void ImplicitArrayItemReplacement() { var json1 = @"{ ""ip"": [ ""1.2.3.4"", ""7.8.9.10"", ""11.12.13.14"" ] }"; var json2 = @"{ ""ip"": [ ""15.16.17.18"" ] }"; var jsonConfigSource1 = new JsonConfigurationSource { FileProvider = TestStreamHelpers.StringToFileProvider(json1) }; var jsonConfigSource2 = new JsonConfigurationSource { FileProvider = TestStreamHelpers.StringToFileProvider(json2) }; var configurationBuilder = new ConfigurationBuilder(); configurationBuilder.Add(jsonConfigSource1); configurationBuilder.Add(jsonConfigSource2); var config = configurationBuilder.Build(); Assert.Equal(3, config.GetSection("ip").GetChildren().Count()); Assert.Equal("15.16.17.18", config["ip:0"]); Assert.Equal("7.8.9.10", config["ip:1"]); Assert.Equal("11.12.13.14", config["ip:2"]); }
public void JsonConfiguration_Does_Not_Throw_On_Optional_Configuration() { var configSource = new JsonConfigurationSource("NotExistingConfig.json", optional: true); configSource.Load(); Assert.Throws <InvalidOperationException>(() => configSource.Get("key")); }
public void ImplicitArrayItemReplacement() { var json1 = @"{ 'ip': [ '1.2.3.4', '7.8.9.10', '11.12.13.14' ] }"; var json2 = @"{ 'ip': [ '15.16.17.18' ] }"; var jsonConfigSource1 = new JsonConfigurationSource(TestStreamHelpers.ArbitraryFilePath); jsonConfigSource1.Load(TestStreamHelpers.StringToStream(json1)); var jsonConfigSource2 = new JsonConfigurationSource(TestStreamHelpers.ArbitraryFilePath); jsonConfigSource2.Load(TestStreamHelpers.StringToStream(json2)); var builder = new ConfigurationBuilder(); builder.Add(jsonConfigSource1, load: false); builder.Add(jsonConfigSource2, load: false); var config = builder.Build(); Assert.Equal(3, config.GetConfigurationSections("ip").Count()); Assert.Equal("15.16.17.18", config.Get("ip:0")); Assert.Equal("7.8.9.10", config.Get("ip:1")); Assert.Equal("11.12.13.14", config.Get("ip:2")); }
public void PropertiesAreSortedByNumberOnlyFirst() { var json = @"{ 'setting': { 'hello': 'a', 'bob': 'b', '42': 'c', '4':'d', '10': 'e', '1text': 'f', } }"; var jsonConfigSource = new JsonConfigurationSource(TestStreamHelpers.ArbitraryFilePath); jsonConfigSource.Load(TestStreamHelpers.StringToStream(json)); var builder = new ConfigurationBuilder(); builder.Add(jsonConfigSource, load: false); var config = builder.Build(); var configurationSection = config.GetConfigurationSection("setting"); var indexConfigurationSections = configurationSection.GetConfigurationSections().ToArray(); Assert.Equal(6, indexConfigurationSections.Count()); Assert.Equal("4", indexConfigurationSections[0].Key); Assert.Equal("10", indexConfigurationSections[1].Key); Assert.Equal("42", indexConfigurationSections[2].Key); Assert.Equal("1text", indexConfigurationSections[3].Key); Assert.Equal("bob", indexConfigurationSections[4].Key); Assert.Equal("hello", indexConfigurationSections[5].Key); }
public void ArrayMerge() { var json1 = @"{ 'ip': [ '1.2.3.4', '7.8.9.10', '11.12.13.14' ] }"; var json2 = @"{ 'ip': { '3': '15.16.17.18' } }"; var jsonConfigSource1 = new JsonConfigurationSource { FileProvider = TestStreamHelpers.StringToFileProvider(json1) }; var jsonConfigSource2 = new JsonConfigurationSource { FileProvider = TestStreamHelpers.StringToFileProvider(json2) }; var configurationBuilder = new ConfigurationBuilder(); configurationBuilder.Add(jsonConfigSource1); configurationBuilder.Add(jsonConfigSource2); var config = configurationBuilder.Build(); Assert.Equal(4, config.GetSection("ip").GetChildren().Count()); Assert.Equal("1.2.3.4", config["ip:0"]); Assert.Equal("7.8.9.10", config["ip:1"]); Assert.Equal("11.12.13.14", config["ip:2"]); Assert.Equal("15.16.17.18", config["ip:3"]); }
public void ArraysAreKeptInFileOrder() { var json = @"{ ""setting"": [ ""b"", ""a"", ""2"" ] }"; var jsonConfigSource = new JsonConfigurationSource { FileProvider = TestStreamHelpers.StringToFileProvider(json) }; var configurationBuilder = new ConfigurationBuilder(); configurationBuilder.Add(jsonConfigSource); var config = configurationBuilder.Build(); var configurationSection = config.GetSection("setting"); var indexConfigurationSections = configurationSection.GetChildren().ToArray(); Assert.Equal(3, indexConfigurationSections.Count()); Assert.Equal("b", indexConfigurationSections[0].Value); Assert.Equal("a", indexConfigurationSections[1].Value); Assert.Equal("2", indexConfigurationSections[2].Value); }
internal JsonStreamConfigurationProvider(JsonConfigurationSource source, MemoryStream stream) : base(source) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } _stream = stream; }
public void JsonConfiguration_Throws_On_Missing_Configuration_File() { var configSource = new JsonConfigurationSource("NotExistingConfig.json", optional: false); var exception = Assert.Throws <FileNotFoundException>(() => configSource.Load()); // Assert Assert.Equal(Resources.FormatError_FileNotFound("NotExistingConfig.json"), exception.Message); }
public void LoadConfig() { var jsonSource = new JsonConfigurationSource { Path = "./Data/appsettings.json" }; var jsonConfig = new JsonConfigurationProvider(jsonSource); }
public Provider(JsonConfigurationSource source, IConfigurationRoot existingConfiguration, string serverKey) : base(source) { EnsureArg.IsNotNullOrWhiteSpace(serverKey, nameof(serverKey)); _serverKey = serverKey; _existingConfiguration = existingConfiguration; }
public Provider(JsonConfigurationSource source, IConfigurationRoot existingConfiguration, string healthServerKey) : base(source) { _existingConfiguration = existingConfiguration; _authorityKey = $"{healthServerKey}:Security:Authentication:Authority"; _audienceKey = $"{healthServerKey}:Security:Authentication:Audience"; _securityEnabledKey = $"{healthServerKey}:Security:Enabled"; }
protected override void ConfigureWebHost(IWebHostBuilder builder) { base.ConfigureWebHost(builder); // This is required for testing of error pages. builder.UseEnvironment(Environments.Production); builder.ConfigureAppConfiguration((_, configBuilder) => { var jsonConfigSource = new JsonConfigurationSource { Path = GetTestRunSettingsPath(), Optional = false, }; jsonConfigSource.ResolveFileProvider(); // We add TestsSettings.json before environment variables source, // leaving a chance to override connection string via environment variables. configBuilder.Sources.InsertBeforeType(jsonConfigSource, typeof(EnvironmentVariablesConfigurationSource)); if (moviesPageSize != null) { configBuilder.AddInMemoryCollection(new[] { new KeyValuePair <string, string>("moviesPageSize", moviesPageSize.Value.ToString(CultureInfo.InvariantCulture)) }); } }); builder.ConfigureLogging((hostingContext, loggingBuilder) => { loggingBuilder.ClearProviders(); loggingBuilder.AddLogging(settings => hostingContext.Configuration.Bind("logging", settings)); }); builder.ConfigureServices(services => { services.AddSingleton <IApplicationBootstrapper>(new FakeApplicationBootstrapper <MongoUser>(authenticatedUser)); // We insert DatabaseSeeder as first service, so that it is executed before UsersInitializer. services.Insert(0, ServiceDescriptor.Scoped <IApplicationInitializer, DatabaseSeeder>()); services.AddSingleton <ISeedData>(seedData); services.AddSingleton <IMovieInfoProvider>(fakeMovieInfoProviderFactory()); // Same instance should be registered for IIdGeneratorQueue and IIdGenerator. services.AddSingleton <FakeIdGenerator>(); services.AddSingleton <IIdGeneratorQueue>(sp => sp.GetRequiredService <FakeIdGenerator>()); services.AddSingleton <IIdGenerator <ObjectId> >(sp => sp.GetRequiredService <FakeIdGenerator>()); services.AddHttpsRedirection(options => { // By default test application listens for https requests on port 5001. // We must let HTTPS redirection know that the port differs from default 443, // otherwise HTTPS redirection will not happen. // https://docs.microsoft.com/en-us/aspnet/core/security/enforcing-ssl?view=aspnetcore-3.1&tabs=visual-studio#port-configuration options.HttpsPort = 5001; }); }); }
/// <summary> /// Initializes a new instance of the <see cref="ProcessIncludesConfigurationSource"/> class. /// </summary> /// <param name="jsonConfigurationSource">jsonConfigurationSource</param> /// <param name="rootPath">rootPath</param> /// <param name="valueEvaluators">Evaluator that can be used in include.</param> public ProcessIncludesConfigurationSource( JsonConfigurationSource jsonConfigurationSource, string rootPath, IReadOnlyCollection <IValueEvaluator> valueEvaluators = null) { _jsonConfigurationSource = jsonConfigurationSource; _rootPath = rootPath; _valueEvaluators = valueEvaluators; }
public void GetSettingObjectTestThrowException() { var source = new JsonConfigurationSource <DemoSetting>(@"c:\temp\data1234.config"); var ex = Assert.Throws <ConfigurationFileSourceException>(() => source.GetSettingObject()); Assert.Equal(@"c:\temp\data1234.config", ex.FileName); Assert.Same(source, ex.ConfigurationSource); }
public IntegrationFixture() { var jsonConfigurationSource = new JsonConfigurationSource(); jsonConfigurationSource.Path = "appsettings.json"; server = new TestServer(new WebHostBuilder().UseStartup <Startup>().ConfigureAppConfiguration(b => b.Add(jsonConfigurationSource))); Client = server.CreateClient(); }
public void CtorTest() { Assert.Throws <ArgumentException>(() => new JsonConfigurationSource <object>(null)); Assert.Throws <ArgumentException>(() => new JsonConfigurationSource <object>(string.Empty)); Assert.Throws <ArgumentException>(() => new JsonConfigurationSource <object>(" ")); var source = new JsonConfigurationSource <object>("data.config"); Assert.NotNull(source); }
public void GetSettingObjectTest() { InstallDemoFileSys(); var source = new JsonConfigurationSource <DemoSetting>(@"c:\temp\data.config"); var settingObject = source.GetSettingObject() as DemoSetting; Assert.Equal("DemoDataValue", settingObject?.Text); }
public void ArrayOfObjects() { var json = @"{ 'ip': [ { 'address': '1.2.3.4', 'hidden': false }, { 'address': '5.6.7.8', 'hidden': true } ] }"; var jsonConfigSource = new JsonConfigurationSource(TestStreamHelpers.ArbitraryFilePath); jsonConfigSource.Load(TestStreamHelpers.StringToStream(json)); Assert.Equal("1.2.3.4", jsonConfigSource.Get("ip:0:address")); Assert.Equal("False", jsonConfigSource.Get("ip:0:hidden")); Assert.Equal("5.6.7.8", jsonConfigSource.Get("ip:1:address")); Assert.Equal("True", jsonConfigSource.Get("ip:1:hidden")); }
public void ArraysAreKeptInFileOrder() { var json = @"{ 'setting': [ 'b', 'a', '2' ] }"; var jsonConfigSource = new JsonConfigurationSource(TestStreamHelpers.ArbitraryFilePath); jsonConfigSource.Load(TestStreamHelpers.StringToStream(json)); var builder = new ConfigurationBuilder(); builder.Add(jsonConfigSource, load: false); var config = builder.Build(); var configurationSection = config.GetSection("setting"); var indexConfigurationSections = configurationSection.GetChildren().ToArray(); Assert.Equal(3, indexConfigurationSections.Count()); Assert.Equal("b", indexConfigurationSections[0].Value); Assert.Equal("a", indexConfigurationSections[1].Value); Assert.Equal("2", indexConfigurationSections[2].Value); }
public void NestedArrays() { var json = @"{ 'ip': [ [ '1.2.3.4', '5.6.7.8' ], [ '9.10.11.12', '13.14.15.16' ], ] }"; var jsonConfigSource = new JsonConfigurationSource(TestStreamHelpers.ArbitraryFilePath); jsonConfigSource.Load(TestStreamHelpers.StringToStream(json)); Assert.Equal("1.2.3.4", jsonConfigSource.Get("ip:0:0")); Assert.Equal("5.6.7.8", jsonConfigSource.Get("ip:0:1")); Assert.Equal("9.10.11.12", jsonConfigSource.Get("ip:1:0")); Assert.Equal("13.14.15.16", jsonConfigSource.Get("ip:1:1")); }
public void PropertiesAreSortedByNumberOnlyFirst() { var json = @"{ 'setting': { 'hello': 'a', 'bob': 'b', '42': 'c', '4':'d', '10': 'e', '1text': 'f', } }"; var jsonConfigSource = new JsonConfigurationSource(TestStreamHelpers.ArbitraryFilePath); jsonConfigSource.Load(TestStreamHelpers.StringToStream(json)); var builder = new ConfigurationBuilder(); builder.Add(jsonConfigSource, load: false); var config = builder.Build(); var configurationSection = config.GetSection("setting"); var indexConfigurationSections = configurationSection.GetChildren().ToArray(); Assert.Equal(6, indexConfigurationSections.Count()); Assert.Equal("setting:4", indexConfigurationSections[0].Key); Assert.Equal("setting:10", indexConfigurationSections[1].Key); Assert.Equal("setting:42", indexConfigurationSections[2].Key); Assert.Equal("setting:1text", indexConfigurationSections[3].Key); Assert.Equal("setting:bob", indexConfigurationSections[4].Key); Assert.Equal("setting:hello", indexConfigurationSections[5].Key); }
public void ArraysAreConvertedToKeyValuePairs() { var json = @"{ 'ip': [ '1.2.3.4', '7.8.9.10', '11.12.13.14' ] }"; var jsonConfigSource = new JsonConfigurationSource(TestStreamHelpers.ArbitraryFilePath); jsonConfigSource.Load(TestStreamHelpers.StringToStream(json)); Assert.Equal("1.2.3.4", jsonConfigSource.Get("ip:0")); Assert.Equal("7.8.9.10", jsonConfigSource.Get("ip:1")); Assert.Equal("11.12.13.14", jsonConfigSource.Get("ip:2")); }
public void ArrayMerge() { var json1 = @"{ 'ip': [ '1.2.3.4', '7.8.9.10', '11.12.13.14' ] }"; var json2 = @"{ 'ip': { '3': '15.16.17.18' } }"; var jsonConfigSource1 = new JsonConfigurationSource(TestStreamHelpers.ArbitraryFilePath); jsonConfigSource1.Load(TestStreamHelpers.StringToStream(json1)); var jsonConfigSource2 = new JsonConfigurationSource(TestStreamHelpers.ArbitraryFilePath); jsonConfigSource2.Load(TestStreamHelpers.StringToStream(json2)); var builder = new ConfigurationBuilder(); builder.Add(jsonConfigSource1, load: false); builder.Add(jsonConfigSource2, load: false); var config = builder.Build(); Assert.Equal(4, config.GetSection("ip").GetChildren().Count()); Assert.Equal("1.2.3.4", config["ip:0"]); Assert.Equal("7.8.9.10", config["ip:1"]); Assert.Equal("11.12.13.14", config["ip:2"]); Assert.Equal("15.16.17.18", config["ip:3"]); }