Example #1
0
        public void GetConnectionSdfAndMdfFile_MdfFileWins()
        {
            // Arrange
            var mockSdfHandler = new Mock <MockDbFileHandler>();

            mockSdfHandler.Setup(m => m.GetConnectionConfiguration(@"DataDirectory\Bar.sdf")).Returns(new MockConnectionConfiguration("sdf connection"));
            var mockMdfHandler = new Mock <MockDbFileHandler>();

            mockMdfHandler.Setup(m => m.GetConnectionConfiguration(@"DataDirectory\Bar.mdf")).Returns(new MockConnectionConfiguration("mdf connection"));
            var handlers = new Dictionary <string, IDbFileHandler>
            {
                { ".sdf", mockSdfHandler.Object },
                { ".mdf", mockMdfHandler.Object },
            };
            var configManager = new ConfigurationManagerWrapper(handlers, "DataDirectory");
            Func <string, bool> fileExists = path => path.Equals(@"DataDirectory\Bar.mdf") ||
                                             path.Equals(@"DataDirectory\Bar.sdf");
            Func <string, IConnectionConfiguration> getFromConfig = name => null;

            // Act
            IConnectionConfiguration configuration = configManager.GetConnection("Bar", getFromConfig, fileExists);

            // Assert
            Assert.NotNull(configuration);
            Assert.Equal("mdf connection", configuration.ConnectionString);
        }
		public virtual void Configure(IEngine engine, EventBroker broker, ConfigurationManagerWrapper configuration)
		{
			engine.Container.AddComponentInstance("n2.configuration", typeof(ConfigurationManagerWrapper), configuration);
			engine.Container.AddComponentInstance("n2.engine", typeof(IEngine), engine);
			engine.Container.AddComponentInstance("n2.container", typeof(IServiceContainer), engine.Container);
			engine.Container.AddComponentInstance("n2.containerConfigurer", typeof(ContainerConfigurer), this);

			AddComponentInstance(engine.Container, configuration.GetConnectionStringsSection());
			AddComponentInstance(engine.Container, configuration.Sections.Engine);
			RegisterConfiguredComponents(engine.Container, configuration.Sections.Engine);
			AddComponentInstance(engine.Container, configuration.Sections.Web);
			InitializeEnvironment(engine.Container, configuration.Sections);
			AddComponentInstance(engine.Container, configuration.Sections.Database);
			AddComponentInstance(engine.Container, configuration.Sections.Management);

			AddComponentInstance(engine.Container, broker);

			var skipTypes = configuration.Sections.Engine.Components.GetConfiguredServiceTypes();
			AddComponentUnlessConfigured(engine.Container, typeof(BasicTemporaryFileHelper), typeof(BasicTemporaryFileHelper), skipTypes);
			AddComponentUnlessConfigured(engine.Container, typeof(TypeCache), typeof(TypeCache), skipTypes);
			AddComponentUnlessConfigured(engine.Container, typeof(ITypeFinder), typeof(WebAppTypeFinder), skipTypes);
			AddComponentUnlessConfigured(engine.Container, typeof(ServiceRegistrator), typeof(ServiceRegistrator), skipTypes);

			var registrator = engine.Container.Resolve<ServiceRegistrator>();
			var services = registrator.FindServices();
			var configurationKeys = configuration.GetComponentConfigurationKeys();
			services = registrator.FilterServices(services, configurationKeys);
			services = registrator.FilterServices(services, skipTypes);
			registrator.RegisterServices(services);

			InitializeUrlParser(engine.Container);
		}
Example #3
0
        public void ProvideConfigurationSource()
        {
            var manager = new ConfigurationManagerWrapper();
            IConfigurationSource source = new ConfigurationSource(manager, config => new ConfigurationWrapper(config));

            _container.RegisterInstanceAs(source);
        }
Example #4
0
        public CommandFactory(IPersister persister, ISecurityManager security, IVersionManager versionMaker, IEditUrlManager editUrlManager, IContentAdapterProvider adapters, StateChanger changer)
        {
            this.persister = persister;
            this.security  = security;

            config = new ConfigurationManagerWrapper();

            makeVersionOfMaster = On.Master(new MakeVersionCommand(versionMaker));
            replaceMaster       = new ReplaceMasterCommand(versionMaker);
            makeVersion         = new MakeVersionCommand(versionMaker);
            useNewVersion       = new UseDraftCommand(versionMaker);
            updateObject        = new UpdateObjectCommand();
            delete               = new DeleteCommand(persister.Repository);
            showEdit             = new RedirectToEditCommand(editUrlManager);
            useMaster            = new UseMasterCommand();
            clone                = new CloneCommand();
            validate             = new ValidateCommand();
            save                 = new SaveCommand(persister);
            draftState           = new UpdateContentStateCommand(changer, ContentState.Draft);
            publishedState       = new UpdateContentStateCommand(changer, ContentState.Published);
            unpublishedState     = new UpdateContentStateCommand(changer, ContentState.Unpublished);
            schedulePublishState = new UpdateContentStateSchedulePublishCommand(changer);
            saveActiveContent    = new ActiveContentSaveCommand();
            moveToPosition       = new MoveToPositionCommand();
            unpublishedDate      = new EnsureNotPublishedCommand();
            ensurePublishedDate  = new EnsurePublishedCommand();
            updateReferences     = new UpdateReferencesCommand();
            saveOnPageVersion    = new SaveOnPageVersionCommand(versionMaker);
        }
Example #5
0
		public virtual void Configure(IEngine engine, EventBroker broker, ConfigurationManagerWrapper configuration)
		{
			engine.Container.AddComponentInstance("n2.configuration", typeof(ConfigurationManagerWrapper), configuration);
			engine.Container.AddComponentInstance("n2.engine", typeof(IEngine), engine);
			engine.Container.AddComponentInstance("n2.container", typeof(IServiceContainer), engine.Container);
			engine.Container.AddComponentInstance("n2.containerConfigurer", typeof(ContainerConfigurer), this);

			AddComponentInstance(engine.Container, configuration.GetConnectionStringsSection());
			AddComponentInstance(engine.Container, configuration.Sections.Engine);
			RegisterConfiguredComponents(engine.Container, configuration.Sections.Engine);
			AddComponentInstance(engine.Container, configuration.Sections.Web);
			InitializeEnvironment(engine.Container, configuration.Sections);
			AddComponentInstance(engine.Container, configuration.Sections.Database);
			AddComponentInstance(engine.Container, configuration.Sections.Management);

			AddComponentInstance(engine.Container, broker);

			var skipTypes = configuration.Sections.Engine.Components.GetConfiguredServiceTypes();
			AddComponentUnlessConfigured(engine.Container, typeof(BasicTemporaryFileHelper), typeof(BasicTemporaryFileHelper), skipTypes);
			AddComponentUnlessConfigured(engine.Container, typeof(TypeCache), typeof(TypeCache), skipTypes);
			AddComponentUnlessConfigured(engine.Container, typeof(ITypeFinder), typeof(WebAppTypeFinder), skipTypes);
			AddComponentUnlessConfigured(engine.Container, typeof(ServiceRegistrator), typeof(ServiceRegistrator), skipTypes);

			var registrator = engine.Container.Resolve<ServiceRegistrator>();
			var services = registrator.FindServices();
			var configurationKeys = configuration.GetComponentConfigurationKeys();
			services = registrator.FilterServices(services, configurationKeys);
			services = registrator.FilterServices(services, skipTypes);
			registrator.RegisterServices(services);

			InitializeUrlParser(engine.Container);
		}
        public virtual void Configure(IEngine engine, EventBroker broker, ConfigurationManagerWrapper configuration)
        {
            configuration.Start();
            engine.Container.AddComponentInstance("n2.configuration", typeof(ConfigurationManagerWrapper), configuration);
            engine.Container.AddComponentInstance("n2.engine", typeof(IEngine), engine);
            engine.Container.AddComponentInstance("n2.container", typeof(IServiceContainer), engine.Container);
            engine.Container.AddComponentInstance("n2.containerConfigurer", typeof(ContainerConfigurer), this);

            AddComponentInstance(engine.Container, configuration.GetConnectionStringsSection());
            AddComponentInstance(engine.Container, configuration.Sections.Engine);
            if (configuration.Sections.Engine != null)
                RegisterConfiguredComponents(engine.Container, configuration.Sections.Engine);
            AddComponentInstance(engine.Container, configuration.Sections.Web);
            if (configuration.Sections.Web != null)
                InitializeEnvironment(engine.Container, configuration.Sections);
            AddComponentInstance(engine.Container, configuration.Sections.Database);
            AddComponentInstance(engine.Container, configuration.Sections.Management);

            AddComponentInstance(engine.Container, broker);

            engine.Container.AddComponent("n2.typeFinder", typeof(ITypeFinder), typeof(WebAppTypeFinder));
            engine.Container.AddComponent("n2.webContext", typeof(N2.Web.IWebContext), typeof(N2.Web.AdaptiveContext));
            engine.Container.AddComponent("n2.serviceRegistrator", typeof(ServiceRegistrator), typeof(ServiceRegistrator));

            var registrator = engine.Container.Resolve<ServiceRegistrator>();
            var services = registrator.FindServices();
            var configurationKeys = GetComponentConfigurationKeys(configuration);
            services = registrator.FilterServices(services, configurationKeys);
            registrator.RegisterServices(services);
        }
        public void AppSettings_ShouldCallAppSettingsOfTheWrappedConfigurationManager()
        {
            using(ShimsContext.Create())
            {
                bool appSettingsIsCalled = false;
                var shimAppSettings = new NameValueCollection
                {
                    {"TestName", "TestValue"}
                };

                ShimConfigurationManager.AppSettingsGet = delegate
                {
                    appSettingsIsCalled = true;
                    return shimAppSettings;
                };

                Assert.IsFalse(appSettingsIsCalled);

                var appSettings = new ConfigurationManagerWrapper().AppSettings;

                Assert.AreEqual(shimAppSettings, appSettings);
                Assert.AreEqual(1, appSettings.Count);
                Assert.AreEqual(shimAppSettings[0], appSettings[0]);
                Assert.IsTrue(appSettingsIsCalled);
            }
        }
        public void ConnectionStrings_ShouldCallConnectionStringsOfTheWrappedConfigurationManager()
        {
            using(ShimsContext.Create())
            {
                bool connectionStringsIsCalled = false;
                var shimConnectionStrings = new ConnectionStringSettingsCollection
                {
                    new ConnectionStringSettings("ConnectionName", "ConnectionStringValue")
                };

                ShimConfigurationManager.ConnectionStringsGet = delegate
                {
                    connectionStringsIsCalled = true;
                    return shimConnectionStrings;
                };

                Assert.IsFalse(connectionStringsIsCalled);

                var connectionStrings = new ConfigurationManagerWrapper().ConnectionStrings.ToArray();

                Assert.AreEqual(1, connectionStrings.Count());
                Assert.AreEqual(shimConnectionStrings[0], connectionStrings.ElementAt(0));
                Assert.IsTrue(connectionStringsIsCalled);
            }
        }
Example #9
0
		/// <summary>
		/// Initializes a new instance of the <see cref="Slug"/> class.
		/// </summary>
		/// <param name="configuration">
		/// Configuration from web.config
		/// </param>
		/// <exception cref="ArgumentNullException">
		/// If configuration is null
		/// </exception>
		public Slug(ConfigurationManagerWrapper configuration)
		{
			if (configuration == null)
			{
				throw new ArgumentNullException("configuration");
			}

			NameEditorElement nameEditorElement = configuration.Sections.Management.NameEditor;

			// start with empty collection
			this.replacementPatterns.Clear();

			// first add any replacements from custom configuration, which will be applied first
			foreach (PatternValueElement element in nameEditorElement.Replacements.AllElements)
			{
				this.replacementPatterns.Add(element);
			}

			// then, add system replacements inserted from constructor
			foreach (PatternValueElement element in new PatternValueCollection())
			{
				this.replacementPatterns.Add(element);
			}

			this.whitespaceReplacement = nameEditorElement.WhitespaceReplacement;
			this.toLower = nameEditorElement.ToLower;
		}
Example #10
0
        private Slug CreateCustomReplacementSlug()
        {
            PatternValueCollection patterns = new PatternValueCollection();

            patterns.Clear();             // to remove all those added by constructor
            patterns.Add(new PatternValueElement("c1", "[@]", "at", true));

            NameEditorElement nameEditorElement = new NameEditorElement
            {
                // WhitespaceReplacement = '-',
                Replacements = patterns //,
                                        // ToLower = true
            };

            EditSection editSection = new EditSection {
                NameEditor = nameEditorElement
            };

            ConfigurationManagerWrapper cmw = new ConfigurationManagerWrapper
            {
                Sections = new ConfigurationManagerWrapper.ContentSectionTable(null, null, null, editSection)
            };

            return(new Slug(cmw));
        }
        protected virtual void InitializeEnvironment(IServiceContainer container, ConfigurationManagerWrapper.ContentSectionTable config)
        {
            if (config.Web != null)
            {
                Url.DefaultExtension = config.Web.Web.Extension;
                PathData.PageQueryKey = config.Web.Web.PageQueryKey;
                PathData.ItemQueryKey = config.Web.Web.ItemQueryKey;
                PathData.PartQueryKey = config.Web.Web.PartQueryKey;
                PathData.PathKey = config.Web.Web.PathDataKey;

                if (!config.Web.Web.IsWeb)
                    container.AddComponentInstance("n2.webContext.notWeb", typeof(IWebContext), new ThreadContext());

                if (config.Web.Web.Urls.EnableCaching)
                    container.AddComponent("n2.web.cachingUrlParser", typeof(IUrlParser), typeof(CachingUrlParserDecorator));

                if (config.Web.MultipleSites)
                    container.AddComponent("n2.multipleSitesParser", typeof(IUrlParser), typeof(MultipleSitesParser));
                else
                    container.AddComponent("n2.urlParser", typeof(IUrlParser), typeof(UrlParser));
            }
            if (config.Management != null)
            {
                SelectionUtility.SelectedQueryKey = config.Management.Paths.SelectedQueryKey;
                Url.SetToken("{Selection.SelectedQueryKey}", SelectionUtility.SelectedQueryKey);
            }
        }
Example #12
0
        public void GetConnectionGetsConnectionFromDataDirectoryIfFileWithSupportedExtensionExists()
        {
            // Arrange
            var mockHandler = new Mock <MockDbFileHandler>();

            mockHandler
            .Setup(m => m.GetConnectionConfiguration(@"DataDirectory\Bar.foo"))
            .Returns(new MockConnectionConfiguration("some file based connection"));
            var handlers = new Dictionary <string, IDbFileHandler>
            {
                { ".foo", mockHandler.Object }
            };
            var configManager = new ConfigurationManagerWrapper(handlers, "DataDirectory");
            Func <string, bool> fileExists = path => path.Equals(@"DataDirectory\Bar.foo");
            Func <string, IConnectionConfiguration> getFromConfig = name => null;

            // Act
            IConnectionConfiguration configuration = configManager.GetConnection(
                "Bar",
                getFromConfig,
                fileExists
                );

            // Assert
            Assert.NotNull(configuration);
            Assert.Equal("some file based connection", configuration.ConnectionString);
        }
        public virtual void Configure(IEngine engine, EventBroker broker, ConfigurationManagerWrapper configuration)
        {
            configuration.Start();
            engine.Container.AddComponentInstance("n2.configuration", typeof(ConfigurationManagerWrapper), configuration);
            engine.Container.AddComponentInstance("n2.engine", typeof(IEngine), engine);
            engine.Container.AddComponentInstance("n2.container", typeof(IServiceContainer), engine.Container);
            engine.Container.AddComponentInstance("n2.containerConfigurer", typeof(ContainerConfigurer), this);

            AddComponentInstance(engine.Container, configuration.GetConnectionStringsSection());
            AddComponentInstance(engine.Container, configuration.Sections.Engine);
            if (configuration.Sections.Engine != null)
            {
                RegisterConfiguredComponents(engine.Container, configuration.Sections.Engine);
            }
            AddComponentInstance(engine.Container, configuration.Sections.Web);
            if (configuration.Sections.Web != null)
            {
                InitializeEnvironment(engine.Container, configuration.Sections);
            }
            AddComponentInstance(engine.Container, configuration.Sections.Database);
            AddComponentInstance(engine.Container, configuration.Sections.Management);

            AddComponentInstance(engine.Container, broker);

            engine.Container.AddComponent("n2.typeFinder", typeof(ITypeFinder), typeof(WebAppTypeFinder));
            engine.Container.AddComponent("n2.webContext", typeof(N2.Web.IWebContext), typeof(N2.Web.AdaptiveContext));
            engine.Container.AddComponent("n2.serviceRegistrator", typeof(ServiceRegistrator), typeof(ServiceRegistrator));

            var registrator       = engine.Container.Resolve <ServiceRegistrator>();
            var services          = registrator.FindServices();
            var configurationKeys = GetComponentConfigurationKeys(configuration);

            services = registrator.FilterServices(services, configurationKeys);
            registrator.RegisterServices(services);
        }
Example #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Slug"/> class.
        /// </summary>
        /// <param name="configuration">
        /// Configuration from web.config
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// If configuration is null
        /// </exception>
        public Slug(ConfigurationManagerWrapper configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            NameEditorElement nameEditorElement = configuration.Sections.Management.NameEditor;

            // start with empty collection
            this.replacementPatterns.Clear();

            // first add any replacements from custom configuration, which will be applied first
            foreach (PatternValueElement element in nameEditorElement.Replacements.AllElements)
            {
                this.replacementPatterns.Add(element);
            }

            // then, add system replacements inserted from constructor
            foreach (PatternValueElement element in new PatternValueCollection())
            {
                this.replacementPatterns.Add(element);
            }

            this.whitespaceReplacement = nameEditorElement.WhitespaceReplacement;
            this.toLower = nameEditorElement.ToLower;
        }
        public DependencyResolverFactory(string appSettingKey)
        {
            Check.Argument.IsNotEmpty(appSettingKey, "appSettingKey");

            string resolverTypeName = new ConfigurationManagerWrapper().AppSettings[appSettingKey];
            _resolverType = Type.GetType(resolverTypeName, true, true);
        }
        public void GetUnitySection()
        {
            var cmw = new ConfigurationManagerWrapper();

            var section = cmw.GetSection <UnityConfigurationSection>("unity");

            Assert.IsNotNull(section);
        }
Example #17
0
        public void get_appsetting_of_boolean_and_return_the_expected_boolean_value()
        {
            // Arrange
            var wrapper = new ConfigurationManagerWrapper();

            // Act
            // Assert
            wrapper.GetSetting <bool>("IsValue").Should().BeTrue();
        }
 internal static void Initialize()
 {
     IConfigurationManager configurationManager = new ConfigurationManagerWrapper();
     IWebProjectPathFinder webProjectPathFinder = new WebProjectPathFinder();
     IWebServerSettings webServerSettings = new WebServerSettings(configurationManager, webProjectPathFinder);
     WebServerFactory.Initialize(webServerSettings);
     WebServerFactory.RegisterWebServer<IISExpressWebServer>();
     WebServerFactory.RegisterWebServer<RemoteWebServer>();
 }
Example #19
0
        public void get_appsetting_of_int_and_return_the_expected_int_value()
        {
            // Arrange
            var wrapper = new ConfigurationManagerWrapper();

            // Act
            // Assert
            wrapper.GetSetting <int>("Timeout").Should().Be(10);
        }
Example #20
0
        public void get_appsetting_with_custom_section_of_int_and_return_the_expected_int_value()
        {
            // Arrange
            var wrapper = new ConfigurationManagerWrapper();

            // Act
            // Assert
            wrapper.GetSetting <int>("IntValue", "customSection").Should().Be(10);
        }
		public StatisticsTransferScheduledAction(Collector filler, StatisticsRepository repository, ConfigurationManagerWrapper config)
		{
			var section = config.GetContentSection<StatisticsSection>("statistics", required: false);
			MemoryFlushInterval = section.MemoryFlushInterval;
			TransferInterval = section.TransferInterval;
			StatisticsGranularity = section.Granularity;
			this.filler = filler;
			this.repository = repository;
		}
Example #22
0
        public MasterPageConcern(ConfigurationManagerWrapper configuration)
        {
            var section = configuration.GetContentSection <TemplatesSection>("templates");

            if (section != null)
            {
                masterPageFile = section.MasterPageFile;
            }
        }
        internal static void Initialize()
        {
            IConfigurationManager configurationManager = new ConfigurationManagerWrapper();
            IWebProjectPathFinder webProjectPathFinder = new WebProjectPathFinder();
            IWebServerSettings    webServerSettings    = new WebServerSettings(configurationManager, webProjectPathFinder);

            WebServerFactory.Initialize(webServerSettings);
            WebServerFactory.RegisterWebServer <IISExpressWebServer>();
            WebServerFactory.RegisterWebServer <RemoteWebServer>();
        }
Example #24
0
        public void get_app_setting_with_an_unknown_key_throws_exception()
        {
            // Arrange
            var wrapper = new ConfigurationManagerWrapper();

            // Act
            Action ex = () => wrapper.GetSetting <bool>("Unknown");

            // Assert
            ex.ShouldThrow <ArgumentException>().WithMessage("Specified key (Unknown) not found or empty.");
        }
Example #25
0
 /// <summary>Creates a new instance of the RequestLifeCycleHandler class.</summary>
 /// <param name="webContext">The web context wrapper.</param>
 /// <param name="broker"></param>
 /// <param name="dispatcher"></param>
 /// <param name="adapters"></param>
 /// <param name="errors"></param>
 /// <param name="configuration"></param>
 public RequestLifeCycleHandler(IWebContext webContext, EventBroker broker, RequestPathProvider dispatcher, IContentAdapterProvider adapters, IErrorNotifier errors,
     ConfigurationManagerWrapper configuration)
 {
     rewriteMethod = configuration.Sections.Web.Web.Rewrite;
     managementUrl = configuration.Sections.Management.ManagementInterfaceUrl;
     this.webContext = webContext;
     this.broker = broker;
     this.adapters = adapters;
     this.errors = errors;
     this.dispatcher = dispatcher;
 }
Example #26
0
        public void get_appsetting_with_unknown_custom_section_throws_exception()
        {
            // Arrange
            var wrapper = new ConfigurationManagerWrapper();

            // Act
            Action ex = () => wrapper.GetSetting <int>(string.Empty, "unknown");

            // Assert
            ex.ShouldThrow <ArgumentException>().WithMessage("Section unknown is not found in configuration");
        }
Example #27
0
        public void has_connection_string_with_unknown_connection_name_returns_false()
        {
            // Arrange
            var wrapper = new ConfigurationManagerWrapper();

            // Act
            var result = wrapper.HasConnectionString("someconnection");

            // Assert
            result.Should().BeFalse();
        }
        protected virtual string[] GetComponentConfigurationKeys(ConfigurationManagerWrapper configuration)
        {
            List<string> configurationKeys = new List<string>();

            configuration.Sections.Database.ApplyComponentConfigurationKeys(configurationKeys);
            configuration.Sections.Management.ApplyComponentConfigurationKeys(configurationKeys);
            configuration.Sections.Web.ApplyComponentConfigurationKeys(configurationKeys);
            configuration.Sections.Engine.ApplyComponentConfigurationKeys(configurationKeys);

            return configurationKeys.ToArray();
        }
 /// <summary>Creates a new instance of the RequestLifeCycleHandler class.</summary>
 /// <param name="webContext">The web context wrapper.</param>
 /// <param name="broker"></param>
 /// <param name="dispatcher"></param>
 /// <param name="adapters"></param>
 /// <param name="errors"></param>
 /// <param name="configuration"></param>
 public RequestLifeCycleHandler(IWebContext webContext, EventBroker broker, RequestPathProvider dispatcher, IContentAdapterProvider adapters, IErrorNotifier errors,
                                ConfigurationManagerWrapper configuration)
 {
     rewriteMethod   = configuration.Sections.Web.Web.Rewrite;
     managementUrl   = configuration.Sections.Management.Paths.ManagementInterfaceUrl;
     this.webContext = webContext;
     this.broker     = broker;
     this.adapters   = adapters;
     this.errors     = errors;
     this.dispatcher = dispatcher;
 }
Example #30
0
        public void has_connection_string_with_null_or_empty_name_returns_false(string name)
        {
            // Arrange
            var wrapper = new ConfigurationManagerWrapper();

            // Act
            var result = wrapper.HasConnectionString(name);

            // Assert
            result.Should().BeFalse();
        }
Example #31
0
        public void has_setting_in_a_custom_section_with_an_unknown_key_returns_false()
        {
            // Arrange
            var wrapper = new ConfigurationManagerWrapper();

            // Act
            var result = wrapper.HasSetting("SomeValue", "customSection");

            // Assert
            result.Should().BeFalse();
        }
Example #32
0
        public void get_appsetting_of_boolean_but_using_incorrect_type_throws_exception()
        {
            // Arrange
            var wrapper = new ConfigurationManagerWrapper();

            // Act
            Action ex = () => wrapper.GetSetting <int>("IsValue");

            // Assert
            ex.ShouldThrow <Exception>().WithMessage("true is not a valid value for Int32.");
        }
Example #33
0
        public void has_setting_with_a_known_key_returns_true()
        {
            // Arrange
            var wrapper = new ConfigurationManagerWrapper();

            // Act
            var result = wrapper.HasSetting("IsValue");

            // Assert
            result.Should().BeTrue();
        }
Example #34
0
        public void has_setting_with_an_uknown_key_returns_false()
        {
            // Arrange
            var wrapper = new ConfigurationManagerWrapper();

            // Act
            var result = wrapper.HasSetting("Unknown");

            // Assert
            result.Should().BeFalse();
        }
Example #35
0
        public void get_app_setting_or_default_with_specified_default_returns_the_expected_value()
        {
            // Arrange
            var wrapper = new ConfigurationManagerWrapper();

            // Act
            var value = wrapper.GetSettingOrDefault("EmptyValue", 22);

            // Assert
            value.Should().Be(22);
        }
Example #36
0
        public void get_app_setting_or_default_with_specified_default_but_has_a_value_returns_the_value_not_the_default()
        {
            // Arrange
            var wrapper = new ConfigurationManagerWrapper();

            // Act
            var value = wrapper.GetSettingOrDefault("Size", 22);

            // Assert
            value.Should().Be(30);
        }
Example #37
0
        public void get_app_setting_or_default_with_key_but_empty_value_returns_the_types_default_value()
        {
            // Arrange
            var wrapper = new ConfigurationManagerWrapper();

            // Act
            var value = wrapper.GetSettingOrDefault <int>("EmptyValue");

            // Assert
            value.Should().Be(default(int));
        }
Example #38
0
        public void get_app_setting_with_null_or_empty_key_throws_exception(string key)
        {
            // Arrange
            var wrapper = new ConfigurationManagerWrapper();

            // Act
            Action ex = () => wrapper.GetSetting <bool>(key);

            // Assert
            ex.ShouldThrow <ArgumentException>().WithMessage($"Specified key ({key}) not found or empty.");
        }
Example #39
0
        public void get_app_setting_or_default_with_an_unknown_key_returns_default_value_for_the_typ()
        {
            // Arrange
            var wrapper = new ConfigurationManagerWrapper();

            // Act
            var value = wrapper.GetSettingOrDefault <bool>("Unknown");

            // Assert
            value.Should().BeFalse();
        }
Example #40
0
        public void get_app_setting_or_default_with_custom_and_with_null_or_empty_key_returns_default_value_for_the_typ(string key)
        {
            // Arrange
            var wrapper = new ConfigurationManagerWrapper();

            // Act
            var value = wrapper.GetSettingOrDefault <bool>(key, "customSection");

            // Assert
            value.Should().BeFalse();
        }
Example #41
0
        public void has_connection_string_with_a_known_connection_name_returns_true()
        {
            // Arrange
            var wrapper = new ConfigurationManagerWrapper();

            // Act
            var result = wrapper.HasConnectionString("default");

            // Assert
            result.Should().BeTrue();
        }
Example #42
0
        private Slug CreateDefaultSlug()
        {
            NameEditorElement nameEditorElement = new NameEditorElement();
            EditSection editSection = new EditSection { NameEditor = nameEditorElement };

            ConfigurationManagerWrapper cmw = new ConfigurationManagerWrapper
            {
                Sections = new ConfigurationManagerWrapper.ContentSectionTable(null, null, null, editSection)
            };

            return new Slug(cmw);
        }
		public StatisticsContentHandler(StatisticsRepository repository, ConfigurationManagerWrapper config)
		{
			this.repository = repository;
			var section = config.GetContentSection<Configuration.StatisticsSection>("statistics", required: false);
			this.displayedDays = section.DisplayedDays;
			this.granularity = section.Granularity;
			this.slotSize = granularity == Granularity.Day
				? TimeSpan.FromDays(1)
				: granularity == Granularity.Hour
					? TimeSpan.FromHours(1)
					: TimeSpan.FromMinutes(1);
		}
        public void GetConnectionReturnsNullIfNoConnectionFound() {
            // Act
            var configManager = new ConfigurationManagerWrapper(new Dictionary<string, IDbFileHandler>(), "DataDirectory");            
            Func<string, bool> fileExists = path => false;
            Func<string, IConnectionConfiguration> getFromConfig = name => null;

            // Act
            IConnectionConfiguration configuration = configManager.GetConnection("test", getFromConfig, fileExists);

            // Assert
            Assert.IsNull(configuration);
        }
 protected virtual string[] GetComponentConfigurations(ConfigurationManagerWrapper configuration)
 {
     List<string> configurations = new List<string>();
     string trustConfiguration = (Utility.GetTrustLevel() > System.Web.AspNetHostingPermissionLevel.Medium)
         ? ConfigurationKeys.FullTrust
         : ConfigurationKeys.MediumTrust;
     configurations.Add(trustConfiguration);
     var configured = configuration.GetContentSection<EngineSection>("engine").ComponentConfigurations;
     configurations.AddRange(configured.AddedElements.Select(e => e.Name));
     configurations.RemoveAll(c => configured.RemovedElements.Any(e => c == e.Name));
     return configurations.ToArray();
 }
 public InstallationChecker(IWebContext webContext, EventBroker broker, ConfigurationManagerWrapper configuration, InstallationManager installer)
 {
     if (configuration.Sections.Management.Installer.CheckInstallationStatus)
     {
         welcomeUrl = configuration.Sections.Management.Installer.WelcomeUrl;
         managementUrl = configuration.Sections.Management.ManagementInterfaceUrl;
         this.installer = installer;
         this.webContext = webContext;
         this.broker = broker;
         this.broker.BeginRequest += BeginRequest;
     }
 }
        /// <summary>
        /// Constructor for the application wide controller that configures default values for the entire site.
        /// </summary>
        public ApplicationController()
        {
            Configuration = new ConfigurationManagerWrapper();

            // retrieve the values
            Build = Configuration.AppSettings["Build"];

            // attempt to retrieve the build date, if fail, just use the current date
            string date = Configuration.AppSettings["BuildDate"];
            try { BuildDate = Convert.ToDateTime(date); }
            catch { BuildDate = DateTime.MinValue; }
        }
        public void GetConnectionGetsConnectionFromConfig() {
            // Arrange            
            var configManager = new ConfigurationManagerWrapper(new Dictionary<string, IDbFileHandler>(), "DataDirectory");
            Func<string, bool> fileExists = path => false;
            Func<string, IConnectionConfiguration> getFromConfig = name => new MockConnectionConfiguration("connection string");

            // Act
            IConnectionConfiguration configuration = configManager.GetConnection("foo", getFromConfig, fileExists);

            // Assert
            Assert.IsNotNull(configuration);
            Assert.AreEqual("connection string", configuration.ConnectionString);
        }
        public virtual void Configure(IEngine engine, EventBroker broker, ConfigurationManagerWrapper configuration)
        {
            engine.Container.AddComponentInstance("n2.configuration", typeof(ConfigurationManagerWrapper), configuration);
            engine.Container.AddComponentInstance("n2.engine", typeof(IEngine), engine);
            engine.Container.AddComponentInstance("n2.container", typeof(IServiceContainer), engine.Container);
            engine.Container.AddComponentInstance("n2.containerConfigurer", typeof(ContainerConfigurer), this);

            AddComponentInstance(engine.Container, configuration.GetConnectionStringsSection());
            AddComponentInstance(engine.Container, configuration.Sections.Engine);
            RegisterConfiguredComponents(engine.Container, configuration.Sections.Engine);
            AddComponentInstance(engine.Container, configuration.Sections.Web);
            InitializeEnvironment(engine.Container, configuration.Sections);
            AddComponentInstance(engine.Container, configuration.Sections.Database);
            AddComponentInstance(engine.Container, configuration.Sections.Management);
            AddComponentInstance(engine.Container, broker);

            var skipTypes = configuration.Sections.Engine.Components.GetConfiguredServiceTypes();
#if DEBUG_2
            var watf = new WebAppTypeFinder(new TypeCache(new BasicTemporaryFileHelper(null)), configuration.Sections.Engine);
            engine.Container.AddComponentInstance(watf.GetType().FullName, typeof(ITypeFinder), watf);
            var registrator = new ServiceRegistrator(watf, engine.Container);

#else
            AddComponentUnlessConfigured(engine.Container, typeof(BasicTemporaryFileHelper), typeof(BasicTemporaryFileHelper), skipTypes);
            AddComponentUnlessConfigured(engine.Container, typeof(TypeCache), typeof(TypeCache), skipTypes);
            AddComponentUnlessConfigured(engine.Container, typeof(ITypeFinder), typeof(WebAppTypeFinder), skipTypes);
            AddComponentUnlessConfigured(engine.Container, typeof(ServiceRegistrator), typeof(ServiceRegistrator), skipTypes);
            var registrator = engine.Container.Resolve<ServiceRegistrator>();
#endif
            var services = registrator.FindServices();
            var configurationKeys = configuration.GetComponentConfigurationKeys();
            services = registrator.FilterServices(services, configurationKeys);
            services = registrator.FilterServices(services, skipTypes);
            registrator.RegisterServices(services);

            // workaround for problem with open generic binding for IRepository<> - requires that [Service] attributes be removed
            var cir = engine.Container.Resolve<IContentItemRepository>();
            // register the signleton the hard way
            engine.Container.AddComponentInstance("n2.IRepository.ContentItem", typeof(IRepository<ContentItem>), cir);
#if DEBUG_2
            // double check container sanity
            var test = engine.Container.Resolve<IRepository<ContentItem>>();
            Logger.Debug(cir.GetType().FullName);
            Logger.Debug(test.GetType().FullName);
            if (!cir.Equals(test))
                throw new Exception("inconsistent repositories");
#endif
            InitializeUrlParser(engine.Container);
        }
Example #50
0
        public ErrorHandler(IErrorNotifier notifier, IWebContext context, InstallationManager installer, IMailSender mailSender, 
            ConfigurationManagerWrapper configuration)
        {
            this.notifier = notifier;
            this.context = context;
            this.installer = installer;
            this.mailSender = mailSender;

            beginUrl = configuration.Sections.Management.Installer.WelcomeUrl;
            action = configuration.Sections.Engine.Errors.Action;
            mailTo = configuration.Sections.Engine.Errors.MailTo;
            mailFrom = configuration.Sections.Engine.Errors.MailFrom;
            maxErrorReportsPerHour = configuration.Sections.Engine.Errors.MaxErrorReportsPerHour;
            handleWrongClassException = configuration.Sections.Engine.Errors.HandleWrongClassException;
            mailSender = new SmtpMailSender();
        }
Example #51
0
 public InstallationChecker(IWebContext webContext, EventBroker broker, ConfigurationManagerWrapper configuration, InstallationManager installer)
 {
     this.installer = installer;
     if (configuration.Sections.Management.Installer.CheckInstallationStatus)
     {
         welcomeUrl = configuration.Sections.Management.Installer.WelcomeUrl;
         managementUrl = configuration.Sections.Management.Paths.ManagementInterfaceUrl;
         this.webContext = webContext;
         this.broker = broker;
         this.broker.BeginRequest += BeginRequest;
         this.status = installer.GetStatus();
     }
     else
     {
         installer.UpdateStatus(SystemStatusLevel.Unconfirmed);
     }
 }
Example #52
0
		public ErrorHandler(IErrorNotifier notifier, IWebContext context, InstallationManager installer, IExceptionFilter exceptionFilter, IMailSender mailSender, 
			ConfigurationManagerWrapper configuration)
		{
			this.notifier = notifier;
			this.context = context;
			this.installer = installer;
			this.exceptionFilter = exceptionFilter;
			this.mailSender = mailSender;

			beginUrl = configuration.Sections.Management.Installer.WelcomeUrl;
			action = configuration.Sections.Engine.Errors.Action;
			mailTo = configuration.Sections.Engine.Errors.MailTo;
			mailFrom = configuration.Sections.Engine.Errors.MailFrom;
			maxErrorReportsPerHour = configuration.Sections.Engine.Errors.MaxErrorReportsPerHour;
			handleWrongClassException = configuration.Sections.Engine.Errors.HandleWrongClassException;
			handleSqlException = configuration.Sections.Engine.Errors.SqlExceptionHandling == ExceptionResolutionMode.RefreshGet;
		}
        /// <summary>
        ///     加载配置
        /// </summary>
        /// <param name="appSettigName"></param>
        public override void LoadConfiguration(string appSettigName)
        {
            var rightConfigPath = new ConfigurationManagerWrapper().AppSettings[appSettigName];
            var baseConfigPath = AppDomain.CurrentDomain.BaseDirectory;
            var fullConfigPath = MergePathHelper.MergeFilePath(baseConfigPath, rightConfigPath);

            if (string.IsNullOrWhiteSpace(rightConfigPath) || string.IsNullOrWhiteSpace(baseConfigPath) ||
                string.IsNullOrWhiteSpace(fullConfigPath))
                return;

            var xmlDoc = XmlHelper.ReadFull(fullConfigPath);

            if (xmlDoc == null)
                return;

            LoadConfiguration(xmlDoc);
        }
        public void GetConnectionGetsConnectionFromDataDirectoryIfFileWithSupportedExtensionExists() {
            // Arrange   
            var mockHandler = new Mock<MockDbFileHandler>();
            mockHandler.Setup(m => m.GetConnectionConfiguration(@"DataDirectory\Bar.foo")).Returns(new MockConnectionConfiguration("some file based connection"));
            var handlers = new Dictionary<string, IDbFileHandler> {
                {".foo", mockHandler.Object }
            };
            var configManager = new ConfigurationManagerWrapper(handlers, "DataDirectory");
            Func<string, bool> fileExists = path => path.Equals(@"DataDirectory\Bar.foo");
            Func<string, IConnectionConfiguration> getFromConfig = name => null;

            // Act
            IConnectionConfiguration configuration = configManager.GetConnection("Bar", getFromConfig, fileExists);

            // Assert
            Assert.IsNotNull(configuration);
            Assert.AreEqual("some file based connection", configuration.ConnectionString);
        }
Example #55
0
        private Slug CreateLowercaseSlug()
        {
            NameEditorElement nameEditorElement = new NameEditorElement
            {
                WhitespaceReplacement = '-',
                Replacements = new PatternValueCollection(),
                ToLower = true
            };

            EditSection editSection = new EditSection { NameEditor = nameEditorElement };

            ConfigurationManagerWrapper cmw = new ConfigurationManagerWrapper
            {
                Sections = new ConfigurationManagerWrapper.ContentSectionTable(null, null, null, editSection)
            };

            return new Slug(cmw);
        }
Example #56
0
        private Slug CreateCustomReplacementSlug()
        {
            PatternValueCollection patterns = new PatternValueCollection();
            patterns.Clear(); // to remove all those added by constructor
            patterns.Add(new PatternValueElement("c1", "[@]", "at", true));

            NameEditorElement nameEditorElement = new NameEditorElement
            {
                // WhitespaceReplacement = '-',
                Replacements = patterns //,
                // ToLower = true
            };

            EditSection editSection = new EditSection { NameEditor = nameEditorElement };

            ConfigurationManagerWrapper cmw = new ConfigurationManagerWrapper
            {
                Sections = new ConfigurationManagerWrapper.ContentSectionTable(null, null, null, editSection)
            };

            return new Slug(cmw);
        }
Example #57
0
		protected virtual void InitializeEnvironment(IServiceContainer container, ConfigurationManagerWrapper.ContentSectionTable config)
		{
			if (config.Web != null)
			{
				Url.DefaultExtension = config.Web.Web.Extension;
				PathData.PageQueryKey = config.Web.Web.PageQueryKey;
				PathData.ItemQueryKey = config.Web.Web.ItemQueryKey;
				PathData.PartQueryKey = config.Web.Web.PartQueryKey;
				PathData.PathKey = config.Web.Web.PathDataKey;

				var skipList = config.Engine.Components.GetConfiguredServiceTypes();
				if (config.Web.Web.IsWeb)
					AddComponentUnlessConfigured(container, typeof(N2.Web.IWebContext), typeof(N2.Web.AdaptiveContext), skipList);
				else
					AddComponentUnlessConfigured(container, typeof(N2.Web.IWebContext), typeof(N2.Web.ThreadContext), skipList);
			}
			if (config.Management != null)
			{
				SelectionUtility.SelectedQueryKey = config.Management.Paths.SelectedQueryKey;
				Url.SetToken("{Selection.SelectedQueryKey}", SelectionUtility.SelectedQueryKey);
			}
		}
        public void GetConnectionSdfAndMdfFile_MdfFileWins() {
            // Arrange
            var mockSdfHandler = new Mock<MockDbFileHandler>();
            mockSdfHandler.Setup(m => m.GetConnectionConfiguration(@"DataDirectory\Bar.sdf")).Returns(new MockConnectionConfiguration("sdf connection"));
            var mockMdfHandler = new Mock<MockDbFileHandler>();
            mockMdfHandler.Setup(m => m.GetConnectionConfiguration(@"DataDirectory\Bar.mdf")).Returns(new MockConnectionConfiguration("mdf connection"));
            var handlers = new Dictionary<string, IDbFileHandler> {
                {".sdf", mockSdfHandler.Object },
                {".mdf", mockMdfHandler.Object },
            };
            var configManager = new ConfigurationManagerWrapper(handlers, "DataDirectory");
            Func<string, bool> fileExists = path => path.Equals(@"DataDirectory\Bar.mdf") || 
                                                    path.Equals(@"DataDirectory\Bar.sdf");
            Func<string, IConnectionConfiguration> getFromConfig = name => null;

            // Act
            IConnectionConfiguration configuration = configManager.GetConnection("Bar", getFromConfig, fileExists);

            // Assert
            Assert.IsNotNull(configuration);
            Assert.AreEqual("mdf connection", configuration.ConnectionString);
        }
 public FakeRequestLifeCycleHandler(IWebContext webContext, RequestPathProvider dispatcher, IContentAdapterProvider adapters, IErrorNotifier errors, ConfigurationManagerWrapper configuration)
     : base(webContext, EventBroker.Instance, dispatcher, adapters, errors, configuration)
 {
     initialized = true;
 }
 public MasterPageConcern(ConfigurationManagerWrapper configuration)
 {
     var section = configuration.GetContentSection<TemplatesSection>("templates");
     if (section != null)
         masterPageFile = section.MasterPageFile;
 }