public void AddingCategoryFilterToConfigIsReflectedInContainer() { using (var configurationSource = new SystemConfigurationSource(false)) using (var serviceLocator = (UnityServiceLocator)EnterpriseLibraryContainer.CreateDefaultContainer(configurationSource)) { EnterpriseLibraryContainer.Current = serviceLocator; Logger.Reset(); MockTraceListener.Reset(); Logger.Write("test", "MockCategoryOne"); Assert.AreEqual(1, MockTraceListener.Entries.Count); System.Configuration.Configuration rwConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); LoggingSettings rwSettings = rwConfiguration.GetSection(LoggingSettings.SectionName) as LoggingSettings; ((CategoryFilterData)rwSettings.LogFilters.Get("Category")).CategoryFilters.Add(new CategoryFilterEntry("MockCategoryOne")); rwConfiguration.Save(); ((IConfigurationSourceTest)configurationSource).ConfigSourceChanged(string.Empty); var categoryFilter = EnterpriseLibraryContainer.Current.GetInstance <CategoryFilter>("Category"); Assert.AreEqual(1, categoryFilter.CategoryFilters.Count(c => c == "MockCategoryOne")); } }
static void Main(string[] args) { // 構成情報を組み立てる var builder = new ConfigurationSourceBuilder(); builder.ConfigureLogging() .SpecialSources .AllEventsCategory .SendTo .FlatFile("FlatFileListener") .FormatWith( new FormatterBuilder() .TextFormatterNamed("TextFormatter") .UsingTemplate("{timestamp(local:yyyy/MM/dd HH:mm:ss.fff)}: {message}")) .ToFile("output.txt"); // 組み立てた構成情報からConfigurationSourceを作成 var config = new DictionaryConfigurationSource(); builder.UpdateConfigurationWithReplace(config); // 構成情報を元にEnterpriseLibraryのコンテナの初期化 EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(config); // EnterpriseLibraryのコンテナからLogging Application BlockのLog書き込み部品を取得 var logger = EnterpriseLibraryContainer.Current.GetInstance <LogWriter>(); // ログに出力する logger.Write("Hello world"); // ログを表示 Process.Start("output.txt"); }
public void EntLib5UseCase() { // construct the Configuration Source to use var builder = new ConfigurationSourceBuilder(); // fluent API configuration builder.ConfigureLogging() .WithOptions .DoNotRevertImpersonation() .LogToCategoryNamed("Simple") .SendTo.FlatFile("Simple Log File") .FormatWith(new FormatterBuilder() .TextFormatterNamed("simpleFormat") .UsingTemplate("{timestamp} : {message}{newline}")) .ToFile("simple.log"); var configSource = new DictionaryConfigurationSource(); builder.UpdateConfigurationWithReplace(configSource); EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource); ILog log = LogManager.GetLogger(GetType()); log.Debug("Debug Event Log Entry."); log.Warn("Warning Event Log Entry."); }
public override void createTestFixture() { base.createTestFixture(); ObjectsConverter.Configure(); configureLogging(); clientInformation = new ClientInformation() { Version = Const.ServiceVersion }; clientInformation.ApplicationLanguage = "en"; clientInformation.PlatformVersion = "fgfdgdfg"; clientInformation.ApplicationVersion = "1.0.0.0"; var conf = new ConfigurationSourceBuilder(); conf.ConfigureCaching().ForCacheManagerNamed(SecurityManager.AuthenticationCacheName).StoreInMemory(); var configSource = new DictionaryConfigurationSource(); conf.UpdateConfigurationWithReplace(configSource); var xmlStream = DateTimeExtension.GetResource("BodyArchitect.UnitTests.V2.BAPointsTests.BAPoints.xml"); var paymentsManager = new PaymentsManager(); this.paymentsManager = paymentsManager.Load(xmlStream); InternalBodyArchitectService.PaymentsManager = this.paymentsManager; EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource); }
public void ConfigurationChangeNotificationRefreshesLoggerAutomatically() { using (var configurationSource = new SystemConfigurationSource(true, 100)) using (var serviceLocator = (UnityServiceLocator)EnterpriseLibraryContainer.CreateDefaultContainer(configurationSource)) { EnterpriseLibraryContainer.Current = serviceLocator; Logger.Reset(); MockTraceListener.Reset(); Logger.Write("test", "MockCategoryOne"); Assert.AreEqual(1, MockTraceListener.Entries.Count); System.Configuration.Configuration rwConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); LoggingSettings rwSettings = rwConfiguration.GetSection(LoggingSettings.SectionName) as LoggingSettings; ((CategoryFilterData)rwSettings.LogFilters.Get("Category")).CategoryFilters.Add(new CategoryFilterEntry("MockCategoryOne")); rwConfiguration.Save(); Thread.Sleep(1000); MockTraceListener.Reset(); Logger.Write("test", "MockCategoryOne"); Assert.AreEqual(0, MockTraceListener.Entries.Count); } }
public void ConfigurationChangeNotificationRefreshesLogger() { using (var configurationSource = new SystemConfigurationSource(false)) using (var serviceLocator = (UnityServiceLocator)EnterpriseLibraryContainer.CreateDefaultContainer(configurationSource)) { EnterpriseLibraryContainer.Current = serviceLocator; Logger.Reset(); MockTraceListener.Reset(); Logger.Write("test", "MockCategoryOne"); Assert.AreEqual(1, MockTraceListener.Entries.Count); System.Configuration.Configuration rwConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); LoggingSettings rwSettings = rwConfiguration.GetSection(LoggingSettings.SectionName) as LoggingSettings; ((CategoryFilterData)rwSettings.LogFilters.Get("Category")).CategoryFilters.Add(new CategoryFilterEntry("MockCategoryOne")); rwConfiguration.Save(); ((IConfigurationSourceTest)configurationSource).ConfigSourceChanged(string.Empty); MockTraceListener.Reset(); Logger.Write("test", "MockCategoryOne"); Assert.AreEqual(0, MockTraceListener.Entries.Count, "should have been filtered out by the new category filter"); } }
public void SetUp() { hashProviders = new Dictionary <string, IHashProvider>(); symmetricCrytoProviders = new Dictionary <string, ISymmetricCryptoProvider>(); CreateKeyFile(symmetricKeyFile); CreateKeyFile(keyedHashKeyFile); configSource = ConfigurationSourceFactory.Create(); HashProviderFactory factory = new HashProviderFactory(configSource); defaultHashProvider = factory.Create(hashInstance); hashProviders.Add(hashInstance, defaultHashProvider); SymmetricCryptoProviderFactory symmfactory = new SymmetricCryptoProviderFactory(configSource); defaultSymmetricCryptoProvider = symmfactory.Create(symmInstance); algorithSymmetricCryptoProvider = symmfactory.Create(symmetricAlgorithm1); symmetricCrytoProviders.Add(symmInstance, defaultSymmetricCryptoProvider); symmetricCrytoProviders.Add(symmetricAlgorithm1, algorithSymmetricCryptoProvider); var container = EnterpriseLibraryContainer.CreateDefaultContainer(configSource); cryptographyManager = container.GetInstance <CryptographyManager>(); }
public void TestGetExceptionManagerFromServiceLocator() { // Create the container var container = new UnityContainer(); // Configurator will read Enterprise Library configuration // and set up the container var configurator = new UnityContainerConfigurator(container); // Configuration source holds the new configuration we want to use // load this in your own code var configSource = new FileConfigurationSource("EntLib.config.xml"); // Configure the container EnterpriseLibraryContainer.CreateDefaultContainer(configSource); // Wrap in ServiceLocator var locator = new UnityServiceLocator(container); // And set Enterprise Library to use it EnterpriseLibraryContainer.Current = locator; var exceptionManager = EnterpriseLibraryContainer.Current.GetInstance <ExceptionManager>(); Assert.NotNull(exceptionManager); }
private void configureEntLib() { var formatterStandard = new FormatterBuilder().TextFormatterNamed("Text Formatter").UsingTemplate( "Timestamp: {timestamp}{newline}Message: {message}{newline}Severity: {severity}{newline}Machine: {machine}{newline}Process Name: {processName}{newline}Extended Properties: {dictionary({key} - {value}{newline})}"); var conf = new ConfigurationSourceBuilder(); var logConfig = conf.ConfigureLogging(); logConfig.WithOptions.LogToCategoryNamed("Exception").SendTo.RollingFile( "ExceptionFileListener").WithHeader("----------------------------------------").WithFooter("----------------------------------------").ToFile(UserContext.Settings.ExceptionsLogFile); logConfig.WithOptions.LogToCategoryNamed("General").SendTo.RollingFile( "FlatFile TraceListener").WithHeader("----------------------------------------").WithFooter("----------------------------------------").FormatWith(formatterStandard).ToFile(UserContext.Settings.StandardLogFile); logConfig.WithOptions.LogToCategoryNamed("email").SendTo.Email("email").FormatWith(formatterStandard).UsingSmtpServer( ApplicationSettings.MailSmtp).WithUserNameAndPassword(ApplicationSettings.MailUserName, ApplicationSettings.MailPassword).To( ApplicationSettings.MailAccount).From( ApplicationSettings.MailAccount).UseSSL(true); //configure cache var cacheCfg = conf.ConfigureCaching(); cacheCfg.ForCacheManagerNamed(PicturesCache.PicturesCacheName).StoreInIsolatedStorage( "Isolated Storage Cache Store").UsePartition("PicturesCache1"); cacheCfg.ForCacheManagerNamed("ErrorCache").StoreInMemory(); var configSource = new DictionaryConfigurationSource(); conf.UpdateConfigurationWithReplace(configSource); EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource); BodyArchitect.Logger.Log.EnableExceptionLog = Settings1.Default.LogErrorEnabled; BodyArchitect.Logger.Log.EnableStandardLog = Settings1.Default.LogStandardEnabled; }
public void EntLib5FactoryTestWithFluentConfig() { // construct the Configuration Source to use var builder = new ConfigurationSourceBuilder(); // fluent API configuration builder.ConfigureLogging() .WithOptions .DoNotRevertImpersonation() .LogToCategoryNamed("Simple") .SendTo.FlatFile("Simple Log File") .FormatWith(new FormatterBuilder() .TextFormatterNamed("simpleFormat") .UsingTemplate("{timestamp} : {message}{newline}")) .ToFile("simple.log"); var configSource = new DictionaryConfigurationSource(); builder.UpdateConfigurationWithReplace(configSource); EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource); // initialize the EntLib5 Logger factory with configuration file EntLib5Factory factory = new EntLib5Factory(); ILog log = factory.GetLogger(GetType()); Assert.IsNotNull(log); Assert.IsNotNull(log as EntLib5Logger); }
void NullEncryptorTests(string instanceName) { MockStorageEncryptionProvider.Encrypted = false; MockStorageEncryptionProvider.Decrypted = false; CacheManagerSettings settings = (CacheManagerSettings)TestConfigurationSource.GenerateConfiguration().GetSection(CacheManagerSettings.SectionName); CacheStorageData cacheStorageData = settings.BackingStores.Get(((CacheManagerData)settings.CacheManagers.Get(instanceName)).CacheStorage); StorageEncryptionProviderData encryptionProviderData = settings.EncryptionProviders.Get(cacheStorageData.StorageEncryption); IStorageEncryptionProvider provider = EnterpriseLibraryContainer.CreateDefaultContainer(TestConfigurationSource.GenerateConfiguration()).GetInstance <IStorageEncryptionProvider>(encryptionProviderData.Name); Assert.IsNotNull(provider); byte[] input = new byte[] { 0, 1, 2, 3, 4, 5 }; byte[] encrypted = provider.Encrypt(input); Assert.IsTrue(MockStorageEncryptionProvider.Encrypted, "static encrypted"); Assert.IsTrue(CompareBytes(input, encrypted), "no encryption performed"); byte[] decrypted = provider.Decrypt(encrypted); Assert.IsTrue(MockStorageEncryptionProvider.Decrypted, "static decrypted"); Assert.IsTrue(CompareBytes(encrypted, decrypted), "no decryption performed"); Assert.IsTrue(CompareBytes(input, decrypted), "no decryption performed2"); }
public void CanBuildValidationInstanceFactoryFromGivenConfiguration() { DictionaryConfigurationSource configurationSource = new DictionaryConfigurationSource(); ValidationSettings settings = new ValidationSettings(); configurationSource.Add(ValidationSettings.SectionName, settings); ValidatedTypeReference typeReference = new ValidatedTypeReference(typeof(BaseTestDomainObject)); settings.Types.Add(typeReference); typeReference.DefaultRuleset = "RuleA"; ValidationRulesetData ruleData = new ValidationRulesetData("RuleA"); typeReference.Rulesets.Add(ruleData); ValidatedPropertyReference propertyReference1 = new ValidatedPropertyReference("Property1"); ruleData.Properties.Add(propertyReference1); MockValidatorData validator11 = new MockValidatorData("validator1", true); propertyReference1.Validators.Add(validator11); validator11.MessageTemplate = "message-from-config1-RuleA"; CompositeValidatorFactory factory = EnterpriseLibraryContainer.CreateDefaultContainer(configurationSource) .GetInstance <CompositeValidatorFactory>(); var validator = factory.CreateValidator <BaseTestDomainObject>("RuleA"); var results = validator.Validate(new BaseTestDomainObject()); Assert.IsNotNull(factory); Assert.IsFalse(results.IsValid); Assert.AreEqual(validator11.MessageTemplate, results.ElementAt(0).Message); }
/// <summary> /// ConfigurationSourceBuilderの内容を元にIServiceProviderを作成します。 /// </summary> /// <param name="self"></param> /// <returns></returns> public static IServiceLocator CreateContainer(this ConfigurationSourceBuilder self) { var configuration = new DictionaryConfigurationSource(); self.UpdateConfigurationWithReplace(configuration); return(EnterpriseLibraryContainer.CreateDefaultContainer(configuration)); }
private static TraceListener GetListener(string name, IConfigurationSource configurationSource) { var container = EnterpriseLibraryContainer.CreateDefaultContainer(configurationSource); var listener = container.GetInstance <TraceListener>(name); container.Dispose(); return(listener); }
/// <summary> /// Initializes a new instance of the <see cref="EntLib5Factory"/> class. /// </summary> /// <param name="EntLib5ConfigurationSrc">The enterprise library 5.0 configuration source to load. Supercedes any configuration found in the Config file.</param> public EntLib5Factory(IConfigurationSource EntLib5ConfigurationSrc) { // replace any settings from App.Config with the ones in the provided config source var builder = new ConfigurationSourceBuilder(); builder.UpdateConfigurationWithReplace(EntLib5ConfigurationSrc); EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(EntLib5ConfigurationSrc); }
public void CanResolveCryptoProvider() { IServiceLocator container = EnterpriseLibraryContainer.CreateDefaultContainer(configurationSource); ISymmetricCryptoProvider provider = container.GetInstance <ISymmetricCryptoProvider>(symmetricInstance); Assert.IsNotNull(provider); Assert.AreSame(typeof(DpapiSymmetricCryptoProvider), provider.GetType()); }
public void CanBuildLogWriterStructureHolder() { LogWriterStructureHolder setup = EnterpriseLibraryContainer.CreateDefaultContainer(configurationSource) .GetInstance <LogWriterStructureHolder>(); Assert.IsNotNull(setup); Assert.AreEqual(2, setup.TraceSources.Count); }
public void StaticFacadeUsesTheCurrentServiceLocator() { GlobalCountCallHandler.Calls.Clear(); var interceptionConfigurationSource = new DictionaryConfigurationSource(); interceptionConfigurationSource.Add( PolicyInjectionSettings.SectionName, new PolicyInjectionSettings { Policies = { new PolicyData("policy") { MatchingRules = { new CustomMatchingRuleData("always", typeof(AlwaysMatchingRule)) }, Handlers = { new CustomCallHandlerData("count", typeof(GlobalCountCallHandler)) { Attributes ={ { "callhandler","count" } } } } } } }); var interceptionLocator = EnterpriseLibraryContainer.CreateDefaultContainer(interceptionConfigurationSource); var noInterceptionLocator = EnterpriseLibraryContainer.CreateDefaultContainer(new DictionaryConfigurationSource()); try { EnterpriseLibraryContainer.Current = interceptionLocator; var interceptedWrappable = PolicyInjection.Create <Wrappable>(); interceptedWrappable.Method(); Assert.AreEqual(1, GlobalCountCallHandler.Calls.Count); GlobalCountCallHandler.Calls.Clear(); EnterpriseLibraryContainer.Current = noInterceptionLocator; var nonInterceptedWrappable = PolicyInjection.Create <Wrappable>(); nonInterceptedWrappable.Method(); Assert.AreEqual(0, GlobalCountCallHandler.Calls.Count); } finally { EnterpriseLibraryContainer.Current = null; GlobalCountCallHandler.Calls.Clear(); interceptionLocator.Dispose(); noInterceptionLocator.Dispose(); } }
protected override void Act() { IServiceLocator locator = EnterpriseLibraryContainer.CreateDefaultContainer(GetConfig()); EnterpriseLibraryContainer.Current = locator; staticFu = EnterpriseLibraryContainer.Current.GetInstance <StaticFu>(); Assert.IsInstanceOfType(staticFu.MyInnerFoo, typeof(Foo)); updatableConfigSource.DoSourceChanged(new[] { "MockRegistrationProvider" }); }
static IServiceLocator GetContainerWithTracingFlag(bool tracingEnabled) { var config = new FileConfigurationSource(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile, false); var loggingSettings = ((LoggingSettings)config.GetSection(LoggingSettings.SectionName)); loggingSettings.TracingEnabled = tracingEnabled; Logger.Reset(); return(EnterpriseLibraryContainer.CreateDefaultContainer(config)); }
private static ITracerInstrumentationProvider GetTracerInstrumentationProvider(IConfigurationSource configuration) { if (configuration == null) { return(new NullTracerInstrumentationProvider()); } var container = EnterpriseLibraryContainer.CreateDefaultContainer(configuration); return(container.GetInstance <ITracerInstrumentationProvider>()); }
public void CanCreateIsolatedCacheStorageWithoutEncryption() { IsolatedStorageCacheStorageData data = new IsolatedStorageCacheStorageData("name", "", "partition"); settings.BackingStores.Add(data); IServiceLocator container = EnterpriseLibraryContainer.CreateDefaultContainer(configurationSource); IsolatedStorageBackingStore createdObject = (IsolatedStorageBackingStore)container.GetInstance <IBackingStore>("name"); Assert.IsNotNull(createdObject); }
public DatabaseHelper(string configurationFilepath = null) { if (configurationFilepath != null) { configSource = new FileConfigurationSource(configurationFilepath); dataBase = EnterpriseLibraryContainer.CreateDefaultContainer(configSource).GetInstance <Database>(); } else { dataBase = EnterpriseLibraryContainer.Current.GetInstance <Database>(); } }
public void CanBuildCustomAuthorizationProviderFromSystemConfiguration() { using (var configurationSource = new SystemConfigurationSource(false)) { IAuthorizationProvider custom = EnterpriseLibraryContainer.CreateDefaultContainer(configurationSource) .GetInstance <IAuthorizationProvider>("custom"); Assert.IsNotNull(custom); Assert.AreSame(typeof(MockCustomAuthorizationProvider), custom.GetType()); Assert.AreEqual("value1", ((MockCustomAuthorizationProvider)custom).customValue); } }
public void CanBuildDefaultLogger() { DictionaryConfigurationSource configurationSource = new DictionaryConfigurationSource(); configurationSource.Add(InstrumentationConfigurationSection.SectionName, new InstrumentationConfigurationSection(true, true, "fooApplicationName")); configurationSource.Add(CacheManagerSettings.SectionName, new CacheManagerSettings()); DefaultCachingEventLogger logger = EnterpriseLibraryContainer.CreateDefaultContainer(configurationSource).GetInstance <DefaultCachingEventLogger>(); Assert.IsNotNull(logger); }
public void CanCreateCustomCacheManager() { CustomCacheManagerData data = new CustomCacheManagerData("name", typeof(CustomCacheManager)); data.Attributes[MockCustomStorageBackingStore.AttributeKey] = "value1"; settings.CacheManagers.Add(data); IServiceLocator container = EnterpriseLibraryContainer.CreateDefaultContainer(configurationSource); CustomCacheManager createdObject = (CustomCacheManager)container.GetInstance <ICacheManager>("name"); Assert.IsNotNull(createdObject); Assert.AreEqual("value1", createdObject.customValue); }
public static void LoadConfigurationForCaching() { var builder = new ConfigurationSourceBuilder(); builder.ConfigureCaching() .ForCacheManagerNamed("MyCache") .WithOptions .UseAsDefaultCache().StoreInMemory(); var configSource = new DictionaryConfigurationSource(); builder.UpdateConfigurationWithReplace(configSource); EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource); }
/// <summary> /// Initializes a new instance of the <see cref="EntLib5Factory"/> class. /// </summary> /// <param name="EntLib5ConfigurationFile">The enterprise library 5.0 configuration file to load and watch. Supercedes any configuration found in the Config file.</param> public EntLib5Factory(string EntLib5ConfigurationFile) { // verify provided file exists var fi = new System.IO.FileInfo(EntLib5ConfigurationFile); if (fi.Exists) { var builder = new ConfigurationSourceBuilder(); var EntLib5ConfigurationSrc = new FileConfigurationSource(EntLib5ConfigurationFile, true); builder.UpdateConfigurationWithReplace(EntLib5ConfigurationSrc); EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(EntLib5ConfigurationSrc); } }
public void CanConnectToOracleAndExecuteAReader() { OracleDatabase oracleDatabase = EnterpriseLibraryContainer.CreateDefaultContainer(configurationSource) .GetInstance <OracleDatabase>("OracleTest"); DbConnection connection = oracleDatabase.CreateConnection(); Assert.IsNotNull(connection); Assert.IsTrue(connection is OracleConnection); connection.Open(); DbCommand cmd = oracleDatabase.GetSqlStringCommand("Select * from Region"); cmd.CommandTimeout = 0; }
public void setupFixture() { profile = new ProfileDTO(); profile.UserName = "******"; var conf = new ConfigurationSourceBuilder(); conf.ConfigureCaching().ForCacheManagerNamed(SecurityManager.AuthenticationCacheName).StoreInMemory(); var configSource = new DictionaryConfigurationSource(); conf.UpdateConfigurationWithReplace(configSource); EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource); }