public void CanParseMultipleSections() { string xml = XmlConfigurationSource.ToXml( SectionGenerator.GetThreeSections() ); var source = new XmlConfigurationSource( xml ); Assert.Equal( 3, source.Sections.Count ); Assert.NotNull( source.Sections["Default"] ); Assert.NotNull( source.Sections["Default2"] ); Assert.NotNull( source.Sections["Default3"] ); int count = 0; foreach ( IConfigurationSection configurationSection in source ) { foreach ( KeyValuePair<string, string> pair in configurationSection ) { Assert.Equal( pair.Value, source.Sections[configurationSection.Name].Get<string>( pair.Key ) ); count++; } foreach ( KeyValuePair<string, string> pair in source.Sections[configurationSection.Name] ) { Assert.Equal( pair.Value, configurationSection.Get<string>( pair.Key ) ); count++; } } Assert.Equal( 10, count ); }
public void CanParseSingleSection() { IConfigurationSection section = SectionGenerator.GetSingleSection(); string xml = XmlConfigurationSource.ToXml( new[] {section} ); var source = new XmlConfigurationSource( xml ); Assert.Equal( 1, source.Sections.Count ); Assert.NotNull( source.Sections["Default"] ); int count = 0; foreach ( IConfigurationSection configurationSection in source ) { foreach ( KeyValuePair<string, string> pair in configurationSection ) { Assert.Equal( pair.Value, section.Get<string>( pair.Key ) ); count++; } foreach ( KeyValuePair<string, string> pair in section ) { Assert.Equal( pair.Value, configurationSection.Get<string>( pair.Key ) ); count++; } } Assert.Equal( 10, count ); }
public void CanLoadFromFile() { string xml = XmlConfigurationSource.ToXml( SectionGenerator.GetThreeSections() ); var source = new XmlConfigurationSource( xml ) {FileName = "CanLoadFromFile.xml"}; source.Save(); var sourceFromFile = XmlConfigurationSource.FromFile( "CanLoadFromFile.xml" ); string sourceString = source.ToString(); string sourceFromFileString = sourceFromFile.ToString(); Assert.Equal( sourceString, sourceFromFileString ); }
/// <summary> /// Initliaizes resources /// </summary> public static bool Initialize() { try { if (isInitialize == false) { XmlConfigurationSource source = new XmlConfigurationSource("Data/AppConfig.xml"); ActiveRecordStarter.Initialize(source, typeof(Blog), typeof(Post), typeof(User)); isInitialize = true; } return(true); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); return(false); } }
public void Initialize() { //ActiveRecordStarter.Initialize(typeof(BlogPost).Assembly, source); //ActiveRecordStarter.CreateSchema(); /* * Hashtable properties = new Hashtable(); * * properties.Add("hibernate.connection.driver_class", "NHibernate.Driver.SqlClientDriver"); * properties.Add("hibernate.dialect", "NHibernate.Dialect.MsSql2008Dialect"); * properties.Add("hibernate.connection.provider", "NHibernate.Connection.DriverConnectionProvider"); * properties.Add("hibernate.connection.connection_string", "Data Source=.\\SQLexpress;Initial Catalog=Northwind;Integrated Security=True"); * InPlaceConfigurationSource source = new InPlaceConfigurationSource(); * source.Add(typeof(ActiveRecordBase), (IDictionary<string, string>)properties); */ XmlConfigurationSource source = new XmlConfigurationSource("config.xml"); ActiveRecordStarter.Initialize(source, typeof(Order), typeof(Product), typeof(Supplier), typeof(Customer), typeof(OrderDetails)); }
public void SupportMixingNameAttributesAndCommonAttributes() { var xml = @"<settings> <Data Name='DefaultConnection' ConnectionString='TestConnectionString' Provider='SqlClient' /> <Data Name='Inventory' ConnectionString='AnotherTestConnectionString'> <Provider>MySql</Provider> </Data> </settings>"; var xmlConfigSrc = new XmlConfigurationSource(ArbitraryFilePath); xmlConfigSrc.Load(TestStreamHelpers.StringToStream(xml)); Assert.Equal("TestConnectionString", xmlConfigSrc.Get("Data:DefaultConnection:ConnectionString")); Assert.Equal("SqlClient", xmlConfigSrc.Get("Data:DefaultConnection:Provider")); Assert.Equal("AnotherTestConnectionString", xmlConfigSrc.Get("Data:Inventory:ConnectionString")); Assert.Equal("MySql", xmlConfigSrc.Get("Data:Inventory:Provider")); }
/// <summary> /// Adds a XML 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="XmlConfigurationSource"/> to add.</param> /// <returns>The <see cref="IConfigurationBuilder"/>.</returns> public static IConfigurationBuilder AddXmlFile( this IConfigurationBuilder builder, Action <XmlConfigurationSource> configureSource) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } if (configureSource == null) { throw new ArgumentNullException(nameof(configureSource)); } var source = new XmlConfigurationSource(); configureSource(source); builder.Add(source); return(builder); }
private static void Main() { Thread.CurrentThread.CurrentUICulture = new CultureInfo("zh-Hans"); // The following line provides localization for data formats. Thread.CurrentThread.CurrentCulture = new CultureInfo("zh-Hans"); IConfigurationSource config = new XmlConfigurationSource("ARConfig.xml"); var asm = Assembly.Load("LibEntity"); ActiveRecordStarter.Initialize(asm, config); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Login()); }
private static void Main() { Thread.CurrentThread.CurrentUICulture = new CultureInfo("zh-Hans"); // The following line provides localization for data formats. Thread.CurrentThread.CurrentCulture = new CultureInfo("zh-Hans"); IConfigurationSource config = new XmlConfigurationSource("ARConfig.xml"); var asm = Assembly.Load("LibEntity"); ActiveRecordStarter.Initialize(asm, config); var mf = new MainFormGe(new BarButtonItem()); var lf = new LoginForm(mf); Application.Run(lf); }
public static void Initialize(string typename, IConfigurationSource src = null) { if (src == null) { src = ConfigurationManager.GetSection("DataAccess") as IConfigurationSource; if (src == null && File.Exists(DefaultCfgFileName)) { src = new XmlConfigurationSource(DefaultCfgFileName); } } properties = new Dictionary <string, string>(); IConfiguration config = src.GetConfiguration(typename); foreach (IConfiguration childConfig in config.Children) { properties[childConfig.Name] = childConfig.Value; } }
/// <summary> /// Initliaizes resources /// </summary> public static bool Initialize() { try { if (isInitialize == false) { Stream appConfigStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("CslaDemo.BLL.Data.appconfig.xml"); XmlConfigurationSource source = new XmlConfigurationSource(appConfigStream); ActiveRecordStarter.Initialize(source, typeof(Blog), typeof(Post), typeof(User)); isInitialize = true; } return(true); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); return(false); } }
private static void Main() { Thread.CurrentThread.CurrentUICulture = new CultureInfo("zh-Hans"); // The following line provides localization for data formats. Thread.CurrentThread.CurrentCulture = new CultureInfo("zh-Hans"); IConfigurationSource config = new XmlConfigurationSource("ARConfig.xml"); var asm = Assembly.Load("LibEntity"); ActiveRecordStarter.Initialize(asm, config); RuntimeManager.Bind(ProductCode.EngineOrDesktop); var mf = new MainForm_OP(); Application.Run(mf); }
private void btnSelect_Click(object sender, EventArgs e) { ConfigHelper.current_seam = (CoalSeam)cboCoalSeam.SelectedItem; Hide(); XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(Application.StartupPath + "\\" + "ARConfig.xml"); XmlElement root = xmldoc.DocumentElement; var a = root.SelectNodes("/activerecord/config/add"); var sqlcons = a[3].Attributes["value"].InnerText.Split(';'); string str = ""; for (int i = 0; i < sqlcons.Length; i++) { switch (i) { case 0: str += "data Source=" + ConfigHelper.current_seam.db_name; break; default: str += sqlcons[i]; break; } str += ";"; } a[3].Attributes["value"].InnerText = str; xmldoc.Save(Application.StartupPath + "\\" + "ARConfig.xml"); Thread.CurrentThread.CurrentUICulture = new CultureInfo("zh-Hans"); Thread.CurrentThread.CurrentCulture = new CultureInfo("zh-Hans"); IConfigurationSource config = new XmlConfigurationSource("ARConfig.xml"); var asm = Assembly.Load("LibEntity"); ActiveRecordStarter.Initialize(asm, config); Form.ShowDialog(); }
public void LoadKeyValuePairsFromValidEncryptedXml_ThrowsPlatformNotSupported() { var xml = @" <settings> <Data.Setting> <DefaultConnection> <Connection.String>Test.Connection.String</Connection.String> <Provider>SqlClient</Provider> </DefaultConnection> <Inventory> <EncryptedData Type=""http://www.w3.org/2001/04/xmlenc#Element"" xmlns=""http://www.w3.org/2001/04/xmlenc#""> <EncryptionMethod Algorithm=""http://www.w3.org/2001/04/xmlenc#aes256-cbc"" /> <KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#""> <EncryptedKey xmlns=""http://www.w3.org/2001/04/xmlenc#""> <EncryptionMethod Algorithm=""http://www.w3.org/2001/04/xmlenc#kw-aes256"" /> <KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#""> <KeyName>myKey</KeyName> </KeyInfo> <CipherData> <CipherValue>b0dxJI/o00vZgTNOJ6wUt0/6wCKWlQANAYE8cBsEzok4LQma7ErEnA==</CipherValue> </CipherData> </EncryptedKey> </KeyInfo> <CipherData> <CipherValue>iXzecb+Cha80LLrl4zON3o7HfpRc0NxlJsnBb6zbKFa1HqtNhy2VrTnrEsZUViBWRkRbl+MCix7TiaIs4NtLijNU5Ob8Ez3vcD4T/QcmPywBYJDJhj1OUUeJSKH+icjg</CipherValue> </CipherData> </EncryptedData> <Provider>MySql</Provider> </Inventory> </Data.Setting> </settings>"; // Arrange var xmlConfigSrc = new XmlConfigurationSource(ArbitraryFilePath); // Act & assert var ex = Assert.Throws <PlatformNotSupportedException>(() => xmlConfigSrc.Load(TestStreamHelpers.StringToStream(xml))); Assert.Equal(Resources.Error_EncryptedXmlNotSupported, ex.Message); }
public void ThrowExceptionWhenKeyIsDuplicated() { var xml = @"<settings> <Data> <DefaultConnection> <ConnectionString>TestConnectionString</ConnectionString> <Provider>SqlClient</Provider> </DefaultConnection> </Data> <Data Name='DefaultConnection' ConnectionString='NewConnectionString'> <Provider>NewProvider</Provider> </Data> </settings>"; var xmlConfigSrc = new XmlConfigurationSource(ArbitraryFilePath); var expectedMsg = Resources.FormatError_KeyIsDuplicated("Data:DefaultConnection:ConnectionString", Resources.FormatMsg_LineInfo(8, 52)); var exception = Assert.Throws <FormatException>(() => xmlConfigSrc.Load(TestStreamHelpers.StringToStream(xml))); Assert.Equal(expectedMsg, exception.Message); }
public void ThrowExceptionWhenFindNamespace() { var xml = @"<settings xmlns:MyNameSpace='http://microsoft.com/wwa/mynamespace'> <MyNameSpace:Data> <DefaultConnection> <ConnectionString>TestConnectionString</ConnectionString> <Provider>SqlClient</Provider> </DefaultConnection> <Inventory> <ConnectionString>AnotherTestConnectionString</ConnectionString> <Provider>MySql</Provider> </Inventory> </MyNameSpace:Data> </settings>"; var xmlConfigSrc = new XmlConfigurationSource(ArbitraryFilePath); var expectedMsg = Resources.FormatError_NamespaceIsNotSupported(Resources.FormatMsg_LineInfo(1, 11)); var exception = Assert.Throws <FormatException>(() => xmlConfigSrc.Load(TestStreamHelpers.StringToStream(xml))); Assert.Equal(expectedMsg, exception.Message); }
public void LoadKeyValuePairsFromValidEncryptedXml_ThrowsPlatformNotSupported() { var xml = @" <settings> <Data.Setting> <DefaultConnection> <Connection.String>Test.Connection.String</Connection.String> <Provider>SqlClient</Provider> </DefaultConnection> <Inventory> <EncryptedData Type=""http://www.w3.org/2001/04/xmlenc#Element"" xmlns=""http://www.w3.org/2001/04/xmlenc#""> <EncryptionMethod Algorithm=""http://www.w3.org/2001/04/xmlenc#aes256-cbc"" /> <KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#""> <EncryptedKey xmlns=""http://www.w3.org/2001/04/xmlenc#""> <EncryptionMethod Algorithm=""http://www.w3.org/2001/04/xmlenc#kw-aes256"" /> <KeyInfo xmlns=""http://www.w3.org/2000/09/xmldsig#""> <KeyName>myKey</KeyName> </KeyInfo> <CipherData> <CipherValue>b0dxJI/o00vZgTNOJ6wUt0/6wCKWlQANAYE8cBsEzok4LQma7ErEnA==</CipherValue> </CipherData> </EncryptedKey> </KeyInfo> <CipherData> <CipherValue>iXzecb+Cha80LLrl4zON3o7HfpRc0NxlJsnBb6zbKFa1HqtNhy2VrTnrEsZUViBWRkRbl+MCix7TiaIs4NtLijNU5Ob8Ez3vcD4T/QcmPywBYJDJhj1OUUeJSKH+icjg</CipherValue> </CipherData> </EncryptedData> <Provider>MySql</Provider> </Inventory> </Data.Setting> </settings>"; // Arrange var xmlConfigSrc = new XmlConfigurationSource(ArbitraryFilePath); // Act & assert var ex = Assert.Throws<PlatformNotSupportedException>(() => xmlConfigSrc.Load(TestStreamHelpers.StringToStream(xml))); Assert.Equal(Resources.Error_EncryptedXmlNotSupported, ex.Message); }
public void NameAttributeInRootElementContributesToPrefix() { var xml = @"<settings Name='Data'> <DefaultConnection> <ConnectionString>TestConnectionString</ConnectionString> <Provider>SqlClient</Provider> </DefaultConnection> <Inventory> <ConnectionString>AnotherTestConnectionString</ConnectionString> <Provider>MySql</Provider> </Inventory> </settings>"; var xmlConfigSrc = new XmlConfigurationSource(ArbitraryFilePath); xmlConfigSrc.Load(TestStreamHelpers.StringToStream(xml)); Assert.Equal("TestConnectionString", xmlConfigSrc.Get("Data:DefaultConnection:ConnectionString")); Assert.Equal("SqlClient", xmlConfigSrc.Get("Data:DefaultConnection:Provider")); Assert.Equal("AnotherTestConnectionString", xmlConfigSrc.Get("Data:Inventory:ConnectionString")); Assert.Equal("MySql", xmlConfigSrc.Get("Data:Inventory:Provider")); }
public void Initialize() { try { if (ActiveRecordStarter.IsInitialized) { return; } //Gets the assembly in which the Character model is present var assembly = Assembly.GetAssembly(typeof(Creature)); //Get path of current bin directory and then navifates to the xml file. var path = TestContext.CurrentContext.TestDirectory + "../../../ActiveRecord.Test.xml"; XmlConfigurationSource config = new XmlConfigurationSource(path); //Initilaize activerecord with given configuration ActiveRecordStarter.Initialize(assembly, config); } catch (InvalidOperationException exception) { string causeOfException = "Het domein-model kan niet worden geinitaliseerd. Er is een fout opgetreden: " + "De instelling, die aangeeft waar de configuratie voor het " + "ORM framework zich bevind, kan niet worden geladen. "; throw new InvalidOperationException(causeOfException, exception); } catch (Exception exception) { // Er is een onbekende fout opgetreden. string causeOfException = "Het domein-model kan niet worden geinitaliseerd. Er is een onbekende fout opgetreden."; throw new Exception(causeOfException, exception); } }
public void CommonAttributesContributeToKeyValuePairs() { var xml = @"<settings Port=""8008""> <Data> <DefaultConnection ConnectionString=""TestConnectionString"" Provider=""SqlClient""/> <Inventory ConnectionString=""AnotherTestConnectionString"" Provider=""MySql""/> </Data> </settings>"; var xmlConfigSrc = new XmlConfigurationSource(ArbitraryFilePath); xmlConfigSrc.Load(TestStreamHelpers.StringToStream(xml)); Assert.Equal("8008", xmlConfigSrc.Get("Port")); Assert.Equal("TestConnectionString", xmlConfigSrc.Get("Data:DefaultConnection:ConnectionString")); Assert.Equal("SqlClient", xmlConfigSrc.Get("Data:DefaultConnection:Provider")); Assert.Equal("AnotherTestConnectionString", xmlConfigSrc.Get("Data:Inventory:ConnectionString")); Assert.Equal("MySql", xmlConfigSrc.Get("Data:Inventory:Provider")); }
public void SupportMixingChildElementsAndAttributes() { var xml = @"<settings Port='8008'> <Data> <DefaultConnection Provider='SqlClient'> <ConnectionString>TestConnectionString</ConnectionString> </DefaultConnection> <Inventory ConnectionString='AnotherTestConnectionString'> <Provider>MySql</Provider> </Inventory> </Data> </settings>"; var xmlConfigSrc = new XmlConfigurationSource(ArbitraryFilePath); xmlConfigSrc.Load(TestStreamHelpers.StringToStream(xml)); Assert.Equal("8008", xmlConfigSrc.Get("Port")); Assert.Equal("TestConnectionString", xmlConfigSrc.Get("Data:DefaultConnection:ConnectionString")); Assert.Equal("SqlClient", xmlConfigSrc.Get("Data:DefaultConnection:Provider")); Assert.Equal("AnotherTestConnectionString", xmlConfigSrc.Get("Data:Inventory:ConnectionString")); Assert.Equal("MySql", xmlConfigSrc.Get("Data:Inventory:Provider")); }
/// <summary> /// Adds a XML 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 AddXmlFile(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("Error_InvalidFilePath", nameof(path)); } var source = new XmlConfigurationSource { FileProvider = provider, Path = path, Optional = optional, ReloadOnChange = reloadOnChange }; source.ResolveFileProvider(); builder.Add(source); return(builder); }
/// <summary> /// Called to initialize setup NHibernate and ActiveRecord /// </summary> /// <param name="asm"></param> /// <param name="dbType"></param> /// <param name="connStr"></param> /// <returns>Whether its a fatal error</returns> public static bool InitAR(Assembly asm) { if (s_configReader == null) { s_configReader = DatabaseConfiguration.GetARConfiguration(DBType, ConnectionString); if (s_configReader == null) { throw new Exception("Invalid Database Type: " + DBType); } } s_config = new XmlConfigurationSource(s_configReader); NHibernate.Cfg.Environment.UseReflectionOptimizer = true; ActiveRecordStarter.Initialize(asm, s_config); if (!IsConnected) { throw new Exception("Failed to connect to Database."); } s_dialect = NHibernate.Dialect.Dialect.GetDialect(Config.Properties) ?? NHibernate.Dialect.Dialect.GetDialect(); return(true); }
private static void InitializeFacilities() { //init for the log system var configForLogging = ConfigurationManager.AppSettings["LoggingConfig"].ToServerPath(); log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(configForLogging)); //init the database var configForDatabase = ConfigurationManager.AppSettings["DatabaseConfig"].ToServerPath(); IConfigurationSource source = new XmlConfigurationSource(configForDatabase); ActiveRecordStarter.Initialize(source, typeof(Data.Log), //为避免数据库体积过大,将日志记录至 /tmp 目录下 typeof(Users), typeof(Roles), typeof(Account), typeof(Block), typeof(Bot), typeof(Mine), typeof(MineProfile), typeof(Share) ); }
public void SupportAndIgnoreComments() { var xml = @"<!-- Comments --> <settings> <Data> <!-- Comments --> <DefaultConnection> <ConnectionString><!-- Comments -->TestConnectionString</ConnectionString> <Provider>SqlClient</Provider> </DefaultConnection> <Inventory> <ConnectionString>AnotherTestConnectionString</ConnectionString> <Provider>MySql</Provider> </Inventory> </Data> </settings><!-- Comments -->"; var xmlConfigSrc = new XmlConfigurationSource(ArbitraryFilePath); xmlConfigSrc.Load(TestStreamHelpers.StringToStream(xml)); Assert.Equal("TestConnectionString", xmlConfigSrc.Get("Data:DefaultConnection:ConnectionString")); Assert.Equal("SqlClient", xmlConfigSrc.Get("Data:DefaultConnection:Provider")); Assert.Equal("AnotherTestConnectionString", xmlConfigSrc.Get("Data:Inventory:ConnectionString")); Assert.Equal("MySql", xmlConfigSrc.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 LoadKeyValuePairsFromValidXml() { var xml = @" <settings> <Data.Setting> <DefaultConnection> <Connection.String>Test.Connection.String</Connection.String> <Provider>SqlClient</Provider> </DefaultConnection> <Inventory> <ConnectionString>AnotherTestConnectionString</ConnectionString> <Provider>MySql</Provider> </Inventory> </Data.Setting> </settings>"; var xmlConfigSrc = new XmlConfigurationSource(ArbitraryFilePath); xmlConfigSrc.Load(TestStreamHelpers.StringToStream(xml)); Assert.Equal("Test.Connection.String", xmlConfigSrc.Get("DATA.SETTING:DEFAULTCONNECTION:CONNECTION.STRING")); Assert.Equal("SqlClient", xmlConfigSrc.Get("DATA.SETTING:DefaultConnection:Provider")); Assert.Equal("AnotherTestConnectionString", xmlConfigSrc.Get("data.setting:inventory:connectionstring")); Assert.Equal("MySql", xmlConfigSrc.Get("Data.setting:Inventory:Provider")); }
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); }
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()); }
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 SupportAndIgnoreXMLDeclaration() { var xml = @"<?xml version='1.0' encoding='UTF-8'?> <settings> <Data> <DefaultConnection> <ConnectionString>TestConnectionString</ConnectionString> <Provider>SqlClient</Provider> </DefaultConnection> <Inventory> <ConnectionString>AnotherTestConnectionString</ConnectionString> <Provider>MySql</Provider> </Inventory> </Data> </settings>"; var xmlConfigSrc = new XmlConfigurationSource(ArbitraryFilePath); xmlConfigSrc.Load(TestStreamHelpers.StringToStream(xml)); Assert.Equal("TestConnectionString", xmlConfigSrc.Get("Data:DefaultConnection:ConnectionString")); Assert.Equal("SqlClient", xmlConfigSrc.Get("Data:DefaultConnection:Provider")); Assert.Equal("AnotherTestConnectionString", xmlConfigSrc.Get("Data:Inventory:ConnectionString")); Assert.Equal("MySql", xmlConfigSrc.Get("Data:Inventory:Provider")); }
public void SupportCDATAAsTextNode() { var xml = @"<settings> <Data> <Inventory> <Provider><![CDATA[SpecialStringWith<>]]></Provider> </Inventory> </Data> </settings>"; var xmlConfigSrc = new XmlConfigurationSource(ArbitraryFilePath); xmlConfigSrc.Load(TestStreamHelpers.StringToStream(xml)); Assert.Equal("SpecialStringWith<>", xmlConfigSrc.Get("Data:Inventory:Provider")); }
public void XmlConfiguration_Does_Not_Throw_On_Optional_Configuration() { var configSource = new XmlConfigurationSource("NotExistingConfig.xml", optional: true); configSource.Load(); Assert.Throws<InvalidOperationException>(() => configSource.Get("key")); }
public ExtendedXmlConfigurationProvider(XmlConfigurationSource source) : base(source) { }
public void NameAttributeContributesToPrefix() { var xml = @"<settings> <Data Name='DefaultConnection'> <ConnectionString>TestConnectionString</ConnectionString> <Provider>SqlClient</Provider> </Data> <Data Name='Inventory'> <ConnectionString>AnotherTestConnectionString</ConnectionString> <Provider>MySql</Provider> </Data> </settings>"; var xmlConfigSrc = new XmlConfigurationSource(ArbitraryFilePath); xmlConfigSrc.Load(TestStreamHelpers.StringToStream(xml)); Assert.Equal("TestConnectionString", xmlConfigSrc.Get("Data:DefaultConnection:ConnectionString")); Assert.Equal("SqlClient", xmlConfigSrc.Get("Data:DefaultConnection:Provider")); Assert.Equal("AnotherTestConnectionString", xmlConfigSrc.Get("Data:Inventory:ConnectionString")); Assert.Equal("MySql", xmlConfigSrc.Get("Data:Inventory:Provider")); }
public void LoadMethodCanHandleEmptyValue() { var xml = @"<?xml version=""1.0"" encoding=""UTF-8""?> <?xml-stylesheet type=""text/xsl"" href=""style1.xsl""?> <settings> <?xml-stylesheet type=""text/xsl"" href=""style2.xsl""?> <Key1></Key1> <Key2 Key3="""" /> </settings>"; var xmlConfigSrc = new XmlConfigurationSource(ArbitraryFilePath); xmlConfigSrc.Load(TestStreamHelpers.StringToStream(xml)); Assert.Equal(string.Empty, xmlConfigSrc.Get("Key1")); Assert.Equal(string.Empty, xmlConfigSrc.Get("Key2:Key3")); }
public void XmlConfiguration_Throws_On_Missing_Configuration_File() { var configSource = new XmlConfigurationSource("NotExistingConfig.xml", optional: false); Assert.Throws<FileNotFoundException>(() => { try { configSource.Load(); } catch (FileNotFoundException exception) { Assert.Equal(Resources.FormatError_FileNotFound("NotExistingConfig.xml"), exception.Message); throw; } }); }
/// <summary> /// 演示IConfigurationBuilder、IConfiguration、IConfigurationSource的关系 /// </summary> static void Demo2() { // 定义 IConfigurationSource json var source = new JsonConfigurationSource() { Path = "config.json", ReloadOnChange = true, ReloadDelay = 200 }; // 定义 IConfigurationSource xml var source2 = new XmlConfigurationSource() { Path = "config.xml" }; // 定义 IConfigurationBuilder // var builder = new ConfigurationBuilder().Add(source).Add(source2); var builder = new ConfigurationBuilder().Add(source); // 定义 IConfiguration var config = builder.Build(); var services = new ServiceCollection(); Action changeCallBack = () => { ConfigInfo options = services .AddOptions() .Configure <ConfigInfo>(config) .BuildServiceProvider() .GetService <IOptions <ConfigInfo> >() .Value; Console.WriteLine(options.Version); }; var opts = services.BuildServiceProvider().GetService <IOptions <ConfigInfo> >().Value; ChangeToken.OnChange(() => config.GetReloadToken(), changeCallBack); //// 读取配置,配置名称不区分大小写 //Console.WriteLine(config["Version"]); //Console.WriteLine(config.GetSection("Items").GetChildren().ToArray()[0]["Name"]); //Console.WriteLine(config.GetSection("Items").GetChildren().ToArray()[1]["Name"]); //// Console.WriteLine(config.GetSection("Items").GetChildren().ToArray()[2]["Name"]); //Console.WriteLine(config["Extend"]); // 从 IConfiguration 中创建类型 //ConfigInfo oldCfgInfo = null; //while (true) //{ // var cfgInfo = config.Get<ConfigInfo>(); // if (oldCfgInfo != cfgInfo) // { // oldCfgInfo = cfgInfo; // Console.WriteLine("创建实例"); // } // Console.WriteLine(cfgInfo.Version); // Thread.Sleep(1000); //} // 读取配置 // Console.WriteLine(cfgInfo.Version); }
public void ThrowExceptionWhenKeyIsDuplicated() { var xml = @"<settings> <Data> <DefaultConnection> <ConnectionString>TestConnectionString</ConnectionString> <Provider>SqlClient</Provider> </DefaultConnection> </Data> <Data Name='DefaultConnection' ConnectionString='NewConnectionString'> <Provider>NewProvider</Provider> </Data> </settings>"; var xmlConfigSrc = new XmlConfigurationSource(ArbitraryFilePath); var expectedMsg = Resources.FormatError_KeyIsDuplicated("Data:DefaultConnection:ConnectionString", Resources.FormatMsg_LineInfo(8, 52)); var exception = Assert.Throws<FormatException>(() => xmlConfigSrc.Load(TestStreamHelpers.StringToStream(xml))); Assert.Equal(expectedMsg, exception.Message); }
public void ThrowExceptionWhenFindNamespace() { var xml = @"<settings xmlns:MyNameSpace='http://microsoft.com/wwa/mynamespace'> <MyNameSpace:Data> <DefaultConnection> <ConnectionString>TestConnectionString</ConnectionString> <Provider>SqlClient</Provider> </DefaultConnection> <Inventory> <ConnectionString>AnotherTestConnectionString</ConnectionString> <Provider>MySql</Provider> </Inventory> </MyNameSpace:Data> </settings>"; var xmlConfigSrc = new XmlConfigurationSource(ArbitraryFilePath); var expectedMsg = Resources.FormatError_NamespaceIsNotSupported(Resources.FormatMsg_LineInfo(1, 11)); var exception = Assert.Throws<FormatException>(() => xmlConfigSrc.Load(TestStreamHelpers.StringToStream(xml))); Assert.Equal(expectedMsg, exception.Message); }
public void ThrowExceptionWhenFindDTD() { var xml = @"<!DOCTYPE DefaultConnection[ <!ELEMENT DefaultConnection (ConnectionString,Provider)> <!ELEMENT ConnectionString (#PCDATA)> <!ELEMENT Provider (#PCDATA)> ]> <settings> <Data> <DefaultConnection> <ConnectionString>TestConnectionString</ConnectionString> <Provider>SqlClient</Provider> </DefaultConnection> <Inventory> <ConnectionString>AnotherTestConnectionString</ConnectionString> <Provider>MySql</Provider> </Inventory> </Data> </settings>"; var xmlConfigSrc = new XmlConfigurationSource(ArbitraryFilePath); var isMono = Type.GetType("Mono.Runtime") != null; var expectedMsg = isMono ? "Document Type Declaration (DTD) is prohibited in this XML. Line 1, position 10." : "For security reasons DTD is prohibited in this XML document. " + "To enable DTD processing set the DtdProcessing property on XmlReaderSettings " + "to Parse and pass the settings into XmlReader.Create method."; var exception = Assert.Throws<System.Xml.XmlException>(() => xmlConfigSrc.Load(TestStreamHelpers.StringToStream(xml))); Assert.Equal(expectedMsg, exception.Message); }