示例#1
0
        static void Main(string[] args)
        {
            Dictionary <string, string> source = new Dictionary <string, string>
            {
                ["Format:DateTime:LongDatePattern"]  = "dddd, MMMM d, yyyy",
                ["Format:DateTime:LongTimePattern"]  = "h:mm:ss tt",
                ["Format:DateTime:ShortDatePattern"] = "M/d/yyyy",
                ["Format:DateTime:ShortTimePattern"] = "h:mm tt",

                ["Format:CurrencyDecimal:Digits"] = "2",
                ["Format:CurrencyDecimal:Symbol"] = "$",
            };

            MemoryConfigurationSource memSource = new MemoryConfigurationSource();

            memSource.InitialData = source;

            //  var ss = new MemoryConfigurationProvider(memSource);


            IConfiguration configuration = new ConfigurationBuilder().Add(memSource).Build();


            var data  = configuration.GetSection("Format:DateTime:LongDatePattern").Value;
            var data2 = configuration.GetSection("Format:CurrencyDecimal:Digits").Value;

            Console.WriteLine("Hello World!");
        }
    public void CanGetSection()
    {
        // Arrange
        var initialData = new Dictionary <string, string>()
        {
            { "color", "blue" },
            { "type", "car" },
            { "wheels:year", "2008" },
            { "wheels:count", "4" },
            { "wheels:brand", "michelin" },
            { "wheels:brand:type", "rally" },
        };
        var memoryConfig = new MemoryConfigurationSource {
            InitialData = initialData
        };
        var configuration = new WebAssemblyHostConfiguration();

        // Act
        configuration.Add(memoryConfig);
        var section = configuration.GetSection("wheels").AsEnumerable(makePathsRelative: true).ToDictionary(k => k.Key, v => v.Value);

        // Assert
        Assert.Equal(4, section.Count);
        Assert.Equal("2008", section["year"]);
        Assert.Equal("4", section["count"]);
        Assert.Equal("michelin", section["brand"]);
        Assert.Equal("rally", section["brand:type"]);
    }
        private IConfigurationSection GetConfigSection(string configSectionName, bool includeB2cConfig = false)
        {
            var configAsDictionary = new Dictionary <string, string>()
            {
                { configSectionName, null },
                { $"{configSectionName}:Instance", TestConstants.AadInstance },
                { $"{configSectionName}:TenantId", TestConstants.TenantIdAsGuid },
                { $"{configSectionName}:ClientId", TestConstants.TenantIdAsGuid },
                { $"{configSectionName}:Domain", TestConstants.Domain },
            };

            if (includeB2cConfig)
            {
                configAsDictionary.Add($"{configSectionName}:SignUpSignInPolicyId", TestConstants.B2CSignUpSignInUserFlow);
                configAsDictionary[$"{configSectionName}:Instance"] = TestConstants.B2CInstance;
                configAsDictionary[$"{configSectionName}:Domain"]   = TestConstants.B2CTenant;
            }

            var memoryConfigSource = new MemoryConfigurationSource {
                InitialData = configAsDictionary
            };
            var configBuilder = new ConfigurationBuilder();

            configBuilder.Add(memoryConfigSource);
            var configSection = configBuilder.Build().GetSection(configSectionName);

            return(configSection);
        }
示例#4
0
            public TestModuleExtensionInfo(string name)
            {
                var dic1 = new Dictionary <string, string>()
                {
                    { "name", name },
                    { "desciption", name },
                    { "type", "module" },
                };

                var memConfigSrc1 = new MemoryConfigurationSource {
                    InitialData = dic1
                };
                var configurationBuilder = new ConfigurationBuilder();

                configurationBuilder.Add(memConfigSrc1);

                Manifest = new ManifestInfo(new ModuleAttribute());

                var features =
                    new List <IFeatureInfo>()
                {
                    { new FeatureInfo(name, name, 0, String.Empty, String.Empty, this, Array.Empty <string>(), false, false) }
                };

                Features = features;
            }
示例#5
0
        public static IHostBuilder UseVault(this IHostBuilder hostBuilder)
        {
            hostBuilder.ConfigureAppConfiguration((ctx, cfg) =>
            {
                var options      = cfg.Build().GetOptions <VaultOptions>("Vault");
                var enabled      = options.Enabled;
                var vaultEnabled = Environment.GetEnvironmentVariable("VAULT_ENABLED")?.ToLowerInvariant();
                if (!string.IsNullOrWhiteSpace(vaultEnabled))
                {
                    enabled = vaultEnabled == "true" || vaultEnabled == "1";
                }
                if (enabled)
                {
                    var client = new VaultStore(options);
                    var secret = client.GetDefaultAsync().GetAwaiter().GetResult();

                    var source = new MemoryConfigurationSource()
                    {
                        InitialData = secret.ToDictionary(k => k.Key, p => p.Value.ToString())
                    };
                    cfg.Add(source);
                }
            });
            return(hostBuilder);
        }
        public void Settings_Should_Update_Dictionary_Item()
        {
            var dic1 = new Dictionary <string, string>()
            {
                { "test:Name1", "Value1" },
                { "test:Name2", "Value2" }
            };

            var memSrc = new MemoryConfigurationSource {
                InitialData = dic1
            };

            var configuration = new ConfigurationBuilder()
                                .Add(memSrc)
                                .Build();

            var services = new ServiceCollection();

            services.AddOptions();

            services.Configure <ConfigurationTest2>(settings => settings.DITest = configuration.GetSection("test").GetChildren().ToDictionary(x => x.Key, x => x.Value));
            var t2 = services.BuildServiceProvider().GetService <IOptionsSnapshot <ConfigurationTest2> >();

            Assert.Equal(2, t2.Value.DITest.Count);

            configuration["test:Name1"] = "ChangedValue1";
            var t3 = services.BuildServiceProvider().GetService <IOptionsSnapshot <ConfigurationTest2> >();

            Assert.Equal("ChangedValue1", t3.Value.DITest["Name1"]);
        }
        private static async Task AddVaultAsync(this IConfigurationBuilder builder, VaultOptions options)
        {
            VerifyOptions(options);
            var(client, _) = GetClientAndSettings(options);
            if (options.Kv is null || !options.Kv.Enabled)
            {
                return;
            }

            var kvPath = options.Kv?.Path;

            if (string.IsNullOrWhiteSpace(kvPath))
            {
                throw new VaultException("Vault KV secret path can not be empty.");
            }

            Console.WriteLine($"Loading settings from Vault: '{options.Url}', KV path: '{kvPath}'.");
            var keyValueSecrets = new KeyValueSecrets(client, options);
            var secret          = await keyValueSecrets.GetAsync(kvPath);

            var parser = new JsonParser();
            var data   = parser.Parse(JObject.FromObject(secret));
            var source = new MemoryConfigurationSource {
                InitialData = data
            };

            builder.Add(source);
        }
    public void CanSetAndGetConfigurationValue()
    {
        // Arrange
        var initialData = new Dictionary <string, string>()
        {
            { "color", "blue" },
            { "type", "car" },
            { "wheels:year", "2008" },
            { "wheels:count", "4" },
            { "wheels:brand", "michelin" },
            { "wheels:brand:type", "rally" },
        };
        var memoryConfig = new MemoryConfigurationSource {
            InitialData = initialData
        };
        var configuration = new WebAssemblyHostConfiguration();

        // Act
        configuration.Add(memoryConfig);
        configuration["type"]         = "car";
        configuration["wheels:count"] = "6";

        // Assert
        Assert.Equal("car", configuration["type"]);
        Assert.Equal("blue", configuration["color"]);
        Assert.Equal("6", configuration["wheels:count"]);
    }
        public HelpControllerTests()
        {
            configData = new MemoryConfigurationSource
            {
                InitialData = new List <KeyValuePair <string, string> >()
                {
                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:Phase", "mockPhase"),
                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:EmailTemplateId", "mockInternalEmailTemplateId"),
                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:ServiceSupportEmailAddress", "mockServiceSupportEmail"),

                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:FieldMappings:0:Name", "message"),
                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:FieldMappings:0:TemplateField", "feedback-message"),
                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:FieldMappings:0:FormField", "message"),

                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:FieldMappings:1:Name", "name"),
                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:FieldMappings:1:TemplateField", "feedback-full-name"),
                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:FieldMappings:1:FormField", "full-name"),

                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:FieldMappings:2:Name", "email"),
                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:FieldMappings:2:TemplateField", "feedback-email-address"),
                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:FieldMappings:2:FormField", "email-address"),

                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmailExternal:EmailTemplateId", "mockExternalEmailTemplateId")
                }
            };
        }
示例#10
0
        /// <summary>
        /// Integrates Lockbox as a configuration source for the application settings.
        /// Specified configuration will be fetched via HTTP request and added to the builder pipeline.
        /// </summary>
        /// <param name="builder">Instance of IConfigurationBuilder</param>
        /// <param name="encryptionKey">Encryption key used for encrypting values. If omitted then "LOCKBOX_ENCRYPTION_KEY" environment variable will be used instead.</param>
        /// <param name="apiUrl">URL of the Lockbox API. If omitted then "LOCKBOX_API_URL" environment variable will be used instead.</param>
        /// <param name="apiKey">API key that will be used for authenticating HTTP requests to the Lockbox API. If omitted then "LOCKBOX_API_KEY" environment variable will be used instead.</param>
        /// <param name="boxName">Name of the box that contains specified entry defined below. If omitted then "LOCKBOX_BOX_NAME" environment variable will be used instead.</param>
        /// <param name="entryKey">Name of the entry within a box that will be used for getting configuration values. If omitted then "LOCKBOX_ENTRY_KEY" environment variable will be used instead.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public static IConfigurationBuilder AddLockbox(this IConfigurationBuilder builder,
                                                       string encryptionKey = null,
                                                       string apiUrl        = null,
                                                       string apiKey        = null,
                                                       string boxName       = null,
                                                       string entryKey      = null)
        {
            encryptionKey = GetParameterOrFail(encryptionKey, EncryptionKeyEnvironmentVariable, "encryption key");
            apiUrl        = GetParameterOrFail(apiUrl, ApiUrlEnvironmentVariable, "API key");
            apiKey        = GetParameterOrFail(apiKey, ApiKeyEnvironmentVariable, "API url");
            boxName       = GetParameterOrFail(boxName, BoxNameEnvironmentVariable, "box name");
            entryKey      = GetParameterOrFail(entryKey, EntryKeyEnvironmentVariable, "entry key");

            var lockboxClient   = new LockboxEntryClient(encryptionKey, apiUrl, apiKey);
            var entryDictionary = lockboxClient.GetEntryAsync(boxName, entryKey).Result;

            if (entryDictionary == null)
            {
                throw new ArgumentException($"Lockbox entry has not been found for key: '{entryKey}'.", nameof(entryKey));
            }

            var data   = JsonParser.Parse((JObject)entryDictionary);
            var source = new MemoryConfigurationSource {
                InitialData = data
            };

            builder.Add(source);

            return(builder);
        }
示例#11
0
        public HelpControllerTests()
        {
            configData = new MemoryConfigurationSource
            {
                InitialData = new List <KeyValuePair <string, string> >()
                {
                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:Phase", "mockPhase"),
                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:EmailTemplateId", "mockInternalEmailTemplateId"),
                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:ServiceSupportEmailAddress", "mockServiceSupportEmail"),

                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:FieldMappings:0:Name", "message"),
                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:FieldMappings:0:TemplateField", "feedback-message"),
                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:FieldMappings:0:FormField", "message"),

                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:FieldMappings:1:Name", "name"),
                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:FieldMappings:1:TemplateField", "feedback-full-name"),
                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:FieldMappings:1:FormField", "full-name"),

                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:FieldMappings:2:Name", "email"),
                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:FieldMappings:2:TemplateField", "feedback-email-address"),
                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmail:FieldMappings:2:FormField", "email-address"),

                    new KeyValuePair <string, string>("EmailNotification:FeedbackEmailExternal:EmailTemplateId", "mockExternalEmailTemplateId"),

                    new KeyValuePair <string, string>("FormsConfiguration:ServiceFeedbackForm:Name", "form1"),
                    new KeyValuePair <string, string>("FormsConfiguration:ServiceFeedbackForm:Version", "version1"),
                    new KeyValuePair <string, string>("ApplicationSettings:GFCUrls:StartPage", "start-page"),
                    new KeyValuePair <string, string>("ApplicationSettings:GFCUrls:ConfirmationPage", "confirmation-page")
                }
            };
        }
            public TestModuleExtensionInfo(string name)
            {
                var dic1 = new Dictionary <string, string>()
                {
                    { "name", name },
                    { "desciption", name },
                    { "type", "module" },
                };

                var memConfigSrc1 = new MemoryConfigurationSource {
                    InitialData = dic1
                };
                var configurationBuilder = new ConfigurationBuilder();

                configurationBuilder.Add(memConfigSrc1);

                Manifest = new ManifestInfo(configurationBuilder.Build(), "module");

                var features =
                    new List <IFeatureInfo>()
                {
                    { new FeatureInfo(name, name, 0, "", "", this, new string[0]) }
                };

                Features = features;
            }
        public void NewConfigurationSourceOverridesOldOneWhenKeyIsDuplicated()
        {
            // Arrange
            var dic1 = new Dictionary <string, string>()
            {
                { "Key1:Key2", "ValueInMem1" }
            };
            var dic2 = new Dictionary <string, string>()
            {
                { "Key1:Key2", "ValueInMem2" }
            };
            var memConfigSrc1 = new MemoryConfigurationSource(dic1);
            var memConfigSrc2 = new MemoryConfigurationSource(dic2);

            var builder = new ConfigurationBuilder();

            // Act
            builder.Add(memConfigSrc1, load: false);
            builder.Add(memConfigSrc2, load: false);

            var config = builder.Build();

            // Assert
            Assert.Equal("ValueInMem2", config["Key1:Key2"]);
        }
        public void Constructors__InitializesProperties()
        {
            ConfigServerClientSettings settings = new ConfigServerClientSettings();
            var memSource = new MemoryConfigurationSource();
            IList <IConfigurationSource> sources = new List <IConfigurationSource>()
            {
                memSource
            };
            ILoggerFactory factory = new LoggerFactory();

            var source = new ConfigServerConfigurationSource(settings, sources, new Dictionary <string, object>()
            {
                { "foo", "bar" }
            }, factory);

            Assert.Equal(settings, source.DefaultSettings);
            Assert.Equal(factory, source.LogFactory);
            Assert.Null(source.Configuration);
            Assert.NotSame(sources, source._sources);
            Assert.Single(source._sources);
            Assert.Equal(memSource, source._sources[0]);
            Assert.Single(source._properties);
            Assert.Equal("bar", source._properties["foo"]);

            var config = new ConfigurationBuilder().AddInMemoryCollection().Build();

            source = new ConfigServerConfigurationSource(settings, config, factory);
            Assert.Equal(settings, source.DefaultSettings);
            Assert.Equal(factory, source.LogFactory);
            Assert.NotNull(source.Configuration);
            var root = source.Configuration as IConfigurationRoot;

            Assert.NotNull(root);
            Assert.Same(config, root);
        }
示例#15
0
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);

            builder.RootComponents.Add <App>("app");
            var vehicleData = new Dictionary <string, string>()
            {
                { "color", "blue" },
                { "type", "car" },
                { "wheels:count", "3" },
                { "wheels:brand", "Blazin" },
                { "wheels:brand:type", "rally" },
                { "wheels:year", "2008" },
            };

            var memoryConfig = new MemoryConfigurationSource {
                InitialData = vehicleData
            };

            builder.Configuration.Add(memoryConfig);
            builder.Services.AddTransient(sp => new HttpClient {
                BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
            });

            await builder.Build().RunAsync();
        }
示例#16
0
        public void SourcesReturnsAddedConfigurationProviders()
        {
            // Arrange
            var dict = new Dictionary <string, string>()
            {
                { "Mem:KeyInMem", "MemVal" }
            };
            var memConfigSrc1 = new MemoryConfigurationSource {
                InitialData = dict
            };
            var memConfigSrc2 = new MemoryConfigurationSource {
                InitialData = dict
            };
            var memConfigSrc3 = new MemoryConfigurationSource {
                InitialData = dict
            };

            var configurationBuilder = new ConfigurationBuilder();

            // Act
            configurationBuilder.Add(memConfigSrc1);
            configurationBuilder.Add(memConfigSrc2);
            configurationBuilder.Add(memConfigSrc3);

            configurationBuilder.Build();

            // Assert
            Assert.AreEqual(new[] { memConfigSrc1, memConfigSrc2, memConfigSrc3 }, configurationBuilder.Sources);
        }
示例#17
0
        public void NewConfigurationProviderOverridesOldOneWhenKeyIsDuplicated()
        {
            // Arrange
            var dic1 = new Dictionary <string, string>()
            {
                { "Key1:Key2", "ValueInMem1" }
            };
            var dic2 = new Dictionary <string, string>()
            {
                { "Key1:Key2", "ValueInMem2" }
            };
            var memConfigSrc1 = new MemoryConfigurationSource {
                InitialData = dic1
            };
            var memConfigSrc2 = new MemoryConfigurationSource {
                InitialData = dic2
            };

            var config = new ConfigurationManager();
            IConfigurationBuilder configurationBuilder = config;

            // Act
            configurationBuilder.Add(memConfigSrc1);
            configurationBuilder.Add(memConfigSrc2);

            // Assert
            Assert.Equal("ValueInMem2", config["Key1:Key2"]);
        }
示例#18
0
        private IConfigurationSection GetConfigSection(string configSectionName)
        {
            string serializedTokenDecryptionJsonBlob = JsonSerializer.Serialize(
                s_tokenDecryptionCertificatesDescription,
                new JsonSerializerOptions
            {
                IgnoreNullValues            = true,
                PropertyNameCaseInsensitive = true,
            }).Replace(":2", ": \"Base64Encoded\"");
            var configAsDictionary = new Dictionary <string, string>()
            {
                { configSectionName, null },
                { $"{configSectionName}:Instance", TestConstants.AadInstance },
                { $"{configSectionName}:TenantId", TestConstants.TenantIdAsGuid },
                { $"{configSectionName}:ClientId", TestConstants.TenantIdAsGuid },
                { $"{configSectionName}:TokenDecryptionCertificates", serializedTokenDecryptionJsonBlob },
            };
            var memoryConfigSource = new MemoryConfigurationSource {
                InitialData = configAsDictionary
            };
            var configBuilder = new ConfigurationBuilder();

            configBuilder.Add(memoryConfigSource);
            var configSection = configBuilder.Build().GetSection(configSectionName);

            return(configSection);
        }
示例#19
0
        public void CanGetSubKey()
        {
            // Arrange
            var dic1 = new Dictionary<string, string>()
                {
                    {"Data:DB1:Connection1", "MemVal1"},
                    {"Data:DB1:Connection2", "MemVal2"}
                };
            var dic2 = new Dictionary<string, string>()
                {
                    {"DataSource:DB2:Connection", "MemVal3"}
                };
            var dic3 = new Dictionary<string, string>()
                {
                    {"Data", "MemVal4"}
                };
            var memConfigSrc1 = new MemoryConfigurationSource(dic1);
            var memConfigSrc2 = new MemoryConfigurationSource(dic2);
            var memConfigSrc3 = new MemoryConfigurationSource(dic3);

            var config = new Configuration();
            config.AddLoadedSource(memConfigSrc1);
            config.AddLoadedSource(memConfigSrc2);
            config.AddLoadedSource(memConfigSrc3);

            string memVal1, memVal2, memVal3, memVal4, memVal5;
            bool memRet1, memRet2, memRet3, memRet4, memRet5;

            // Act
            var configFocus = config.GetSubKey("Data");

            memRet1 = configFocus.TryGet("DB1:Connection1", out memVal1);
            memRet2 = configFocus.TryGet("DB1:Connection2", out memVal2);
            memRet3 = configFocus.TryGet("DB2:Connection", out memVal3);
            memRet4 = configFocus.TryGet("Source:DB2:Connection", out memVal4);
            memRet5 = configFocus.TryGet(null, out memVal5);

            // Assert
            Assert.True(memRet1);
            Assert.True(memRet2);
            Assert.False(memRet3);
            Assert.False(memRet4);
            Assert.True(memRet5);

            Assert.Equal("MemVal1", memVal1);
            Assert.Equal("MemVal2", memVal2);
            Assert.Equal("MemVal4", memVal5);

            Assert.Equal("MemVal1", configFocus.Get("DB1:Connection1"));
            Assert.Equal("MemVal2", configFocus.Get("DB1:Connection2"));
            Assert.Null(configFocus.Get("DB2:Connection"));
            Assert.Null(configFocus.Get("Source:DB2:Connection"));
            Assert.Equal("MemVal4", configFocus.Get(null));

            Assert.Equal("MemVal1", configFocus["DB1:Connection1"]);
            Assert.Equal("MemVal2", configFocus["DB1:Connection2"]);
            Assert.Null(configFocus["DB2:Connection"]);
            Assert.Null(configFocus["Source:DB2:Connection"]);
            Assert.Equal("MemVal4", configFocus[null]);
        }
示例#20
0
        public void CanGetConnectionStrings()
        {
            // Arrange
            var dic1 = new Dictionary <string, string>()
            {
                { "ConnectionStrings:DB1:Connection1", "MemVal1" },
                { "ConnectionStrings:DB1:Connection2", "MemVal2" }
            };
            var dic2 = new Dictionary <string, string>()
            {
                { "ConnectionStrings:DB2:Connection", "MemVal3" }
            };
            var memConfigSrc1 = new MemoryConfigurationSource {
                InitialData = dic1
            };
            var memConfigSrc2 = new MemoryConfigurationSource {
                InitialData = dic2
            };

            var config = new ConfigurationManager();
            IConfigurationBuilder configurationBuilder = config;

            configurationBuilder.Add(memConfigSrc1);
            configurationBuilder.Add(memConfigSrc2);

            // Act
            var memVal1 = config.GetConnectionString("DB1:Connection1");
            var memVal2 = config.GetConnectionString("DB1:Connection2");
            var memVal3 = config.GetConnectionString("DB2:Connection");

            // Assert
            Assert.Equal("MemVal1", memVal1);
            Assert.Equal("MemVal2", memVal2);
            Assert.Equal("MemVal3", memVal3);
        }
示例#21
0
        public void SourcesReturnsAddedConfigurationProviders()
        {
            // Arrange
            var dict = new Dictionary <string, string>()
            {
                { "Mem:KeyInMem", "MemVal" }
            };
            var memConfigSrc1 = new MemoryConfigurationSource {
                InitialData = dict
            };
            var memConfigSrc2 = new MemoryConfigurationSource {
                InitialData = dict
            };
            var memConfigSrc3 = new MemoryConfigurationSource {
                InitialData = dict
            };

            var config = new ConfigurationManager();
            IConfigurationBuilder configurationBuilder = config;

            // Act

            // A MemoryConfigurationSource is added by default, so there will be no error unless we clear it
            configurationBuilder.Sources.Clear();
            configurationBuilder.Add(memConfigSrc1);
            configurationBuilder.Add(memConfigSrc2);
            configurationBuilder.Add(memConfigSrc3);

            // Assert
            Assert.Equal(new[] { memConfigSrc1, memConfigSrc2, memConfigSrc3 }, configurationBuilder.Sources);
        }
    public void SettingValueUpdatesAllProviders()
    {
        // Arrange
        var initialData = new Dictionary <string, string>()
        {
            { "color", "blue" }
        };
        var source1 = new MemoryConfigurationSource {
            InitialData = initialData
        };
        var source2       = new CustomizedTestConfigurationSource();
        var configuration = new WebAssemblyHostConfiguration();

        // Act
        configuration.Add(source1);
        configuration.Add(source2);
        configuration["type"] = "car";

        // Assert
        Assert.Equal("car", configuration["type"]);
        IConfigurationRoot root = configuration;

        Assert.All(root.Providers, provider =>
        {
            provider.TryGet("type", out var value);
            Assert.Equal("car", value);
        });
    }
        private static IConfigurationRoot GenerateConfiguration(string authType)
        {
            var configSource = new MemoryConfigurationSource
            {
                InitialData = new[]
                {
                    new KeyValuePair <string, string>("ConfigurationStorageConnectionString", "UseDevelopmentStorage=true;"),
                    new KeyValuePair <string, string>("ConfigNames", "SFA.DAS.Reservations.Web,SFA.DAS.EmployerAccountAPI:AccountApi,SFA.DAS.ProviderRelationships.Api.ClientV2,SFA.DAS.Encoding"),
                    new KeyValuePair <string, string>("Environment", "DEV"),
                    new KeyValuePair <string, string>("Version", "1.0"),
                    new KeyValuePair <string, string>("UseStub", "true"),
                    new KeyValuePair <string, string>("AuthType", authType),
                    new KeyValuePair <string, string>("ReservationsApi:url", "https://local.test.com"),
                    new KeyValuePair <string, string>("ReservationsWeb:DashboardUrl", $"https://{TestDataValues.DashboardUrl}"),
                    new KeyValuePair <string, string>("ReservationsWeb:EmployerDashboardUrl", $"https://{TestDataValues.EmployerDashboardUrl}"),
                    new KeyValuePair <string, string>("ReservationsWeb:EmployerApprenticeUrl", $"https://{TestDataValues.EmployerApprenticeUrl}"),
                    new KeyValuePair <string, string>("ReservationsWeb:FindApprenticeshipTrainingUrl", $"https://test"),
                    new KeyValuePair <string, string>("ReservationsWeb:ApprenticeshipFundingRulesUrl", $"https://test")
                }
            };

            var provider = new MemoryConfigurationProvider(configSource);

            return(new ConfigurationRoot(new List <IConfigurationProvider> {
                provider
            }));
        }
示例#24
0
        internal static void Main()
        {
            var configSource = new MemoryConfigurationSource
            {
                InitialData = new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("env", "Development"),
                    new KeyValuePair <string, string>("host", "localhost"),
                    new KeyValuePair <string, string>("port", "9000"),
                }
            };
            var configProvider = new MemoryConfigurationProvider(new MemoryConfigurationSource
            {
                InitialData = new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("env", "Production")
                }
            });
            var configProviders = new List <IConfigurationProvider>
            {
                configSource.Build(null), // like configProvider above
                configProvider
            };
            var configRoot = new ConfigurationRoot(configProviders);

            Console.WriteLine($"{configRoot["env"]}|{configRoot["host"]}|{configRoot["port"]}");
        }
示例#25
0
        public static IConfigurationRoot GenerateConfiguration()
        {
            var configSource = new MemoryConfigurationSource
            {
                InitialData = new[]
                {
                    new KeyValuePair <string, string>("ConfigurationStorageConnectionString", "UseDevelopmentStorage=true;"),
                    new KeyValuePair <string, string>("ConfigNames", "SFA.DAS.FindApprenticeshipTraining.Web"),
                    new KeyValuePair <string, string>("Environment", "DEV"),
                    new KeyValuePair <string, string>("Version", "1.0"),

                    new KeyValuePair <string, string>("FindApprenticeshipTrainingApi:Key", "test"),
                    new KeyValuePair <string, string>("FindApprenticeshipTrainingApi:BaseUrl", "http://localhost:5003/"),
                    new KeyValuePair <string, string>("FindApprenticeshipTrainingApi:PingUrl", "http://localhost:5003/"),
                    new KeyValuePair <string, string>("FindApprenticeshipTrainingWeb:RedisConnectionString", ""),
                    new KeyValuePair <string, string>("FindApprenticeshipTrainingWeb:DataProtectionKeysDatabase", ""),
                    new KeyValuePair <string, string>("FindApprenticeshipTrainingWeb:ZendeskSectionId", "213452345"),
                    new KeyValuePair <string, string>("FindApprenticeshipTrainingWeb:ZendeskSnippetKey", "e0730bdd"),
                    new KeyValuePair <string, string>("FindApprenticeshipTrainingWeb:ZendeskCoBrowsingSnippetKey", "Qec2OgXsUy8")
                }
            };

            var provider = new MemoryConfigurationProvider(configSource);

            return(new ConfigurationRoot(new List <IConfigurationProvider> {
                provider
            }));
        }
        public void SettingValueUpdatesAllConfigurationSources()
        {
            // Arrange
            var dict = new Dictionary <string, string>()
            {
                { "Key1", "Value1" },
                { "Key2", "Value2" }
            };
            var memConfigSrc1 = new MemoryConfigurationSource(dict);
            var memConfigSrc2 = new MemoryConfigurationSource(dict);
            var memConfigSrc3 = new MemoryConfigurationSource(dict);

            var builder = new ConfigurationBuilder();

            builder.Add(memConfigSrc1, load: false);
            builder.Add(memConfigSrc2, load: false);
            builder.Add(memConfigSrc3, load: false);

            var config = builder.Build();

            // Act
            config["Key1"] = "NewValue1";
            config["Key2"] = "NewValue2";

            // Assert
            Assert.Equal("NewValue1", config["Key1"]);
            Assert.Equal("NewValue1", memConfigSrc1.Get("Key1"));
            Assert.Equal("NewValue1", memConfigSrc2.Get("Key1"));
            Assert.Equal("NewValue1", memConfigSrc3.Get("Key1"));
            Assert.Equal("NewValue2", config["Key2"]);
            Assert.Equal("NewValue2", memConfigSrc1.Get("Key2"));
            Assert.Equal("NewValue2", memConfigSrc2.Get("Key2"));
            Assert.Equal("NewValue2", memConfigSrc3.Get("Key2"));
        }
示例#27
0
        private IConfiguration CreateConfigurationForEnvironment(string environmentName)
        {
            IConfiguration configuration = new ConfigurationBuilder()
                                           .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
                                           .AddJsonFile($"appsettings.{environmentName}.json", optional: false, reloadOnChange: false)
                                           .AddEnvironmentVariables()
                                           .Build();

            var connectionStringBuilder =
                new NpgsqlConnectionStringBuilder(configuration.GetValue <string>(ConnectionStringKey))
            {
                Database           = $"db4it--{applicationName}",
                IncludeErrorDetail = true
            };

            var memoryConfigurationSource = new MemoryConfigurationSource
            {
                InitialData = new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>(ConnectionStringKey, connectionStringBuilder.ConnectionString)
                }
            };

            IConfiguration enhancedConfiguration = new ConfigurationBuilder()
                                                   .AddConfiguration(configuration)
                                                   .Add(memoryConfigurationSource)
                                                   .Build();

            return(enhancedConfiguration);
        }
示例#28
0
        private static async Task SetVaultConfig(
            this IConfigurationBuilder builder,
            VaultOptions options,
            string kvp)
        {
            VerifyOptions(options);
            var kvPath = string.IsNullOrWhiteSpace(kvp) ? options.KeyValue?.Path : kvp;

            if (!(options.KeyValue?.Enabled ?? false) && string.IsNullOrWhiteSpace(kvPath))
            {
                return;
            }

            var(client, _) = GetClientAndSettings(options);
            var keyValueService = new KeyValueService(client, options);
            var secret          = await keyValueService.GetAsync(kvPath);

            var parser = new JsonConfigurationParser();
            var data   = parser.Parse(JObject.FromObject(secret));
            var source = new MemoryConfigurationSource {
                InitialData = data
            };

            builder.Add(source);
        }
示例#29
0
        public void ConfigurationToAppConfigurator()
        {
            "原本在 IConfiguration 存放的内容,可以通过 AppConfigurator 创建出来的配置读取到".Test(() =>
            {
                // Arrange
                const string key              = "LindexiIsDoubi";
                const string value            = "doubi";
                var memoryConfigurationSource = new MemoryConfigurationSource()
                {
                    InitialData = new List <KeyValuePair <string, string> >()
                    {
                        new KeyValuePair <string, string>(key, value)
                    }
                };
                IConfigurationProvider configurationProvider = new MemoryConfigurationProvider(memoryConfigurationSource);
                IConfiguration configuration = new ConfigurationRoot(new List <IConfigurationProvider>()
                {
                    configurationProvider
                });

                // Act
                var appConfigurator    = configuration.ToAppConfigurator();
                var configurationValue = appConfigurator.Default[key];

                // Assert
                Assert.IsNotNull(configurationValue);
                Assert.AreEqual(value, configurationValue.ToString());
            });
        }
            public TestThemeExtensionInfo(string name, IFeatureInfo baseTheme)
            {
                var dic1 = new Dictionary <string, string>()
                {
                    { "name", name },
                    { "desciption", name },
                    { "type", "theme" },
                    { "basetheme", baseTheme.Id }
                };

                var memConfigSrc1 = new MemoryConfigurationSource {
                    InitialData = dic1
                };
                var configurationBuilder = new ConfigurationBuilder();

                configurationBuilder.Add(memConfigSrc1);

                Manifest = new ManifestInfo(configurationBuilder.Build(), "theme");

                Features =
                    new List <IFeatureInfo>()
                {
                    { new FeatureInfo(name, name, 0, "", "", this, new string[] { baseTheme.Id }) }
                };

                Id = name;
            }
示例#31
0
            public TestThemeExtensionInfo(string name)
            {
                var dic1 = new Dictionary <string, string>()
                {
                    { "name", name },
                    { "desciption", name },
                    { "type", "theme" },
                };

                var memConfigSrc1 = new MemoryConfigurationSource {
                    InitialData = dic1
                };
                var configurationBuilder = new ConfigurationBuilder();

                configurationBuilder.Add(memConfigSrc1);

                Manifest = new ManifestInfo(new ThemeAttribute());

                var features =
                    new List <IFeatureInfo>()
                {
                    { new FeatureInfo(name, name, 0, "", "", this, new string[0], false) }
                };

                Features = features;

                Id = name;
            }
        public void CanGetConfigurationSection()
        {
            // Arrange
            var dic1 = new Dictionary<string, string>()
                {
                    {"Data:DB1:Connection1", "MemVal1"},
                    {"Data:DB1:Connection2", "MemVal2"}
                };
            var dic2 = new Dictionary<string, string>()
                {
                    {"DataSource:DB2:Connection", "MemVal3"}
                };
            var dic3 = new Dictionary<string, string>()
                {
                    {"Data", "MemVal4"}
                };
            var memConfigSrc1 = new MemoryConfigurationSource(dic1);
            var memConfigSrc2 = new MemoryConfigurationSource(dic2);
            var memConfigSrc3 = new MemoryConfigurationSource(dic3);

            var builder = new ConfigurationBuilder();
            builder.Add(memConfigSrc1, load: false);
            builder.Add(memConfigSrc2, load: false);
            builder.Add(memConfigSrc3, load: false);

            var config = builder.Build();

            string memVal1, memVal2, memVal3, memVal4, memVal5;

            // Act
            var configFocus = config.GetSection("Data");

            memVal1 = configFocus["DB1:Connection1"];
            memVal2 = configFocus["DB1:Connection2"];
            memVal3 = configFocus["DB2:Connection"];
            memVal4 = configFocus["Source:DB2:Connection"];
            memVal5 = configFocus.Value;

            // Assert
            Assert.Equal("MemVal1", memVal1);
            Assert.Equal("MemVal2", memVal2);
            Assert.Equal("MemVal4", memVal5);

            Assert.Equal("MemVal1", configFocus["DB1:Connection1"]);
            Assert.Equal("MemVal2", configFocus["DB1:Connection2"]);
            Assert.Null(configFocus["DB2:Connection"]);
            Assert.Null(configFocus["Source:DB2:Connection"]);
            Assert.Equal("MemVal4", configFocus.Value);
        }
示例#33
0
文件: Program.cs 项目: bigfont/Docs
        public void Main(string[] args)
        {
            var configuration = new Configuration();
            Console.WriteLine("Initial Config Sources: " + configuration.Sources.Count());

            var defaultSettings = new MemoryConfigurationSource();
            defaultSettings.Set("username", "Guest");
            configuration.Add(defaultSettings);
            Console.WriteLine("Added Memory Source. Sources: " + configuration.Sources.Count());

            configuration.AddCommandLine(args);
            Console.WriteLine("Added Command Line Source. Sources: " + configuration.Sources.Count());

            string username = configuration.Get("username");

            Console.WriteLine($"Hello, {username}!");
        }
示例#34
0
        protected override void OnStart(string[] args)
        {
            var configSource = new MemoryConfigurationSource();
            configSource.Add("server.urls", "http://localhost:5000");

            var config = new ConfigurationBuilder(configSource).Build();
            var builder = new WebHostBuilder(_serviceProvider, config);
            builder.UseServer("Microsoft.AspNet.Server.Kestrel");
            builder.UseServices(services => services.AddMvc());
            builder.UseStartup(appBuilder =>
            {
                appBuilder.UseDefaultFiles();
                appBuilder.UseStaticFiles();
                appBuilder.UseMvc();
            });

            _hostingEngine = builder.Build();
            _shutdownServerDisposable = _hostingEngine.Start();
        }
示例#35
0
        public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
        {
            // Setup configuration sources.

            var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
                .AddIniFile("data.ini")
                .AddJsonFile("config.json")
                .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true);

            //Command line: Data:Value=1
            var defaultSettings = new MemoryConfigurationSource();
            defaultSettings.Set("username", "Guest");
            builder.Add(defaultSettings);

            if (env.IsDevelopment())
            {
                // This reads the configuration keys from the secret store.
                // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
                builder.AddUserSecrets();
            }
            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }
 private static IConfiguration SetUpDefaultAssembly(string assemblyName)
 {
     var source = new MemoryConfigurationSource();
     source.Add("defaultAssembly", assemblyName);
     var config = new ConfigurationBuilder();
     config.Add(source);
     return config.Build();
 }
示例#37
0
        public void LoadAndCombineKeyValuePairsFromDifferentConfigurationSources()
        {
            // Arrange
            var dic1 = new Dictionary<string, string>()
                {
                    {"Mem1:KeyInMem1", "ValueInMem1"}
                };
            var dic2 = new Dictionary<string, string>()
                {
                    {"Mem2:KeyInMem2", "ValueInMem2"}
                };
            var dic3 = new Dictionary<string, string>()
                {
                    {"Mem3:KeyInMem3", "ValueInMem3"}
                };
            var memConfigSrc1 = new MemoryConfigurationSource(dic1);
            var memConfigSrc2 = new MemoryConfigurationSource(dic2);
            var memConfigSrc3 = new MemoryConfigurationSource(dic3);

            var config = new Configuration();

            string memVal1, memVal2, memVal3;
            bool memRet1, memRet2, memRet3;

            // Act
            config.AddLoadedSource(memConfigSrc1);
            config.AddLoadedSource(memConfigSrc2);
            config.AddLoadedSource(memConfigSrc3);

            memRet1 = config.TryGet("mem1:keyinmem1", out memVal1);
            memRet2 = config.TryGet("Mem2:KeyInMem2", out memVal2);
            memRet3 = config.TryGet("MEM3:KEYINMEM3", out memVal3);

            // Assert
            Assert.Contains(memConfigSrc1, config.Sources);
            Assert.Contains(memConfigSrc2, config.Sources);
            Assert.Contains(memConfigSrc3, config.Sources);

            Assert.True(memRet1);
            Assert.True(memRet2);
            Assert.True(memRet3);

            Assert.Equal("ValueInMem1", memVal1);
            Assert.Equal("ValueInMem2", memVal2);
            Assert.Equal("ValueInMem3", memVal3);

            Assert.Equal("ValueInMem1", config.Get("mem1:keyinmem1"));
            Assert.Equal("ValueInMem2", config.Get("Mem2:KeyInMem2"));
            Assert.Equal("ValueInMem3", config.Get("MEM3:KEYINMEM3"));
            Assert.Null(config.Get("NotExist"));

            Assert.Equal("ValueInMem1", config["mem1:keyinmem1"]);
            Assert.Equal("ValueInMem2", config["Mem2:KeyInMem2"]);
            Assert.Equal("ValueInMem3", config["MEM3:KEYINMEM3"]);
            Assert.Null(config["NotExist"]);
        }
示例#38
0
        public void NewConfigurationSourceOverridesOldOneWhenKeyIsDuplicated()
        {
            // Arrange
            var dic1 = new Dictionary<string, string>()
                {
                    {"Key1:Key2", "ValueInMem1"}
                };
            var dic2 = new Dictionary<string, string>()
                {
                    {"Key1:Key2", "ValueInMem2"}
                };
            var memConfigSrc1 = new MemoryConfigurationSource(dic1);
            var memConfigSrc2 = new MemoryConfigurationSource(dic2);

            var config = new Configuration();

            // Act
            config.AddLoadedSource(memConfigSrc1);
            config.AddLoadedSource(memConfigSrc2);

            // Assert
            Assert.Equal("ValueInMem2", config.Get("Key1:Key2"));
        }
示例#39
0
        public void SettingValueUpdatesAllConfigurationSources()
        {
            // Arrange
            var dict = new Dictionary<string, string>()
                {
                    {"Key1", "Value1"},
                    {"Key2", "Value2"}
                };
            var memConfigSrc1 = new MemoryConfigurationSource(dict);
            var memConfigSrc2 = new MemoryConfigurationSource(dict);
            var memConfigSrc3 = new MemoryConfigurationSource(dict);

            var config = new Configuration();
            config.AddLoadedSource(memConfigSrc1);
            config.AddLoadedSource(memConfigSrc2);
            config.AddLoadedSource(memConfigSrc3);

            // Act
            config.Set("Key1", "NewValue1");
            config["Key2"] = "NewValue2";

            // Assert
            Assert.Equal("NewValue1", config.Get("Key1"));
            Assert.Equal("NewValue1", memConfigSrc1.Get("Key1"));
            Assert.Equal("NewValue1", memConfigSrc2.Get("Key1"));
            Assert.Equal("NewValue1", memConfigSrc3.Get("Key1"));
            Assert.Equal("NewValue2", config["Key2"]);
            Assert.Equal("NewValue2", memConfigSrc1.Get("Key2"));
            Assert.Equal("NewValue2", memConfigSrc2.Get("Key2"));
            Assert.Equal("NewValue2", memConfigSrc3.Get("Key2"));
        }
示例#40
0
        public void CanGetSubKeys()
        {
            // Arrange
            var dic1 = new Dictionary<string, string>()
                {
                    {"Data:DB1:Connection1", "MemVal1"},
                    {"Data:DB1:Connection2", "MemVal2"}
                };
            var dic2 = new Dictionary<string, string>()
                {
                    {"Data:DB2Connection", "MemVal3"}
                };
            var dic3 = new Dictionary<string, string>()
                {
                    {"DataSource:DB3:Connection", "MemVal4"}
                };
            var memConfigSrc1 = new MemoryConfigurationSource(dic1);
            var memConfigSrc2 = new MemoryConfigurationSource(dic2);
            var memConfigSrc3 = new MemoryConfigurationSource(dic3);

            var config = new Configuration();
            config.AddLoadedSource(memConfigSrc1);
            config.AddLoadedSource(memConfigSrc2);
            config.AddLoadedSource(memConfigSrc3);

            // Act
            var configFocusList = config.GetSubKeys("Data");
            var subKeysSet = configFocusList.ToDictionary(e => e.Key, e => e.Value);

            // Assert
            Assert.Equal(2, configFocusList.Count());
            Assert.Equal("MemVal1", subKeysSet["DB1"].Get("Connection1"));
            Assert.Equal("MemVal2", subKeysSet["DB1"].Get("Connection2"));
            Assert.Equal("MemVal3", subKeysSet["DB2Connection"].Get(null));
            Assert.False(subKeysSet.ContainsKey("DB3"));
            Assert.False(subKeysSet.ContainsKey("Source:DB3"));
        }
示例#41
0
        public void CanGetConfigurationSections()
        {
            // Arrange
            var dic1 = new Dictionary<string, string>()
                {
                    {"Data:DB1:Connection1", "MemVal1"},
                    {"Data:DB1:Connection2", "MemVal2"}
                };
            var dic2 = new Dictionary<string, string>()
                {
                    {"Data:DB2Connection", "MemVal3"}
                };
            var dic3 = new Dictionary<string, string>()
                {
                    {"DataSource:DB3:Connection", "MemVal4"}
                };
            var memConfigSrc1 = new MemoryConfigurationSource(dic1);
            var memConfigSrc2 = new MemoryConfigurationSource(dic2);
            var memConfigSrc3 = new MemoryConfigurationSource(dic3);

            var builder = new ConfigurationBuilder();
            builder.Add(memConfigSrc1, load: false);
            builder.Add(memConfigSrc2, load: false);
            builder.Add(memConfigSrc3, load: false);

            var config = builder.Build();

            // Act
            var configFocusList = config.GetConfigurationSections("Data");
            var configurationSectionsSet = configFocusList.ToDictionary(e => e.Key, e => e.Value);

            // Assert
            Assert.Equal(2, configFocusList.Count());
            Assert.Equal("MemVal1", configurationSectionsSet["DB1"].Get("Connection1"));
            Assert.Equal("MemVal2", configurationSectionsSet["DB1"].Get("Connection2"));
            Assert.Equal("MemVal3", configurationSectionsSet["DB2Connection"].Get(null));
            Assert.False(configurationSectionsSet.ContainsKey("DB3"));
            Assert.False(configurationSectionsSet.ContainsKey("Source:DB3"));
        }
        public void CanGetConfigurationSections()
        {
            // Arrange
            var dic1 = new Dictionary<string, string>()
                {
                    {"Data:DB1:Connection1", "MemVal1"},
                    {"Data:DB1:Connection2", "MemVal2"}
                };
            var dic2 = new Dictionary<string, string>()
                {
                    {"Data:DB2Connection", "MemVal3"}
                };
            var dic3 = new Dictionary<string, string>()
                {
                    {"DataSource:DB3:Connection", "MemVal4"}
                };
            var memConfigSrc1 = new MemoryConfigurationSource(dic1);
            var memConfigSrc2 = new MemoryConfigurationSource(dic2);
            var memConfigSrc3 = new MemoryConfigurationSource(dic3);

            var builder = new ConfigurationBuilder();
            builder.Add(memConfigSrc1, load: false);
            builder.Add(memConfigSrc2, load: false);
            builder.Add(memConfigSrc3, load: false);

            var config = builder.Build();

            // Act
            var configSections = config.GetSection("Data").GetChildren().ToList();

            // Assert
            Assert.Equal(2, configSections.Count());
            Assert.Equal("MemVal1", configSections.FirstOrDefault(c => c.Key == "Data:DB1")["Connection1"]);
            Assert.Equal("MemVal2", configSections.FirstOrDefault(c => c.Key == "Data:DB1")["Connection2"]);
            Assert.Equal("MemVal3", configSections.FirstOrDefault(c => c.Key == "Data:DB2Connection").Value);
            Assert.False(configSections.Exists(c => c.Key == "Data:DB3"));
            Assert.False(configSections.Exists(c => c.Key == "Source:DB3"));
        }
示例#43
0
        public void CanIterateAfterCastedToIEnumerable()
        {
            // Arrange
            var dict = new Dictionary<string, string>()
                {
                    {"Mem:KeyInMem", "MemVal"}
                };
            var memConfigSrc1 = new MemoryConfigurationSource(dict);
            var memConfigSrc2 = new MemoryConfigurationSource(dict);
            var memConfigSrc3 = new MemoryConfigurationSource(dict);

            var srcSet = new HashSet<IConfigurationSource>()
                {
                    memConfigSrc1,
                    memConfigSrc2,
                    memConfigSrc3
                };

            var config = new Configuration();

            // Act
            config.AddLoadedSource(memConfigSrc1);
            config.AddLoadedSource(memConfigSrc2);
            config.AddLoadedSource(memConfigSrc3);

            var enumerable = config as IEnumerable;

            // Assert
            var enumerator = config.Sources.GetEnumerator();
            int srcCount = 0;
            while (enumerator.MoveNext())
            {
                Assert.Contains(enumerator.Current, srcSet);
                ++srcCount;
            }

            Assert.Equal(3, srcCount);
        }
        public void SettingValueUpdatesAllConfigurationSources()
        {
            // Arrange
            var dict = new Dictionary<string, string>()
                {
                    {"Key1", "Value1"},
                    {"Key2", "Value2"}
                };
            var memConfigSrc1 = new MemoryConfigurationSource(dict);
            var memConfigSrc2 = new MemoryConfigurationSource(dict);
            var memConfigSrc3 = new MemoryConfigurationSource(dict);

            var builder = new ConfigurationBuilder();

            builder.Add(memConfigSrc1, load: false);
            builder.Add(memConfigSrc2, load: false);
            builder.Add(memConfigSrc3, load: false);

            var config = builder.Build();

            // Act
            config["Key1"] =  "NewValue1";
            config["Key2"] = "NewValue2";

            // Assert
            Assert.Equal("NewValue1", config["Key1"]);
            Assert.Equal("NewValue1", memConfigSrc1.Get("Key1"));
            Assert.Equal("NewValue1", memConfigSrc2.Get("Key1"));
            Assert.Equal("NewValue1", memConfigSrc3.Get("Key1"));
            Assert.Equal("NewValue2", config["Key2"]);
            Assert.Equal("NewValue2", memConfigSrc1.Get("Key2"));
            Assert.Equal("NewValue2", memConfigSrc2.Get("Key2"));
            Assert.Equal("NewValue2", memConfigSrc3.Get("Key2"));
        }
        public void NewConfigurationSourceOverridesOldOneWhenKeyIsDuplicated()
        {
            // Arrange
            var dic1 = new Dictionary<string, string>()
                {
                    {"Key1:Key2", "ValueInMem1"}
                };
            var dic2 = new Dictionary<string, string>()
                {
                    {"Key1:Key2", "ValueInMem2"}
                };
            var memConfigSrc1 = new MemoryConfigurationSource(dic1);
            var memConfigSrc2 = new MemoryConfigurationSource(dic2);

            var builder = new ConfigurationBuilder();

            // Act
            builder.Add(memConfigSrc1, load: false);
            builder.Add(memConfigSrc2, load: false);

            var config = builder.Build();

            // Assert
            Assert.Equal("ValueInMem2", config["Key1:Key2"]);
        }
        private BackTelemetryChannel Start(string assemblyName)
        {
            var customConfig = new MemoryConfigurationSource();
            customConfig.Set("server.urls", this.BaseHost);
            var configBuilder = new ConfigurationBuilder();
            configBuilder.Add(customConfig);
            var config = configBuilder.Build();

            var services = new ServiceCollection();
            services.AddTransient<IApplicationEnvironment, ApplicationEnvironment>();
            var serviceProvider = services.BuildServiceProvider();

            var engine = CreateBuilder(config)
                .UseServer("Microsoft.AspNet.Server.WebListener")
                .UseStartup(assemblyName)
                .UseEnvironment("Production")
                .Build();
            this.hostingEngine = engine.Start();

            return (BackTelemetryChannel)engine.ApplicationServices.GetService<ITelemetryChannel>();
        }
        public void LoadAndCombineKeyValuePairsFromDifferentConfigurationSources()
        {
            // Arrange
            var dic1 = new Dictionary<string, string>()
                {
                    {"Mem1:KeyInMem1", "ValueInMem1"}
                };
            var dic2 = new Dictionary<string, string>()
                {
                    {"Mem2:KeyInMem2", "ValueInMem2"}
                };
            var dic3 = new Dictionary<string, string>()
                {
                    {"Mem3:KeyInMem3", "ValueInMem3"}
                };
            var memConfigSrc1 = new MemoryConfigurationSource(dic1);
            var memConfigSrc2 = new MemoryConfigurationSource(dic2);
            var memConfigSrc3 = new MemoryConfigurationSource(dic3);

            var builder = new ConfigurationBuilder();

            string memVal1, memVal2, memVal3;
            bool memRet1, memRet2, memRet3;

            // Act
            builder.Add(memConfigSrc1, load: false);
            builder.Add(memConfigSrc2, load: false);
            builder.Add(memConfigSrc3, load: false);

            var config = builder.Build();

            memVal1 = config["mem1:keyinmem1"];
            memVal2 = config["Mem2:KeyInMem2"];
            memVal3 = config["MEM3:KEYINMEM3"];

            // Assert
            Assert.Contains(memConfigSrc1, builder.Sources);
            Assert.Contains(memConfigSrc2, builder.Sources);
            Assert.Contains(memConfigSrc3, builder.Sources);

            Assert.Equal("ValueInMem1", memVal1);
            Assert.Equal("ValueInMem2", memVal2);
            Assert.Equal("ValueInMem3", memVal3);

            Assert.Equal("ValueInMem1", config["mem1:keyinmem1"]);
            Assert.Equal("ValueInMem2", config["Mem2:KeyInMem2"]);
            Assert.Equal("ValueInMem3", config["MEM3:KEYINMEM3"]);
            Assert.Null(config["NotExist"]);
        }
        public void CanIterateWithGenericEnumerator()
        {
            // Arrange
            var dict = new Dictionary<string, string>()
                {
                    {"Mem:KeyInMem", "MemVal"}
                };
            var memConfigSrc1 = new MemoryConfigurationSource(dict);
            var memConfigSrc2 = new MemoryConfigurationSource(dict);
            var memConfigSrc3 = new MemoryConfigurationSource(dict);

            var srcSet = new HashSet<IConfigurationSource>()
                {
                    memConfigSrc1,
                    memConfigSrc2,
                    memConfigSrc3
                };

            var builder = new ConfigurationBuilder();

            // Act
            builder.Add(memConfigSrc1, load: false);
            builder.Add(memConfigSrc2, load: false);
            builder.Add(memConfigSrc3, load: false);

            var config = builder.Build();

            // Assert
            var enumerator = builder.Sources.GetEnumerator();
            int srcCount = 0;
            while (enumerator.MoveNext())
            {
                Assert.Contains(enumerator.Current, srcSet);
                ++srcCount;
            }

            Assert.Equal(3, srcCount);
        }