private static AppSettingsBuilder AddUserSettings(this AppSettingsBuilder builder, string?basePath)
        {
            if (string.IsNullOrWhiteSpace(basePath))
            {
                return(builder);
            }

            return(builder.Add(new UserJsonConfiguration(basePath)));
        }
        public static MultiSourceKeyValueConfiguration InitializeConfiguration(
            [NotNull] Func <string, string> basePath,
            ILogger logger)
        {
            if (basePath == null)
            {
                throw new ArgumentNullException(nameof(basePath));
            }

            string environmentBasedSettingsPath =
                Environment.GetEnvironmentVariable(Configuration.ConfigurationConstants.JsonSettingsFile);

            string environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";

            AppSettingsBuilder appSettingsBuilder = KeyValueConfigurationManager
                                                    .Add(new ReflectionKeyValueConfiguration(typeof(ConfigurationInitialization).Assembly))
                                                    .Add(new JsonKeyValueConfiguration(basePath("settings.json"), false))
                                                    .Add(new JsonKeyValueConfiguration(basePath($"settings.{environmentName}.json"), false))
                                                    .Add(new JsonKeyValueConfiguration(basePath($"settings.{Environment.MachineName}.json"), false));

            if (environmentBasedSettingsPath.HasValue() && File.Exists(environmentBasedSettingsPath))
            {
                appSettingsBuilder =
                    appSettingsBuilder.Add(new JsonKeyValueConfiguration(environmentBasedSettingsPath,
                                                                         true));

                logger.Information("Added environment based configuration from key '{Key}', file '{File}'", Configuration.ConfigurationConstants.JsonSettingsFile, environmentBasedSettingsPath);
            }

            MultiSourceKeyValueConfiguration multiSourceKeyValueConfiguration = appSettingsBuilder
                                                                                .Add(new EnvironmentVariableKeyValueConfigurationSource())
                                                                                .Add(new UserConfiguration())
                                                                                .DecorateWith(new ExpandKeyValueConfigurationDecorator())
                                                                                .Build();

            logger.Information("Configuration done using chain {Chain}",
                               multiSourceKeyValueConfiguration.SourceChain);

            return(multiSourceKeyValueConfiguration);
        }
        public static AppSettingsBuilder AddEnvironmentVariables(
            this AppSettingsBuilder builder,
            IReadOnlyDictionary <string, string> environmentVariables)
        {
            var nameValueCollection = new NameValueCollection();

            foreach (var environmentVariable in environmentVariables)
            {
                nameValueCollection.Add(environmentVariable.Key, environmentVariable.Value);
            }

            return(builder.Add(new InMemoryKeyValueConfiguration(nameValueCollection)));
        }
        public static AppSettingsBuilder AddCommandLineArgsSettings(
            this AppSettingsBuilder builder,
            IEnumerable <string> args)
        {
            if (args is null)
            {
                return(builder);
            }

            var inMemoryKeyValueConfiguration = args.ToKeyValueConfiguration();

            return(builder.Add(inMemoryKeyValueConfiguration));
        }
        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));
        }
Example #6
0
        public static AppSettingsBuilder AddUserSettings([NotNull] this AppSettingsBuilder builder, string basePath)
        {
            if (builder is null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (string.IsNullOrWhiteSpace(basePath))
            {
                return(builder);
            }

            return(builder.Add(new UserJsonConfiguration(basePath)));
        }
Example #7
0
        public static AppSettingsBuilder AddReflectionSettings(
            [NotNull] this AppSettingsBuilder appSettingsBuilder,
            IEnumerable <Assembly>?scanAssemblies,
            Action <Exception>?exceptionHandler = null)
        {
            if (appSettingsBuilder is null)
            {
                throw new ArgumentNullException(nameof(appSettingsBuilder));
            }

            if (scanAssemblies is null)
            {
                return(appSettingsBuilder);
            }

            foreach (var currentAssembly in scanAssemblies.OrderBy(assembly => assembly.FullName))
            {
                if (currentAssembly.IsDynamic)
                {
                    continue;
                }

                try
                {
                    appSettingsBuilder =
                        appSettingsBuilder.Add(
                            new ReflectionKeyValueConfiguration(currentAssembly));
                }
                catch (FileLoadException ex)
                {
                    exceptionHandler?.Invoke(ex);
                }
                catch (FileNotFoundException ex)
                {
                    exceptionHandler?.Invoke(ex);
                }
                catch (TypeLoadException ex)
                {
                    exceptionHandler?.Invoke(ex);
                }
                catch (ReflectionTypeLoadException ex)
                {
                    exceptionHandler?.Invoke(ex);
                }
            }

            return(appSettingsBuilder);
        }
 public static AppSettingsBuilder Add(this AppSettingsBuilder builder, AppSettingsBuilder next) =>
 builder.Add(next.KeyValueConfiguration);
        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);
        }