/// <summary>
        /// Adds a INI 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 relative 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 AddIniFile(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(Resources.Error_InvalidFilePath, nameof(path));
            }

            if (provider == null && Path.IsPathRooted(path))
            {
                provider = new PhysicalFileProvider(Path.GetDirectoryName(path));
                path     = Path.GetFileName(path);
            }
            var source = new IniConfigurationSource
            {
                FileProvider   = provider,
                Path           = path,
                Optional       = optional,
                ReloadOnChange = reloadOnChange
            };

            builder.Add(source);
            return(builder);
        }
Beispiel #2
0
        public Config(string configFilePath)
        {
            var fileProvider = new PhysicalFileProvider(Path.GetDirectoryName(configFilePath));
            var configSource = new IniConfigurationSource
            {
                Path = Path.GetFileName(configFilePath), FileProvider = fileProvider
            };

            var iniReader = new IniConfigurationProvider(configSource);

            iniReader.Load();

            iniReader.TryGet(FormatIniPath(Section.General, GeneralKeys.Frequency), out var frequency);
            iniReader.TryGet(FormatIniPath(Section.General, GeneralKeys.ApiUrl), out var url);

            FrequencyInSeconds = int.Parse(frequency);
            ApiUrl             = url;

            Components = new List <Component>();

            foreach (var componentKey in iniReader.GetChildKeys(new string[0], Section.Components))
            {
                iniReader.TryGet(FormatIniPath(Section.Components, componentKey), out var dir);
                var patternExists = iniReader.TryGet(FormatIniPath(Section.FilePatterns, componentKey), out var pattern);
                pattern = patternExists ? pattern : "*";

                Components.Add(new Component(componentKey, dir, pattern));
            }
        }
        public void IniConfiguration_Does_Not_Throw_On_Optional_Configuration()
        {
            var configSource = new IniConfigurationSource("NotExistingConfig.ini", optional: true);

            configSource.Load();
            Assert.Throws <InvalidOperationException>(() => configSource.Get("key"));
        }
        private void LoadConfigFile(string filename)
        {
            StreamReader sr = new StreamReader(filename);

            IniConfigurationSource iniSrouce = new IniConfigurationSource();

            iniSrouce.Path = filename;

            IniConfigurationProvider iniFile = new IniConfigurationProvider(iniSrouce);

            iniFile.Load(sr.BaseStream);

            string value;

            iniFile.TryGet("General:LunchMenuURL", out value);
            LunchMenuUrl = value;

            iniFile.TryGet("Database:Server", out value);
            DbServer = value;

            iniFile.TryGet("Database:User", out value);
            DbUser = value;

            iniFile.TryGet("Database:Password", out value);
            DbPass = value;

            iniFile.TryGet("Database:Name", out value);
            DbName = value;
        }
        private void LoadConfigFile(string filename)
        {
            StreamReader sr = new StreamReader(filename);

            IniConfigurationSource iniSrouce = new IniConfigurationSource();

            iniSrouce.Path = filename;

            IniConfigurationProvider iniFile = new IniConfigurationProvider(iniSrouce);

            iniFile.Load(sr.BaseStream);

            string value;

            iniFile.TryGet("Website:homeurl", out value);
            WebsiteHomeUrl = value;

            iniFile.TryGet("Website:url", out value);
            WebsiteUrl = value;

            iniFile.TryGet("Website:nodeTitle", out value);
            WebsiteNodeTitle = value;

            iniFile.TryGet("Website:nodePublishedAt", out value);
            WebsiteNodePublishedAt = value;

            iniFile.TryGet("Website:nodeMessageBody", out value);
            WebsiteNodeMessageBody = value;

            iniFile.TryGet("Email:adminEmail", out value);
            EmailAdminEmail = value;

            iniFile.TryGet("Email:recipentsSourceType", out value);
            EmailRecipentsSourceType = value;

            iniFile.TryGet("Email:recipentsSource", out value);
            EmailRecipentsSource = value;

            iniFile.TryGet("Email:fromName", out value);
            EmailFromName = value;

            iniFile.TryGet("Email:fromEmail", out value);
            EmailFromEmail = value;

            iniFile.TryGet("SmtpClient:host", out value);
            SmtpClientHost = value;

            iniFile.TryGet("SmtpClient:port", out value);
            SmtpClientPort = int.Parse(value);

            iniFile.TryGet("SmtpClient:usessl", out value);
            SmtpClientUseSsl = bool.Parse(value);

            iniFile.TryGet("SmtpClient:username", out value);
            SmtpClientUsername = value;

            iniFile.TryGet("SmtpClient:password", out value);
            SmtpClientPassword = value;
        }
Beispiel #6
0
        public void CanGetValueContainingEqualSign()
        {
            var source = new IniConfigurationSource(Resources.IniTestCaseMultipleEqualSigns);

            var actualValue = source.Sections["aSection"].Get <string>("a_key");

            Assert.Equal("Some text with = in it", actualValue);
        }
        public void CanGetValueContainingEqualSign()
        {
            var source = new IniConfigurationSource(Resources.IniTestCaseMultipleEqualSigns);

            var actualValue = source.Sections["aSection"].Get<string>("a_key");

            Assert.Equal("Some text with = in it", actualValue);
        }
        public void LoadMethodCanHandleEmptyValue()
        {
            var ini          = @"DefaultKey=";
            var iniConfigSrc = new IniConfigurationSource(TestStreamHelpers.ArbitraryFilePath);

            iniConfigSrc.Load(TestStreamHelpers.StringToStream(ini));

            Assert.Equal(string.Empty, iniConfigSrc.Get("DefaultKey"));
        }
        public static IniConfigurationProvider LoadSettings()
        {
            IniConfigurationSource source = new IniConfigurationSource();

            source.Path = "Settings.ini";
            IniConfigurationProvider settings = (IniConfigurationProvider)source.Build(new ConfigurationBuilder());

            settings.Load();
            return(settings);
        }
        public void CanLoadFromFile()
        {
            var source = new IniConfigurationSource( Resources.IniTestCases ) {FileName = "CanLoadFromFile.ini"};
            source.Save();

            var sourceFromFile = IniConfigurationSource.FromFile( "CanLoadFromFile.ini" );
            string sourceString = source.ToString();
            string sourceFromFileString = sourceFromFile.ToString();
            Assert.Equal( sourceString, sourceFromFileString );
        }
        public void DoubleQuoteIsPartOfValueIfNotPaired()
        {
            var ini = "[ConnectionString]\n" +
                      "DefaultConnection=\"TestConnectionString\n" +
                      "Provider=SqlClient\"";
            var iniConfigSrc = new IniConfigurationSource(TestStreamHelpers.ArbitraryFilePath);

            iniConfigSrc.Load(TestStreamHelpers.StringToStream(ini));

            Assert.Equal("\"TestConnectionString", iniConfigSrc.Get("ConnectionString:DefaultConnection"));
            Assert.Equal("SqlClient\"", iniConfigSrc.Get("ConnectionString:Provider"));
        }
        public void DoubleQuoteIsPartOfValueIfAppearInTheMiddleOfValue()
        {
            var ini = "[ConnectionString]\n" +
                      "DefaultConnection=Test\"Connection\"String\n" +
                      "Provider=Sql\"Client";
            var iniConfigSrc = new IniConfigurationSource(TestStreamHelpers.ArbitraryFilePath);

            iniConfigSrc.Load(TestStreamHelpers.StringToStream(ini));

            Assert.Equal("Test\"Connection\"String", iniConfigSrc.Get("ConnectionString:DefaultConnection"));
            Assert.Equal("Sql\"Client", iniConfigSrc.Get("ConnectionString:Provider"));
        }
        public void DoubleQuoteIsPartOfValueIfNotPaired()
        {
            var ini = "[ConnectionString]\n" +
                      "DefaultConnection=\"TestConnectionString\n" +
                      "Provider=SqlClient\"";
            var iniConfigSrc = new IniConfigurationSource(TestStreamHelpers.ArbitraryFilePath);

            iniConfigSrc.Load(TestStreamHelpers.StringToStream(ini));

            Assert.Equal("\"TestConnectionString", iniConfigSrc.Get("ConnectionString:DefaultConnection"));
            Assert.Equal("SqlClient\"", iniConfigSrc.Get("ConnectionString:Provider"));
        }
        public void ThrowExceptionWhenFoundInvalidLine()
        {
            var ini          = @"
ConnectionString
            ";
            var iniConfigSrc = new IniConfigurationSource(TestStreamHelpers.ArbitraryFilePath);
            var expectedMsg  = Resources.FormatError_UnrecognizedLineFormat("ConnectionString");

            var exception = Assert.Throws <FormatException>(() => iniConfigSrc.Load(TestStreamHelpers.StringToStream(ini)));

            Assert.Equal(expectedMsg, exception.Message);
        }
        public void DoubleQuoteIsPartOfValueIfAppearInTheMiddleOfValue()
        {
            var ini = "[ConnectionString]\n" +
                      "DefaultConnection=Test\"Connection\"String\n" +
                      "Provider=Sql\"Client";
            var iniConfigSrc = new IniConfigurationSource(TestStreamHelpers.ArbitraryFilePath);

            iniConfigSrc.Load(TestStreamHelpers.StringToStream(ini));

            Assert.Equal("Test\"Connection\"String", iniConfigSrc.Get("ConnectionString:DefaultConnection"));
            Assert.Equal("Sql\"Client", iniConfigSrc.Get("ConnectionString:Provider"));
        }
Beispiel #16
0
        public void CanLoadFromFile()
        {
            var source = new IniConfigurationSource(Resources.IniTestCases)
            {
                FileName = "CanLoadFromFile.ini"
            };

            source.Save();

            var    sourceFromFile       = IniConfigurationSource.FromFile("CanLoadFromFile.ini");
            string sourceString         = source.ToString();
            string sourceFromFileString = sourceFromFile.ToString();

            Assert.Equal(sourceString, sourceFromFileString);
        }
 public void IniConfiguration_Throws_On_Missing_Configuration_File()
 {
     var configSource = new IniConfigurationSource("NotExistingConfig.ini", optional: false);
     Assert.Throws<FileNotFoundException>(() =>
     {
         try
         {
             configSource.Load();
         }
         catch (FileNotFoundException exception)
         {
             Assert.Equal(Resources.FormatError_FileNotFound("NotExistingConfig.ini"), exception.Message);
             throw;
         }
     });
 }
Beispiel #18
0
        // mix it up.
        private static IConfigurationSource LoadConfigurationSources4()
        {
            string baseDirectory       = AppDomain.CurrentDomain.BaseDirectory;
            string defaultSettingsFile = Path.Combine(baseDirectory, "default.xml");
            string customSettingsFile  = Path.Combine(baseDirectory, "custom.ini");
            string devSettingsFile     = Path.Combine(baseDirectory, "dev.config");

            IConfigurationSource defaultSettings = XmlConfigurationSource.FromFile(defaultSettingsFile);
            IConfigurationSource customSettings  = IniConfigurationSource.FromFile(customSettingsFile);
            IConfigurationSource devSettings     = DotNetConfigurationSource.FromFile(devSettingsFile);

            defaultSettings.Merge(customSettings);
            defaultSettings.Merge(devSettings);
            defaultSettings.ExpandKeyValues();
            return(defaultSettings);
        }
        public void LoadKeyValuePairsFromValidIniFileWithoutSectionHeader()
        {
            var ini          = @"
            DefaultConnection:ConnectionString=TestConnectionString
            DefaultConnection:Provider=SqlClient
            Data:Inventory:ConnectionString=AnotherTestConnectionString
            Data:Inventory:Provider=MySql
            ";
            var iniConfigSrc = new IniConfigurationSource(TestStreamHelpers.ArbitraryFilePath);

            iniConfigSrc.Load(TestStreamHelpers.StringToStream(ini));

            Assert.Equal("TestConnectionString", iniConfigSrc.Get("DefaultConnection:ConnectionString"));
            Assert.Equal("SqlClient", iniConfigSrc.Get("DefaultConnection:Provider"));
            Assert.Equal("AnotherTestConnectionString", iniConfigSrc.Get("Data:Inventory:ConnectionString"));
            Assert.Equal("MySql", iniConfigSrc.Get("Data:Inventory:Provider"));
        }
        public void LoadKeyValuePairsFromValidIniFile()
        {
            var ini = @"[DefaultConnection]
            ConnectionString=TestConnectionString
            Provider=SqlClient
            [Data:Inventory]
            ConnectionString=AnotherTestConnectionString
            SubHeader:Provider=MySql";
            var iniConfigSrc = new IniConfigurationSource(TestStreamHelpers.ArbitraryFilePath);

            iniConfigSrc.Load(TestStreamHelpers.StringToStream(ini));

            Assert.Equal("TestConnectionString", iniConfigSrc.Get("defaultconnection:ConnectionString"));
            Assert.Equal("SqlClient", iniConfigSrc.Get("DEFAULTCONNECTION:PROVIDER"));
            Assert.Equal("AnotherTestConnectionString", iniConfigSrc.Get("Data:Inventory:CONNECTIONSTRING"));
            Assert.Equal("MySql", iniConfigSrc.Get("Data:Inventory:SubHeader:Provider"));
        }
        public void IniConfiguration_Throws_On_Missing_Configuration_File()
        {
            var configSource = new IniConfigurationSource("NotExistingConfig.ini", optional: false);

            Assert.Throws <FileNotFoundException>(() =>
            {
                try
                {
                    configSource.Load();
                }
                catch (FileNotFoundException exception)
                {
                    Assert.Equal(Resources.FormatError_FileNotFound("NotExistingConfig.ini"), exception.Message);
                    throw;
                }
            });
        }
        public void ThrowExceptionWhenKeyIsDuplicated()
        {
            var ini          = @"
            [Data:DefaultConnection]
            ConnectionString=TestConnectionString
            Provider=SqlClient
            [Data]
            DefaultConnection:ConnectionString=AnotherTestConnectionString
            Provider=MySql
            ";
            var iniConfigSrc = new IniConfigurationSource(TestStreamHelpers.ArbitraryFilePath);
            var expectedMsg  = Resources.FormatError_KeyIsDuplicated("Data:DefaultConnection:ConnectionString");

            var exception = Assert.Throws <FormatException>(() => iniConfigSrc.Load(TestStreamHelpers.StringToStream(ini)));

            Assert.Equal(expectedMsg, exception.Message);
        }
        public void LoadKeyValuePairsFromValidIniFile()
        {
            var ini          = @"[DefaultConnection]
ConnectionString=TestConnectionString
Provider=SqlClient
[Data:Inventory]
ConnectionString=AnotherTestConnectionString
SubHeader:Provider=MySql";
            var iniConfigSrc = new IniConfigurationSource(TestStreamHelpers.ArbitraryFilePath);

            iniConfigSrc.Load(TestStreamHelpers.StringToStream(ini));

            Assert.Equal("TestConnectionString", iniConfigSrc.Get("defaultconnection:ConnectionString"));
            Assert.Equal("SqlClient", iniConfigSrc.Get("DEFAULTCONNECTION:PROVIDER"));
            Assert.Equal("AnotherTestConnectionString", iniConfigSrc.Get("Data:Inventory:CONNECTIONSTRING"));
            Assert.Equal("MySql", iniConfigSrc.Get("Data:Inventory:SubHeader:Provider"));
        }
        public void LoadKeyValuePairsFromValidIniFileWithQuotedValues()
        {
            var ini = "[DefaultConnection]\n" +
                      "ConnectionString=\"TestConnectionString\"\n" +
                      "Provider=\"SqlClient\"\n" +
                      "[Data:Inventory]\n" +
                      "ConnectionString=\"AnotherTestConnectionString\"\n" +
                      "Provider=\"MySql\"";
            var iniConfigSrc = new IniConfigurationSource(TestStreamHelpers.ArbitraryFilePath);

            iniConfigSrc.Load(TestStreamHelpers.StringToStream(ini));

            Assert.Equal("TestConnectionString", iniConfigSrc.Get("DefaultConnection:ConnectionString"));
            Assert.Equal("SqlClient", iniConfigSrc.Get("DefaultConnection:Provider"));
            Assert.Equal("AnotherTestConnectionString", iniConfigSrc.Get("Data:Inventory:ConnectionString"));
            Assert.Equal("MySql", iniConfigSrc.Get("Data:Inventory:Provider"));
        }
Beispiel #25
0
        /// <summary>
        /// Adds a INI configuration source to <paramref name="builder"/>.
        /// </summary>
        /// <param name="builder">The <see cref="IConfigurationBuilder"/> to add to.</param>
        /// <param name="configureSource">Configures the <see cref="IniConfigurationSource"/> to add.</param>
        /// <returns>The <see cref="IConfigurationBuilder"/>.</returns>
        public static IConfigurationBuilder AddIniFile(
            this IConfigurationBuilder builder,
            Action <IniConfigurationSource> configureSource)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            if (configureSource == null)
            {
                throw new ArgumentNullException(nameof(configureSource));
            }

            var source = new IniConfigurationSource();

            configureSource(source);
            builder.Add(source);
            return(builder);
        }
        public void SupportAndIgnoreComments()
        {
            var ini          = @"
            ; Comments
            [DefaultConnection]
            # Comments
            ConnectionString=TestConnectionString
            / Comments
            Provider=SqlClient
            [Data:Inventory]
            ConnectionString=AnotherTestConnectionString
            Provider=MySql
            ";
            var iniConfigSrc = new IniConfigurationSource(TestStreamHelpers.ArbitraryFilePath);

            iniConfigSrc.Load(TestStreamHelpers.StringToStream(ini));

            Assert.Equal("TestConnectionString", iniConfigSrc.Get("DefaultConnection:ConnectionString"));
            Assert.Equal("SqlClient", iniConfigSrc.Get("DefaultConnection:Provider"));
            Assert.Equal("AnotherTestConnectionString", iniConfigSrc.Get("Data:Inventory:ConnectionString"));
            Assert.Equal("MySql", iniConfigSrc.Get("Data:Inventory:Provider"));
        }
Beispiel #27
0
        public void CanProcessValidIniFile()
        {
            var source = new IniConfigurationSource(Resources.IniTestCases);
            List <IConfigurationSection> sections = source.Sections.Values.ToList();

            Assert.Equal(5, sections.Count);
            Assert.Equal("owner", sections[0].Name);
            Assert.Equal(2, sections[0].Count);
            Assert.Equal(sections[0].Get <string>("name"), "John Doe");
            Assert.Equal(sections[0].Get <string>("organization"), "Acme Products");

            Assert.Equal("database", sections[1].Name);
            Assert.Equal(3, sections[1].Count);
            Assert.Equal(sections[1].Get <string>("server"), "192.0.2.42");
            Assert.Equal(sections[1].Get <string>("port"), "143");
            Assert.Equal(sections[1].Get <string>("file"), "\"acme payroll.dat\"");

            Assert.Equal("Empty", sections[2].Name);
            Assert.Equal(1, sections[2].Count);
            Assert.Equal(sections[2].Get <string>("MyEmptyValue"), "");

            Assert.Equal("Completely Empty Section", sections[3].Name);
            Assert.Equal(0, sections[3].Count);

            Assert.Equal("NonEmptyAfterCompletelyEmpty", sections[4].Name);
            Assert.Equal(1, sections[4].Count);
            Assert.Equal(sections[4].Get <string>("mykey"), "myval  akdk");

            foreach (IConfigurationSection section in source.Sections.Values)
            {
                foreach (KeyValuePair <string, string> pair in section)
                {
                    Console.WriteLine(pair.Key + ", " + pair.Value);
                }
            }
        }
        public void CanProcessValidIniFileWithSingleLineComments()
        {
            var source = new IniConfigurationSource(Resources.IniTestCases, true);
            List<IConfigurationSection> sections = source.Sections.Values.ToList();

            Assert.Equal(5, sections.Count);
            Assert.Equal("owner", sections[0].Name);
            Assert.Equal(2, sections[0].Count);
            Assert.Equal(sections[0].Get<string>("name"), "John Doe");
            Assert.Equal(sections[0].Get<string>("organization"), "Acme Products");

            Assert.Equal("database", sections[1].Name);
            Assert.Equal(3, sections[1].Count);
            Assert.Equal(sections[1].Get<string>("server"), "192.0.2.42     ; use IP address in case network name resolution is not working");
            Assert.Equal(sections[1].Get<string>("port"), "143");
            Assert.Equal(sections[1].Get<string>("file"), "\"acme payroll.dat\"");

            Assert.Equal("Empty", sections[2].Name);
            Assert.Equal(1, sections[2].Count);
            Assert.Equal(sections[2].Get<string>("MyEmptyValue"), "");

            Assert.Equal("Completely Empty Section", sections[3].Name);
            Assert.Equal(0, sections[3].Count);

            Assert.Equal("NonEmptyAfterCompletelyEmpty", sections[4].Name);
            Assert.Equal(1, sections[4].Count);
            Assert.Equal(sections[4].Get<string>("mykey"), "myval  akdk     ;");

            foreach (IConfigurationSection section in source.Sections.Values)
            {
                foreach (KeyValuePair<string, string> pair in section)
                {
                    Console.WriteLine(pair.Key + ", " + pair.Value);
                }
            }
        }
Beispiel #29
0
        private static IConfigurationSource GetSource(string fileName)
        {
            IConfigurationSource source;

            switch (Extension)
            {
            case ".ini":
                source = IniConfigurationSource.FromFile(fileName);
                break;

            case ".xml":
                source = XmlConfigurationSource.FromFile(fileName);
                break;

            case ".config":
                source = DotNetConfigurationSource.FromFile(fileName);
                break;

            default:
                source = IniConfigurationSource.FromFile(fileName);
                break;
            }
            return(source);
        }
Beispiel #30
0
        private static IConfigurationSource GetSource()
        {
            IConfigurationSource source;

            switch (Extension)
            {
            case ".ini":
                source = new IniConfigurationSource();
                break;

            case ".xml":
                source = new XmlConfigurationSource();
                break;

            case ".config":
                source = new DotNetConfigurationSource();
                break;

            default:
                source = new IniConfigurationSource();
                break;
            }
            return(source);
        }
 public void IniConfiguration_Does_Not_Throw_On_Optional_Configuration()
 {
     var configSource = new IniConfigurationSource("NotExistingConfig.ini", optional: true);
     configSource.Load();
     Assert.Throws<InvalidOperationException>(() => configSource.Get("key"));
 }
        public void LoadKeyValuePairsFromValidIniFileWithoutSectionHeader()
        {
            var ini = @"
            DefaultConnection:ConnectionString=TestConnectionString
            DefaultConnection:Provider=SqlClient
            Data:Inventory:ConnectionString=AnotherTestConnectionString
            Data:Inventory:Provider=MySql
            ";
            var iniConfigSrc = new IniConfigurationSource(TestStreamHelpers.ArbitraryFilePath);

            iniConfigSrc.Load(TestStreamHelpers.StringToStream(ini));

            Assert.Equal("TestConnectionString", iniConfigSrc.Get("DefaultConnection:ConnectionString"));
            Assert.Equal("SqlClient", iniConfigSrc.Get("DefaultConnection:Provider"));
            Assert.Equal("AnotherTestConnectionString", iniConfigSrc.Get("Data:Inventory:ConnectionString"));
            Assert.Equal("MySql", iniConfigSrc.Get("Data:Inventory:Provider"));
        }
        public void SupportAndIgnoreComments()
        {
            var ini = @"
            ; Comments
            [DefaultConnection]
            # Comments
            ConnectionString=TestConnectionString
            / Comments
            Provider=SqlClient
            [Data:Inventory]
            ConnectionString=AnotherTestConnectionString
            Provider=MySql
            ";
            var iniConfigSrc = new IniConfigurationSource(TestStreamHelpers.ArbitraryFilePath);

            iniConfigSrc.Load(TestStreamHelpers.StringToStream(ini));

            Assert.Equal("TestConnectionString", iniConfigSrc.Get("DefaultConnection:ConnectionString"));
            Assert.Equal("SqlClient", iniConfigSrc.Get("DefaultConnection:Provider"));
            Assert.Equal("AnotherTestConnectionString", iniConfigSrc.Get("Data:Inventory:ConnectionString"));
            Assert.Equal("MySql", iniConfigSrc.Get("Data:Inventory:Provider"));
        }
        protected virtual IConfigurationRoot LoadAppConfiguration(Xml.AppInfo appInfo, PathMap appPathMap)
        {
            var builder = new ConfigurationBuilder();

            foreach (var configuration in appInfo.ConfigurationFiles)
            {
                if (configuration.Environment != null && !configuration.Environment.Equals(this.EnvName, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                if (configuration is ConfigurationEnvironmentVariablesElement environmentVariablesConfiguration)
                {
                    builder.Add(new EnvironmentVariablesConfigurationSource()
                    {
                        Prefix = environmentVariablesConfiguration.Prefix,
                    });
                }
                else if (configuration is ConfigurationFileElement fileConfiguration)
                {
                    var loaded = false;
                    foreach (var configPath in appPathMap.Compile(fileConfiguration.Path))
                    {
                        if (File.Exists(configPath))
                        {
                            try
                            {
                                FileConfigurationSource source;
                                switch (fileConfiguration.Type)
                                {
                                case "ini": source = new IniConfigurationSource(); break;

                                case "xml": source = new XmlConfigurationSource(); break;

                                case "json": source = new JsonConfigurationSource(); break;

                                default: throw new Exception("Unknown configuration type.");
                                }

                                source.FileProvider   = new PhysicalFileProvider(Path.GetDirectoryName(configPath));
                                source.Path           = Path.GetFileName(configPath);
                                source.ReloadOnChange = fileConfiguration.ReloadOnChange;

                                builder.Add(source);
                            }
                            catch (Exception exception)
                            {
                                throw new Exception($"Can not read configuration file \"{configPath}\": {exception.Message}", exception);
                            }

                            loaded = true;
                            break;
                        }
                    }

                    if (!fileConfiguration.Optional && !loaded)
                    {
                        throw new Exception($"Can not find required configuration file \"{fileConfiguration.Path}\".");
                    }
                }
            }

            return(builder.Build());
        }
        public void LoadMethodCanHandleEmptyValue()
        {
            var ini = @"DefaultKey=";
            var iniConfigSrc = new IniConfigurationSource(TestStreamHelpers.ArbitraryFilePath);

            iniConfigSrc.Load(TestStreamHelpers.StringToStream(ini));

            Assert.Equal(string.Empty, iniConfigSrc.Get("DefaultKey"));
        }
        public void ThrowExceptionWhenKeyIsDuplicated()
        {
            var ini = @"
            [Data:DefaultConnection]
            ConnectionString=TestConnectionString
            Provider=SqlClient
            [Data]
            DefaultConnection:ConnectionString=AnotherTestConnectionString
            Provider=MySql
            ";
            var iniConfigSrc = new IniConfigurationSource(TestStreamHelpers.ArbitraryFilePath);
            var expectedMsg = Resources.FormatError_KeyIsDuplicated("Data:DefaultConnection:ConnectionString");

            var exception = Assert.Throws<FormatException>(() => iniConfigSrc.Load(TestStreamHelpers.StringToStream(ini)));

            Assert.Equal(expectedMsg, exception.Message);
        }
        public void LoadKeyValuePairsFromValidIniFileWithQuotedValues()
        {
            var ini = "[DefaultConnection]\n" +
                      "ConnectionString=\"TestConnectionString\"\n" +
                      "Provider=\"SqlClient\"\n" +
                      "[Data:Inventory]\n" +
                      "ConnectionString=\"AnotherTestConnectionString\"\n" +
                      "Provider=\"MySql\"";
            var iniConfigSrc = new IniConfigurationSource(TestStreamHelpers.ArbitraryFilePath);

            iniConfigSrc.Load(TestStreamHelpers.StringToStream(ini));

            Assert.Equal("TestConnectionString", iniConfigSrc.Get("DefaultConnection:ConnectionString"));
            Assert.Equal("SqlClient", iniConfigSrc.Get("DefaultConnection:Provider"));
            Assert.Equal("AnotherTestConnectionString", iniConfigSrc.Get("Data:Inventory:ConnectionString"));
            Assert.Equal("MySql", iniConfigSrc.Get("Data:Inventory:Provider"));
        }
 private static IConfigurationSource GetSource()
 {
     IConfigurationSource source;
     switch ( Extension )
     {
         case ".ini":
             source = new IniConfigurationSource();
             break;
         case ".xml":
             source = new XmlConfigurationSource();
             break;
         case ".config":
             source = new DotNetConfigurationSource();
             break;
         default:
             source = new IniConfigurationSource();
             break;
     }
     return source;
 }
        public void ThrowExceptionWhenFoundInvalidLine()
        {
            var ini = @"
            ConnectionString
            ";
            var iniConfigSrc = new IniConfigurationSource(TestStreamHelpers.ArbitraryFilePath);
            var expectedMsg = Resources.FormatError_UnrecognizedLineFormat("ConnectionString");

            var exception = Assert.Throws<FormatException>(() => iniConfigSrc.Load(TestStreamHelpers.StringToStream(ini)));

            Assert.Equal(expectedMsg, exception.Message);
        }