protected override void Arrange()
        {
            base.Arrange();

            var builder = new ConfigurationSourceBuilder();

            builder.ConfigureLogging()
                .LogToCategoryNamed("General")
                    .SendTo.EventLog("Event Log Listener")
                    .FormatWith(new FormatterBuilder().TextFormatterNamed("Text Formatter"))
                    .ToLog("Application");

            builder.ConfigureExceptionHandling()
                    .GivenPolicyWithName("AllExceptions")
                        .ForExceptionType<Exception>()
                            .LogToCategory("General")
                            .ThenDoNothing()
                    .GivenPolicyWithName("OtherExceptions")
                        .ForExceptionType<ArgumentNullException>()
                            .LogToCategory("InvalidCategoryName")
                            .ThenDoNothing();


            var configuration = new DictionaryConfigurationSource();
            builder.UpdateConfigurationWithReplace(configuration);

            LoggingSection = GetSection(LoggingSettings.SectionName, configuration);
            ExceptionHandlingSection = GetSection(ExceptionHandlingSettings.SectionName, configuration);
        }
 public void RegisterEnterpriseLibrary_NullContainerBuilder()
 {
     ContainerBuilder builder = null;
     var source = new DictionaryConfigurationSource();
     Assert.Throws<ArgumentNullException>(() => builder.RegisterEnterpriseLibrary());
     Assert.Throws<ArgumentNullException>(() => builder.RegisterEnterpriseLibrary(source));
 }
        public void Setup()
        {
            var configSource = new DictionaryConfigurationSource();

            configSource.Add(DatabaseSettings.SectionName, new DatabaseSettings { DefaultDatabase = "default" });
            configSettings = new DatabaseSyntheticConfigSettings(configSource);
        }
        private void ConfigureLogging()
        {
            var configurationSource = new DictionaryConfigurationSource();
            var builder = new ConfigurationSourceBuilder();
            const string DefaultListenerName = "Default";

            builder.ConfigureLogging()
                .WithOptions
                    .DoNotRevertImpersonation()
                .SpecialSources
                    .LoggingErrorsAndWarningsCategory
                        .SendTo.SharedListenerNamed(DefaultListenerName)
                .SpecialSources
                    .UnprocessedCategory
                        .SendTo.SharedListenerNamed(DefaultListenerName)
                .SpecialSources
                    .AllEventsCategory
                        .SendTo.SharedListenerNamed(DefaultListenerName)
                .LogToCategoryNamed("General")
                    .WithOptions.SetAsDefaultCategory()
                    .SendTo.SharedListenerNamed(DefaultListenerName);
            builder.UpdateConfigurationWithReplace(configurationSource);

            var configurator = new UnityContainerConfigurator(this.Container);
            EnterpriseLibraryContainer.ConfigureContainer(configurator, configurationSource);

            this.Container.RegisterType<TraceListener, CommonLoggingEntlibTraceListener>(
                DefaultListenerName,
                new ContainerControlledLifetimeManager(),
                new InjectionFactory(this.CreateListener));
        }
        public void Then_ConfigurationSourceContainsSecuritySettings()
        {
            IConfigurationSource source = new DictionaryConfigurationSource();
            configurationSourceBuilder.UpdateConfigurationWithReplace(source);

            Assert.IsNotNull(source.GetSection(SecuritySettings.SectionName));
        }
        protected SecuritySettings GetSecuritySettings()
        {
            IConfigurationSource source = new DictionaryConfigurationSource();
            configurationSourceBuilder.UpdateConfigurationWithReplace(source);

            return (SecuritySettings)source.GetSection(SecuritySettings.SectionName);
        }
        protected override void Arrange()
        {
            base.Arrange();

            IConfigurationSource source = new DictionaryConfigurationSource();
            ConfigurationSourceBuilder sourceBuiler = new ConfigurationSourceBuilder();

            sourceBuiler.ConfigureLogging()
                .WithOptions.DisableTracing()
                .DoNotRevertImpersonation()
                .FilterOnPriority("prio filter").StartingWithPriority(10)
                .FilterOnCategory("categoryFiler").AllowAllCategoriesExcept("cat1")
                .LogToCategoryNamed("General")
                .SendTo.EventLog("Event Log Listener")
                .FormatWith(new FormatterBuilder().TextFormatterNamed("Default"))
                .LogToCategoryNamed("Critical")
                .SendTo.SharedListenerNamed("Event Log Listener")
                .SendTo.Custom<MyCustomListener>("Custom Listener")
                .SendTo.Email("Email Listener")
                .SendTo.SystemDiagnosticsListener("system diagnostics")
                .LogToCategoryNamed("msmq")
                .SendTo.Msmq("msmq");

            sourceBuiler.UpdateConfigurationWithReplace(source);
            LoggingSection = (LoggingSettings)source.GetSection(LoggingSettings.SectionName);
        }
        public void Then_ConfigurationSourceContainsTypeRegistrationProviderSettings()
        {
            IConfigurationSource source = new DictionaryConfigurationSource();
            base.ConfigurationSourceBuilder.UpdateConfigurationWithReplace(source);

            Assert.IsNotNull(source.GetSection(TypeRegistrationProvidersConfigurationSection.SectionName));
        }
 public void Setup()
 {
     container = new UnityContainer();
     var configurationSource = new DictionaryConfigurationSource();
     new UnityContainerConfigurator(container)
         .RegisterAll(configurationSource, new ValidationTypeRegistrationProvider());
 }
        public void ShouldCreateCorrectMatchingRule()
        {
            ValidationFactory.SetDefaultConfigurationValidatorFactory(new ConfigurationValidatorFactory(new DictionaryConfigurationSource()));

            PolicyData policyData = new PolicyData("Validate Parameters");
            policyData.Handlers.Add(new ValidationCallHandlerData());
            ParameterTypeMatchingRuleData matchingRuleData = GetParameterTypeMatchingRuleData();
            policyData.MatchingRules.Add(matchingRuleData);

            PolicyInjectionSettings settings = new PolicyInjectionSettings();
            settings.Policies.Add(policyData);

            DictionaryConfigurationSource configSource = new DictionaryConfigurationSource();
            configSource.Add(PolicyInjectionSettings.SectionName, settings);

            IUnityContainer container = new UnityContainer().AddNewExtension<Interception>();
            settings.ConfigureContainer(container);

            RuleDrivenPolicy policy = container.Resolve<RuleDrivenPolicy>("Validate Parameters");
            List<IMatchingRule> rules = RuleCreationFixture.GetRules(policy);

            Assert.IsNotNull(policy);
            Assert.IsTrue(rules[0] is ParameterTypeMatchingRule);
            ParameterTypeMatchingRule rule = (ParameterTypeMatchingRule)(rules[0]);
            Assert.AreEqual(3, rule.ParameterMatches.Count());
            for (int i = 0; i < matchingRuleData.Matches.Count; ++i)
            {
                AssertMatchDataEqual(
                    matchingRuleData.Matches[i],
                    rule.ParameterMatches.ElementAt(i),
                    "Mismatch at element {0}",
                    i);
            }
        }
 public void SetUp()
 {
     factory = new MockAssembledObjectFactory();
     context = new MockBuilderContext();
     configurationSource = new DictionaryConfigurationSource();
     reflectionCache = new ConfigurationReflectionCache();
 }
        public void Setup()
        {
            var configSource = new DictionaryConfigurationSource();

            configSource.Add(DatabaseSettings.SectionName, new DatabaseSettings());
            configSettings = new DatabaseSyntheticConfigSettings(configSource.GetSection);
        }
        public void ManageabilityProviderGeneratesProperAdmContent()
        {
            DictionaryConfigurationSource configurationSource = new DictionaryConfigurationSource();

            configurationObject.Type = typeof(object);

            MockAdmContentBuilder contentBuilder = new MockAdmContentBuilder();

            contentBuilder.StartCategory("category");
            provider.AddAdministrativeTemplateDirectives(contentBuilder, configurationObject, configurationSource, "TestApp");
            contentBuilder.EndCategory();

            MockAdmContent content = contentBuilder.GetMockContent();
            IEnumerator<AdmCategory> categoriesEnumerator = content.Categories.GetEnumerator();
            categoriesEnumerator.MoveNext();
            IEnumerator<AdmPolicy> policiesEnumerator = categoriesEnumerator.Current.Policies.GetEnumerator();
            Assert.IsTrue(policiesEnumerator.MoveNext());
            IEnumerator<AdmPart> partsEnumerator = policiesEnumerator.Current.Parts.GetEnumerator();
            Assert.IsTrue(partsEnumerator.MoveNext());
            Assert.AreSame(typeof(AdmEditTextPart), partsEnumerator.Current.GetType());
            Assert.IsNull(((AdmEditTextPart)partsEnumerator.Current).KeyName);
            Assert.IsTrue(partsEnumerator.MoveNext());
            Assert.AreSame(typeof(AdmEditTextPart), partsEnumerator.Current.GetType());
            Assert.IsNull(((AdmEditTextPart)partsEnumerator.Current).KeyName);
            Assert.IsFalse(partsEnumerator.MoveNext());
            Assert.IsFalse(policiesEnumerator.MoveNext());
        }
        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.");

        }
        private void ConfigureExceptionHandling()
        {
            var configurationSource = new DictionaryConfigurationSource();
            var builder = new ConfigurationSourceBuilder();
            builder
                .ConfigureExceptionHandling()
                .GivenPolicyWithName(DefaultPolicy)
                    .ForExceptionType<DeleteConstraintException>()
                        .HandleCustom<HttpErrorExceptionHandler>()
                        .ThenThrowNewException()
                    .ForExceptionType<BusinessValidationException>()
                        .HandleCustom<BusinessValidationExceptionHandler>()
                        .ThenThrowNewException()
                    .ForExceptionType<BusinessException>()
                        .HandleCustom<HttpErrorExceptionHandler>()
                        .ThenThrowNewException()
                    .ForExceptionType<Exception>()
                        .LogToCategory("General")
                            .WithSeverity(TraceEventType.Critical)
                            .UsingExceptionFormatter<TextExceptionFormatter>()
                        .HandleCustom(
                            typeof(HttpErrorExceptionHandler),
                            new NameValueCollection
                                {
                                    { HttpErrorExceptionHandler.StatusCodeKey, HttpStatusCode.InternalServerError.ToString("G") },
                                    { HttpErrorExceptionHandler.MessageKey, "An error has occurred while consuming this service. Please contact your administrator for more information." },
                                    { HttpErrorExceptionHandler.AppendHandlingIdKey, bool.TrueString }
                                })
                        .ThenThrowNewException();
            builder.UpdateConfigurationWithReplace(configurationSource);

            var configurator = new UnityContainerConfigurator(this.Container);
            EnterpriseLibraryContainer.ConfigureContainer(configurator, configurationSource);
        }
		public static DictionaryConfigurationSource GenerateConfiguration()
		{
			DictionaryConfigurationSource sections = new DictionaryConfigurationSource();
			sections.Add(DatabaseSettings.SectionName, GenerateDatabaseSettings());
			sections.Add(CacheManagerSettings.SectionName, GenerateCacheManagerSettings());
			return sections;
		}
        public void Then_ConfigurationSourceContainsLoggingSettings()
        {
            var configurationSource = new DictionaryConfigurationSource();
            ConfigurationSourceBuilder.UpdateConfigurationWithReplace(configurationSource);

            Assert.IsNotNull(configurationSource.GetSection(LoggingSettings.SectionName));
        }
        protected override void Arrange()
        {
            base.Arrange();

            validator = new LogFormatterValidator();

            errors = new List<ValidationResult>();

            IConfigurationSource source = new DictionaryConfigurationSource();
            ConfigurationSourceBuilder sourceBuiler = new ConfigurationSourceBuilder();

            sourceBuiler.ConfigureExceptionHandling()
                            .GivenPolicyWithName("policy")
                                .ForExceptionType<Exception>()
                                    .LogToCategory("category")
                                        .UsingExceptionFormatter<BadImageFormatException>();

            sourceBuiler.UpdateConfigurationWithReplace(source);

            ExceptionHandlingSettings EhabSettings = (ExceptionHandlingSettings)source.GetSection(ExceptionHandlingSettings.SectionName);

            var sectionModel = SectionViewModel.CreateSection(Container, "Ehab Section", EhabSettings);

            properties = sectionModel.GetDescendentsOfType<LoggingExceptionHandlerData>().First().Properties;
        }
        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);
        }
        private void ConfigureExceptionHandling()
        {
            var configurationSource = new DictionaryConfigurationSource();
            var builder = new ConfigurationSourceBuilder();
            builder
                .ConfigureExceptionHandling()
                .GivenPolicyWithName(ValidationPolicy)
                    .ForExceptionType<DeleteConstraintException>()
                        .HandleCustom<BusinessValidationHandler>()
                        .ThenThrowNewException()
                    .ForExceptionType<BusinessValidationException>()
                        .ThenNotifyRethrow()
                    .ForExceptionType<BusinessException>()
                        .HandleCustom<BusinessValidationHandler>()
                        .ThenThrowNewException()
                .GivenPolicyWithName(DefaultPolicy)
                    .ForExceptionType<Exception>()
                        .LogToCategory("General")
                            .WithSeverity(TraceEventType.Critical)
                            .UsingExceptionFormatter<TextExceptionFormatter>()
                        .WrapWith<Exception>()
                            .UsingMessage("An error has occurred while processing request. Please contact your administrator for more information. [Error ID: {handlingInstanceID}]")
                        .ThenThrowNewException();
            builder.UpdateConfigurationWithReplace(configurationSource);

            var configurator = new UnityContainerConfigurator(this.Container);
            EnterpriseLibraryContainer.ConfigureContainer(configurator, configurationSource);
        }
Beispiel #21
0
        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 FailsGetConnectionStringIfConnectionStringDoesNotExist()
		{
			DictionaryConfigurationSource configurationSource = new DictionaryConfigurationSource();
			DatabaseConfigurationView view = new DatabaseConfigurationView(configurationSource);

			view.GetConnectionStringSettings(unknownConnectionName);
		}
        protected override void Arrange()
        {
            base.Arrange();

            var builder = new ConfigurationSourceBuilder();
            builder.ConfigureLogging()
                        .LogToCategoryNamed("category")
                            .SendTo
                                .EventLog("listener")
                        .SpecialSources
                            .AllEventsCategory
                                .SendTo
                                    .EventLog("listener")
                        .SpecialSources
                            .LoggingErrorsAndWarningsCategory
                                .SendTo
                                    .EventLog("listener")
                        .SpecialSources
                            .UnprocessedCategory
                                .SendTo
                                    .EventLog("listener");


            var source = new DictionaryConfigurationSource();
            builder.UpdateConfigurationWithReplace(source);

            ElementLookup = Container.Resolve<ElementLookup>();
            LoggingSection = (LoggingSettings)source.GetSection(LoggingSettings.SectionName);
        }
        protected IConfigurationSource GetConfigurationSource()
        {
            IConfigurationSource configurationSource = new DictionaryConfigurationSource();
            ConfigurationSourceBuilder.UpdateConfigurationWithReplace(configurationSource);

            return configurationSource;
        }
        public void RequestForNullNameThrows()
        {
            DictionaryConfigurationSource configurationSource = new DictionaryConfigurationSource();
            DatabaseConfigurationView view = new DatabaseConfigurationView(configurationSource);

            view.GetConnectionStringSettings(null);
        }
        public void SkipsConnectionStringsWithoutProviderNamesOrWithProviderNamesWhichDoNotMapToAProviderFactory()
        {
            DictionaryConfigurationSource configurationSource = new DictionaryConfigurationSource();
            ConnectionStringsSection section = new ConnectionStringsSection();
            section.ConnectionStrings.Add(new ConnectionStringSettings("cs1", "cs1", "System.Data.SqlClient"));
            section.ConnectionStrings.Add(new ConnectionStringSettings("cs2", "cs2"));
            section.ConnectionStrings.Add(new ConnectionStringSettings("cs3", "cs3", "a bogus provider name"));
            section.ConnectionStrings.Add(new ConnectionStringSettings("cs4", "cs4", "System.Data.SqlClient"));
            configurationSource.Add("connectionStrings", section);

            var factory = new DatabaseProviderFactory(configurationSource.GetSection);

            Assert.AreEqual("cs1", factory.Create("cs1").ConnectionString);
            Assert.AreEqual("cs4", factory.Create("cs4").ConnectionString);
            try
            {
                factory.Create("cs2");
                Assert.Fail("should have thrown");
            }
            catch (InvalidOperationException)
            {
                // expected, connection string is ignored
            }

            try
            {
                factory.Create("cs3");
                Assert.Fail("should have thrown");
            }
            catch (InvalidOperationException)
            {
                // expected, connection string is ignored
            }
        }
Beispiel #27
0
        static void LogWithFluentInterface(CustomLogEntry logEntry)
        {
            var builder = new ConfigurationSourceBuilder();

            builder.ConfigureData()
                .ForDatabaseNamed("Logging")
                    .ThatIs.ASqlDatabase()
                    .WithConnectionString(@"data source=.\SQLEXPRESS;Integrated Security=SSPI;Database=Logging")
                .AsDefault();

            builder.ConfigureLogging()
                    .WithOptions
                        .DoNotRevertImpersonation()
                    .LogToCategoryNamed("General")
                        .WithOptions.SetAsDefaultCategory()
                        .SendTo.CustomDatabase("Custom Database Trace Listener")
                        .WithAddCategoryStoredProcedure("AddCategory")
                        .UseDatabase("Logging")
                        .Filter(System.Diagnostics.SourceLevels.All)
                        .WithWriteLogStoredProcedure("WriteLog")
                        .FormatWithSharedFormatter("Text Formatter")
                    .SpecialSources.LoggingErrorsAndWarningsCategory
                        .SendTo.EventLog("Event Log Listener")
                        .FormatWith(new FormatterBuilder()
                             .TextFormatterNamed("Text Formatter")
                               .UsingTemplate(@"Timestamp: {timestamp}{newline}
            Message: {message}{newline}
            Category: {category}{newline}
            Priority: {priority}{newline}
            EventId: {eventid}{newline}
            Severity: {severity}{newline}
            Title:{title}{newline}
            Machine: {localMachine}{newline}
            App Domain: {localAppDomain}{newline}
            ProcessId: {localProcessId}{newline}
            Process Name: {localProcessName}{newline}
            Thread Name: {threadName}{newline}
            Win32 ThreadId:{win32ThreadId}{newline}
            Extended Properties: {dictionary({key} - {value}{newline})}"))
                            .ToLog("Application")
                            .ToMachine(".")
                            .UsingEventLogSource("Enterprise Library Logging")
                            .Filter(SourceLevels.All)
                            ;

            var configSource = new DictionaryConfigurationSource();
            builder.UpdateConfigurationWithReplace(configSource);

            var dbProviderFactory = new DatabaseProviderFactory(configSource);
            DatabaseFactory.SetDatabaseProviderFactory(dbProviderFactory, false);

            var logWriterFactory = new LogWriterFactory(configSource);
            var logWriter = logWriterFactory.Create();
            logWriter.Write(logEntry);

            // Re-initialize static Logger
            Logger.SetLogWriter(logWriter, false);
            Logger.Write("Test2", "General");
        }
 public void CreateConfigurationSource()
 {
     instrumentationConfigurationSource = new DictionaryConfigurationSource();
     instrumentationConfigurationSource.Add(InstrumentationConfigurationSection.SectionName,
                                            new InstrumentationConfigurationSection(true, true, true));
     strategy = new InstrumentationAttachmentStrategy();
     reflectionCache = new ConfigurationReflectionCache();
 }
        protected ExceptionPolicyData GetExceptionPolicyData()
        {
            var source = new DictionaryConfigurationSource();
            configurationSourceBuilder.UpdateConfigurationWithReplace(source);

            return ((ExceptionHandlingSettings)source.GetSection(ExceptionHandlingSettings.SectionName))
                .ExceptionPolicies.Get(policyName);
        }
 public static DictionaryConfigurationSource GenerateConfiguration()
 {
     DictionaryConfigurationSource source = new DictionaryConfigurationSource();
     source.Add(DatabaseSettings.SectionName, GenerateDatabaseSettings());
     source.Add(OracleConnectionSettings.SectionName, GenerateOracleConnectionSettings());
     source.Add("connectionStrings", GenerateConnectionStringSection());
     return source;
 }