From f671fea9986f5d3227d62d877470b0112de36430 Mon Sep 17 00:00:00 2001 From: Bjarke Berg Date: Tue, 17 Mar 2020 16:26:56 +0100 Subject: [PATCH] NetCore: Refactor config/setting to not use dependencies (#7810) * Avoid usage of IOHelper in GlobalSettings * Avoid usage of IOHelper in ModelsBuilderConfig.cs * Avoid usage of IOHelper in ConnectionStrings.cs * Simplified more config * Fix for ModelsBuilderConfig * Moved GetUmbracoMvcAreaNoCache to IOHelperExtensions --- src/Umbraco.Configuration/ConfigsFactory.cs | 32 +++++------ .../ConnectionStrings.cs | 23 +++----- src/Umbraco.Configuration/GlobalSettings.cs | 21 ++----- .../HealthChecks/HealthChecksSection.cs | 12 +--- .../ConfigurationManagerConfigBase.cs | 2 +- .../Implementations/HealthChecksSettings.cs | 26 +++++++++ .../ModelsBuilderConfig.cs | 46 ++------------- src/Umbraco.Core/Composing/Composition.cs | 2 +- src/Umbraco.Core/Configuration/Configs.cs | 56 +----------------- .../Configuration/ConfigsExtensions.cs | 24 +------- .../Configuration/GlobalSettingsExtensions.cs | 45 --------------- .../Configuration/Grid/GridConfig.cs | 7 ++- .../Configuration/Grid/GridEditorsConfig.cs | 21 ++++--- .../Configuration/IConfigsFactory.cs | 2 +- .../Configuration/IConnectionStrings.cs | 6 +- .../Configuration/IGlobalSettings.cs | 2 +- .../ModelsBuilderConfigExtensions.cs | 57 +++++++++++++++++++ src/Umbraco.Core/IO/IIOHelper.cs | 3 + src/Umbraco.Core/IO/IOHelper.cs | 15 ++++- src/Umbraco.Core/IO/IOHelperExtensions.cs | 35 ++++++++++++ src/Umbraco.Core/Manifest/IManifestParser.cs | 2 - src/Umbraco.Core/Umbraco.Core.csproj | 1 + src/Umbraco.Core/UriExtensions.cs | 16 +++--- .../InstallSteps/DatabaseInstallStep.cs | 2 +- .../Manifest/ManifestParser.cs | 6 -- .../Migrations/Install/DatabaseBuilder.cs | 8 +-- .../Mapping/ContentTypeMapDefinition.cs | 6 +- .../Persistence/UmbracoDatabaseFactory.cs | 18 +++--- .../Runtime/CoreInitialComposer.cs | 6 ++ .../Runtime/CoreRuntime.cs | 8 ++- .../Runtime/SqlMainDomLock.cs | 6 +- src/Umbraco.Infrastructure/Trees/TreeNode.cs | 2 +- .../Building/ModelsGenerator.cs | 14 +++-- .../Compose/ModelsBuilderComposer.cs | 2 +- .../ModelsGenerationError.cs | 7 ++- .../OutOfDateModelsStatus.cs | 7 ++- .../PureLiveModelFactory.cs | 20 +++++-- src/Umbraco.Tests.Common/SettingsForTests.cs | 15 +++-- src/Umbraco.Tests.Common/TestHelperBase.cs | 10 ++-- .../Components/ComponentTests.cs | 2 +- .../Configurations/GlobalSettingsTests.cs | 9 ++- .../CoreThings/UriExtensionsTests.cs | 3 +- .../ModelsBuilder/ConfigTests.cs | 12 ++-- .../Persistence/DatabaseContextTests.cs | 4 +- .../PublishedContent/NuCacheChildrenTests.cs | 2 +- .../PublishedContent/NuCacheTests.cs | 2 +- .../Routing/GetContentUrlsTests.cs | 5 +- .../Routing/UmbracoModuleTests.cs | 4 +- .../Runtimes/CoreRuntimeTests.cs | 13 +++-- src/Umbraco.Tests/Runtimes/StandaloneTests.cs | 4 +- .../Security/BackOfficeCookieManagerTests.cs | 4 +- .../TestHelpers/SettingsForTests.cs | 4 +- src/Umbraco.Tests/TestHelpers/TestHelper.cs | 2 +- src/Umbraco.Tests/TestHelpers/TestObjects.cs | 10 +++- src/Umbraco.Tests/Testing/UmbracoTestBase.cs | 7 ++- ...coBackOfficeServiceCollectionExtensions.cs | 7 ++- .../Umbraco/Views/AuthorizeUpgrade.cshtml | 2 +- .../Umbraco/Views/Default.cshtml | 2 +- src/Umbraco.Web/AppBuilderExtensions.cs | 5 +- .../Editors/AuthenticationController.cs | 2 +- .../Editors/BackOfficeController.cs | 8 +-- .../Editors/BackOfficeServerVariables.cs | 2 +- src/Umbraco.Web/Editors/PreviewController.cs | 2 +- src/Umbraco.Web/Editors/UsersController.cs | 2 +- .../Install/Controllers/InstallController.cs | 2 +- .../Mvc/AreaRegistrationExtensions.cs | 5 +- src/Umbraco.Web/Mvc/BackOfficeArea.cs | 6 +- src/Umbraco.Web/Mvc/PluginControllerArea.cs | 4 +- .../Mvc/UmbracoAuthorizeAttribute.cs | 2 +- .../Runtime/WebInitialComponent.cs | 6 +- .../Security/AppBuilderExtensions.cs | 9 +-- .../Security/BackOfficeCookieManager.cs | 12 ++-- .../Security/GetUserSecondsMiddleWare.cs | 8 ++- .../PreviewAuthenticationMiddleware.cs | 6 +- .../Security/SessionIdValidator.cs | 2 +- .../UmbracoBackOfficeCookieAuthOptions.cs | 2 +- src/Umbraco.Web/UmbracoApplication.cs | 7 ++- src/Umbraco.Web/UmbracoApplicationBase.cs | 7 ++- src/Umbraco.Web/UmbracoContext.cs | 2 +- src/Umbraco.Web/UmbracoDefaultOwinStartup.cs | 10 ++-- src/Umbraco.Web/UmbracoInjectedModule.cs | 15 ++--- 81 files changed, 410 insertions(+), 407 deletions(-) create mode 100644 src/Umbraco.Configuration/Implementations/HealthChecksSettings.cs delete mode 100644 src/Umbraco.Core/Configuration/GlobalSettingsExtensions.cs create mode 100644 src/Umbraco.Core/Configuration/ModelsBuilderConfigExtensions.cs diff --git a/src/Umbraco.Configuration/ConfigsFactory.cs b/src/Umbraco.Configuration/ConfigsFactory.cs index 2ba3a109e1..5c6eade265 100644 --- a/src/Umbraco.Configuration/ConfigsFactory.cs +++ b/src/Umbraco.Configuration/ConfigsFactory.cs @@ -1,17 +1,14 @@ -using System.Configuration; using Umbraco.Configuration; using Umbraco.Configuration.Implementations; using Umbraco.Core.Configuration.HealthChecks; +using Umbraco.Core.Configuration.Implementations; using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Core.IO; -using Umbraco.Core.Logging; namespace Umbraco.Core.Configuration { public class ConfigsFactory : IConfigsFactory { public IHostingSettings HostingSettings { get; } = new HostingSettings(); - public ICoreDebug CoreDebug { get; } = new CoreDebug(); public IMachineKeyConfig MachineKeyConfig { get; } = new MachineKeyConfig(); public IIndexCreatorSettings IndexCreatorSettings { get; } = new IndexCreatorSettings(); @@ -29,28 +26,28 @@ namespace Umbraco.Core.Configuration public IUserPasswordConfiguration UserPasswordConfigurationSettings { get; } = new UserPasswordConfigurationSettings(); public IMemberPasswordConfiguration MemberPasswordConfigurationSettings { get; } = new MemberPasswordConfigurationSettings(); public IContentSettings ContentSettings { get; } = new ContentSettings(); + public IGlobalSettings GlobalSettings { get; } = new GlobalSettings(); + public IHealthChecks HealthChecksSettings { get; } = new HealthChecksSettings(); + public IConnectionStrings ConnectionStrings { get; } = new ConnectionStrings(); + public IModelsBuilderConfig ModelsBuilderConfig { get; } = new ModelsBuilderConfig(); - public Configs Create(IIOHelper ioHelper, ILogger logger) + public Configs Create() { - var configs = new Configs(section => ConfigurationManager.GetSection(section)); - configs.Add(() => new GlobalSettings(ioHelper)); - configs.Add(() => HostingSettings); - - configs.Add("umbracoConfiguration/HealthChecks"); - - configs.Add(() => CoreDebug); - configs.Add(() => MachineKeyConfig); - configs.Add(() => new ConnectionStrings(ioHelper, logger)); - configs.Add(() => new ModelsBuilderConfig(ioHelper)); - + var configs = new Configs(); + configs.Add(() => GlobalSettings); + configs.Add(() => HostingSettings); + configs.Add(() => HealthChecksSettings); + configs.Add(() => CoreDebug); + configs.Add(() => MachineKeyConfig); + configs.Add(() => ConnectionStrings); + configs.Add(() => ModelsBuilderConfig); configs.Add(() => IndexCreatorSettings); configs.Add(() => NuCacheSettings); configs.Add(() => TypeFinderSettings); configs.Add(() => RuntimeSettings); configs.Add(() => ActiveDirectorySettings); configs.Add(() => ExceptionFilterSettings); - configs.Add(() => TourSettings); configs.Add(() => LoggingSettings); configs.Add(() => KeepAliveSettings); @@ -61,7 +58,6 @@ namespace Umbraco.Core.Configuration configs.Add(() => MemberPasswordConfigurationSettings); configs.Add(() => ContentSettings); - configs.AddCoreConfigs(ioHelper); return configs; } } diff --git a/src/Umbraco.Configuration/ConnectionStrings.cs b/src/Umbraco.Configuration/ConnectionStrings.cs index 23436d6caf..66fdb33d5b 100644 --- a/src/Umbraco.Configuration/ConnectionStrings.cs +++ b/src/Umbraco.Configuration/ConnectionStrings.cs @@ -3,6 +3,7 @@ using System.Configuration; using System.IO; using System.Linq; using System.Xml.Linq; +using Umbraco.Composing; using Umbraco.Core.IO; using Umbraco.Core.Logging; @@ -10,14 +11,6 @@ namespace Umbraco.Core.Configuration { public class ConnectionStrings : IConnectionStrings { - private readonly IIOHelper _ioHelper; - private readonly ILogger _logger; - - public ConnectionStrings(IIOHelper ioHelper, ILogger logger) - { - _ioHelper = ioHelper; - _logger = logger; - } public ConfigConnectionString this[string key] { @@ -29,9 +22,9 @@ namespace Umbraco.Core.Configuration } } - public void RemoveConnectionString(string key) + public void RemoveConnectionString(string key, IIOHelper ioHelper) { - var fileName = _ioHelper.MapPath(string.Format("{0}/web.config", _ioHelper.Root)); + var fileName = ioHelper.MapPath(string.Format("{0}/web.config", ioHelper.Root)); var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace); var appSettings = xml.Root.DescendantsAndSelf("appSettings").Single(); @@ -52,7 +45,7 @@ namespace Umbraco.Core.Configuration /// Saves the ConnectionString in the very nasty 'medium trust'-supportive way. /// The connection string. /// The provider name. - public void SaveConnectionString(string connectionString, string providerName) + public void SaveConnectionString(string connectionString, string providerName, IIOHelper ioHelper) { if (connectionString == null) throw new ArgumentNullException(nameof(connectionString)); @@ -62,7 +55,7 @@ namespace Umbraco.Core.Configuration var fileSource = "web.config"; - var fileName = _ioHelper.MapPath(_ioHelper.Root +"/" + fileSource); + var fileName = ioHelper.MapPath(ioHelper.Root +"/" + fileSource); var xml = XDocument.Load(fileName, LoadOptions.PreserveWhitespace); if (xml.Root == null) throw new Exception($"Invalid {fileSource} file (no root)."); @@ -75,7 +68,7 @@ namespace Umbraco.Core.Configuration if (configSourceAttribute != null) { fileSource = configSourceAttribute.Value; - fileName = _ioHelper.MapPath(_ioHelper.Root + "/" + fileSource); + fileName = ioHelper.MapPath(ioHelper.Root + "/" + fileSource); if (!File.Exists(fileName)) throw new Exception($"Invalid configSource \"{fileSource}\" (no such file)."); @@ -103,9 +96,9 @@ namespace Umbraco.Core.Configuration } // save - _logger.Info("Saving connection string to {ConfigFile}.", fileSource); + Current.Logger.Info("Saving connection string to {ConfigFile}.", fileSource); xml.Save(fileName, SaveOptions.DisableFormatting); - _logger.Info("Saved connection string to {ConfigFile}.", fileSource); + Current.Logger.Info("Saved connection string to {ConfigFile}.", fileSource); } private static void AddOrUpdateAttribute(XElement element, string name, string value) diff --git a/src/Umbraco.Configuration/GlobalSettings.cs b/src/Umbraco.Configuration/GlobalSettings.cs index 923cd422bf..6fda5fa9ba 100644 --- a/src/Umbraco.Configuration/GlobalSettings.cs +++ b/src/Umbraco.Configuration/GlobalSettings.cs @@ -3,6 +3,7 @@ using System.Configuration; using System.Linq; using System.Net.Mail; using System.Xml.Linq; +using Umbraco.Composing; using Umbraco.Configuration; using Umbraco.Core.IO; @@ -64,7 +65,6 @@ namespace Umbraco.Core.Configuration /// public class GlobalSettings : IGlobalSettings { - private readonly IIOHelper _ioHelper; // TODO these should not be static private static string _reservedPaths; @@ -74,11 +74,6 @@ namespace Umbraco.Core.Configuration internal const string StaticReservedPaths = "~/app_plugins/,~/install/,~/mini-profiler-resources/,"; //must end with a comma! internal const string StaticReservedUrls = "~/config/splashes/noNodes.aspx,~/.well-known,"; //must end with a comma! - public GlobalSettings(IIOHelper ioHelper) - { - _ioHelper = ioHelper; - } - /// /// Used in unit testing to reset all config items that were set with property setters (i.e. did not come from config) /// @@ -203,15 +198,7 @@ namespace Umbraco.Core.Configuration /// Gets the path to umbraco's root directory (/umbraco by default). /// /// The path. - public string Path - { - get - { - return ConfigurationManager.AppSettings.ContainsKey(Constants.AppSettings.Path) - ? _ioHelper.ResolveUrl(ConfigurationManager.AppSettings[Constants.AppSettings.Path]) - : string.Empty; - } - } + public string Path => ConfigurationManager.AppSettings[Constants.AppSettings.Path]; /// /// Gets or sets the configuration status. This will return the version number of the currently installed umbraco instance. @@ -227,7 +214,7 @@ namespace Umbraco.Core.Configuration } set { - SaveSetting(Constants.AppSettings.ConfigurationStatus, value, _ioHelper); + SaveSetting(Constants.AppSettings.ConfigurationStatus, value, Current.IOHelper); //TODO remove } } @@ -254,7 +241,7 @@ namespace Umbraco.Core.Configuration ConfigurationManager.RefreshSection("appSettings"); } - + /// /// Gets the time out in minutes. /// diff --git a/src/Umbraco.Configuration/HealthChecks/HealthChecksSection.cs b/src/Umbraco.Configuration/HealthChecks/HealthChecksSection.cs index 90a7d8c567..373d846567 100644 --- a/src/Umbraco.Configuration/HealthChecks/HealthChecksSection.cs +++ b/src/Umbraco.Configuration/HealthChecks/HealthChecksSection.cs @@ -1,10 +1,9 @@ using System; -using System.Collections.Generic; using System.Configuration; namespace Umbraco.Core.Configuration.HealthChecks { - public class HealthChecksSection : ConfigurationSection, IHealthChecks + public class HealthChecksSection : ConfigurationSection { private const string DisabledChecksKey = "disabledChecks"; private const string NotificationSettingsKey = "notificationSettings"; @@ -21,14 +20,5 @@ namespace Umbraco.Core.Configuration.HealthChecks get { return ((HealthCheckNotificationSettingsElement)(base[NotificationSettingsKey])); } } - IEnumerable IHealthChecks.DisabledChecks - { - get { return DisabledChecks; } - } - - IHealthCheckNotificationSettings IHealthChecks.NotificationSettings - { - get { return NotificationSettings; } - } } } diff --git a/src/Umbraco.Configuration/Implementations/ConfigurationManagerConfigBase.cs b/src/Umbraco.Configuration/Implementations/ConfigurationManagerConfigBase.cs index d218ac803b..0302a7ea31 100644 --- a/src/Umbraco.Configuration/Implementations/ConfigurationManagerConfigBase.cs +++ b/src/Umbraco.Configuration/Implementations/ConfigurationManagerConfigBase.cs @@ -7,7 +7,7 @@ namespace Umbraco.Configuration.Implementations { private UmbracoSettingsSection _umbracoSettingsSection; - public UmbracoSettingsSection UmbracoSettingsSection + protected UmbracoSettingsSection UmbracoSettingsSection { get { diff --git a/src/Umbraco.Configuration/Implementations/HealthChecksSettings.cs b/src/Umbraco.Configuration/Implementations/HealthChecksSettings.cs new file mode 100644 index 0000000000..656a3ffc82 --- /dev/null +++ b/src/Umbraco.Configuration/Implementations/HealthChecksSettings.cs @@ -0,0 +1,26 @@ +using System.Collections.Generic; +using System.Configuration; +using Umbraco.Core.Configuration.HealthChecks; + +namespace Umbraco.Core.Configuration.Implementations +{ + public class HealthChecksSettings : IHealthChecks + { + private HealthChecksSection _healthChecksSection; + + private HealthChecksSection HealthChecksSection + { + get + { + if (_healthChecksSection is null) + { + _healthChecksSection = ConfigurationManager.GetSection("umbracoConfiguration/HealthChecks") as HealthChecksSection; + } + return _healthChecksSection; + } + } + + public IEnumerable DisabledChecks => HealthChecksSection.DisabledChecks; + public IHealthCheckNotificationSettings NotificationSettings => HealthChecksSection.NotificationSettings; + } +} diff --git a/src/Umbraco.Configuration/ModelsBuilderConfig.cs b/src/Umbraco.Configuration/ModelsBuilderConfig.cs index 151e9908a1..79f4b065a0 100644 --- a/src/Umbraco.Configuration/ModelsBuilderConfig.cs +++ b/src/Umbraco.Configuration/ModelsBuilderConfig.cs @@ -13,7 +13,7 @@ namespace Umbraco.Configuration /// public class ModelsBuilderConfig : IModelsBuilderConfig { - private readonly IIOHelper _ioHelper; + private const string Prefix = "Umbraco.ModelsBuilder."; private object _modelsModelLock; private bool _modelsModelConfigured; @@ -23,15 +23,13 @@ namespace Umbraco.Configuration private bool _flagOutOfDateModels; - public string DefaultModelsDirectory => _ioHelper.MapPath("~/App_Data/Models"); + public string DefaultModelsDirectory => "~/App_Data/Models"; /// /// Initializes a new instance of the class. /// - public ModelsBuilderConfig(IIOHelper ioHelper) + public ModelsBuilderConfig() { - _ioHelper = ioHelper ?? throw new ArgumentNullException(nameof(ioHelper)); - // giant kill switch, default: false // must be explicitely set to true for anything else to happen Enable = ConfigurationManager.AppSettings[Prefix + "Enable"] == "true"; @@ -59,12 +57,8 @@ namespace Umbraco.Configuration value = ConfigurationManager.AppSettings[Prefix + "ModelsDirectory"]; if (!string.IsNullOrWhiteSpace(value)) { - var root = _ioHelper.MapPath("~/"); - if (root == null) - throw new ConfigurationErrorsException("Could not determine root directory."); - // GetModelsDirectory will ensure that the path is safe - ModelsDirectory = GetModelsDirectory(root, value, AcceptUnsafeModelsDirectory); + ModelsDirectory = value; } // default: 0 @@ -81,7 +75,7 @@ namespace Umbraco.Configuration /// /// Initializes a new instance of the class. /// - public ModelsBuilderConfig(IIOHelper ioHelper, + public ModelsBuilderConfig( bool enable = false, ModelsMode modelsMode = ModelsMode.Nothing, string modelsNamespace = null, @@ -91,7 +85,6 @@ namespace Umbraco.Configuration bool acceptUnsafeModelsDirectory = false, int debugLevel = 0) { - _ioHelper = ioHelper ?? throw new ArgumentNullException(nameof(ioHelper)); Enable = enable; _modelsMode = modelsMode; @@ -103,36 +96,7 @@ namespace Umbraco.Configuration DebugLevel = debugLevel; } - // internal for tests - internal static string GetModelsDirectory(string root, string config, bool acceptUnsafe) - { - // making sure it is safe, ie under the website root, - // unless AcceptUnsafeModelsDirectory and then everything is OK. - if (!Path.IsPathRooted(root)) - throw new ConfigurationErrorsException($"Root is not rooted \"{root}\"."); - - if (config.StartsWith("~/")) - { - var dir = Path.Combine(root, config.TrimStart("~/")); - - // sanitize - GetFullPath will take care of any relative - // segments in path, eg '../../foo.tmp' - it may throw a SecurityException - // if the combined path reaches illegal parts of the filesystem - dir = Path.GetFullPath(dir); - root = Path.GetFullPath(root); - - if (!dir.StartsWith(root) && !acceptUnsafe) - throw new ConfigurationErrorsException($"Invalid models directory \"{config}\"."); - - return dir; - } - - if (acceptUnsafe) - return Path.GetFullPath(config); - - throw new ConfigurationErrorsException($"Invalid models directory \"{config}\"."); - } /// /// Gets a value indicating whether the whole models experience is enabled. diff --git a/src/Umbraco.Core/Composing/Composition.cs b/src/Umbraco.Core/Composing/Composition.cs index a186a1f00a..9a696c2dc0 100644 --- a/src/Umbraco.Core/Composing/Composition.cs +++ b/src/Umbraco.Core/Composing/Composition.cs @@ -135,7 +135,7 @@ namespace Umbraco.Core.Composing IFactory factory = null; - Configs.RegisterWith(_register, () => factory); + Configs.RegisterWith(_register); // ReSharper disable once AccessToModifiedClosure -- on purpose _register.Register(_ => factory, Lifetime.Singleton); diff --git a/src/Umbraco.Core/Configuration/Configs.cs b/src/Umbraco.Core/Configuration/Configs.cs index abb06d525f..821ee308f0 100644 --- a/src/Umbraco.Core/Configuration/Configs.cs +++ b/src/Umbraco.Core/Configuration/Configs.cs @@ -13,16 +13,8 @@ namespace Umbraco.Core.Configuration /// public class Configs { - private readonly Func _configSectionResolver; - - public Configs(Func configSectionResolver) - { - _configSectionResolver = configSectionResolver ?? throw new ArgumentNullException(nameof(configSectionResolver)); - } - private readonly Dictionary> _configs = new Dictionary>(); private Dictionary> _registerings = new Dictionary>(); - private Lazy _factory; /// /// Gets a configuration. @@ -52,61 +44,15 @@ namespace Umbraco.Core.Configuration _registerings[typeOfConfig] = register => register.Register(_ => (TConfig) lazyConfigFactory.Value, Lifetime.Singleton); } - /// - /// Adds a configuration, provided by a factory. - /// - public void Add(Func configFactory) - where TConfig : class - { - // make sure it is not too late - if (_registerings == null) - throw new InvalidOperationException("Configurations have already been registered."); - - var typeOfConfig = typeof(TConfig); - - _configs[typeOfConfig] = new Lazy(() => - { - if (!(_factory is null)) return _factory.Value.GetInstance(); - throw new InvalidOperationException($"Cannot get configuration of type {typeOfConfig} during composition."); - }); - _registerings[typeOfConfig] = register => register.Register(configFactory, Lifetime.Singleton); - } - - /// - /// Adds a configuration, provided by a configuration section. - /// - public void Add(string sectionName) - where TConfig : class - { - Add(() => GetConfig(sectionName)); - } - - private TConfig GetConfig(string sectionName) - where TConfig : class - { - // note: need to use SafeCallContext here because ConfigurationManager.GetSection ends up getting AppDomain.Evidence - // which will want to serialize the call context including anything that is in there - what a mess! - - using (new SafeCallContext()) - { - if ((_configSectionResolver(sectionName) is TConfig config)) - return config; - var ex = new InvalidOperationException($"Could not get configuration section \"{sectionName}\" from config files."); - throw ex; - } - } - /// /// Registers configurations in a register. /// - public void RegisterWith(IRegister register, Func factory) + public void RegisterWith(IRegister register) { // do it only once if (_registerings == null) throw new InvalidOperationException("Configurations have already been registered."); - _factory = new Lazy(factory); - register.Register(this); foreach (var registering in _registerings.Values) diff --git a/src/Umbraco.Core/Configuration/ConfigsExtensions.cs b/src/Umbraco.Core/Configuration/ConfigsExtensions.cs index 93586b550b..5019282d97 100644 --- a/src/Umbraco.Core/Configuration/ConfigsExtensions.cs +++ b/src/Umbraco.Core/Configuration/ConfigsExtensions.cs @@ -1,13 +1,7 @@ -using System.IO; -using Umbraco.Core.Cache; -using Umbraco.Core.Composing; -using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.Grid; using Umbraco.Core.Configuration.HealthChecks; using Umbraco.Core.Configuration.UmbracoSettings; -using Umbraco.Core.IO; -using Umbraco.Core.Logging; -using Umbraco.Core.Manifest; namespace Umbraco.Core { @@ -45,24 +39,8 @@ namespace Umbraco.Core public static IHealthChecks HealthChecks(this Configs configs) => configs.GetConfig(); - - public static IGridConfig Grids(this Configs configs) - => configs.GetConfig(); - public static ICoreDebug CoreDebug(this Configs configs) => configs.GetConfig(); - public static void AddCoreConfigs(this Configs configs, IIOHelper ioHelper) - { - var configDir = new DirectoryInfo(ioHelper.MapPath(Constants.SystemDirectories.Config)); - - // GridConfig depends on runtime caches, manifest parsers... and cannot be available during composition - configs.Add(factory => new GridConfig( - factory.GetInstance(), - factory.GetInstance(), - configDir, - factory.GetInstance(), - factory.GetInstance().Debug)); - } } } diff --git a/src/Umbraco.Core/Configuration/GlobalSettingsExtensions.cs b/src/Umbraco.Core/Configuration/GlobalSettingsExtensions.cs deleted file mode 100644 index 4d8039dfbb..0000000000 --- a/src/Umbraco.Core/Configuration/GlobalSettingsExtensions.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System; -using Umbraco.Core.IO; - -namespace Umbraco.Core.Configuration -{ - public static class GlobalSettingsExtensions - { - private static string _mvcArea; - - - /// - /// This returns the string of the MVC Area route. - /// - /// - /// This will return the MVC area that we will route all custom routes through like surface controllers, etc... - /// We will use the 'Path' (default ~/umbraco) to create it but since it cannot contain '/' and people may specify a path of ~/asdf/asdf/admin - /// we will convert the '/' to '-' and use that as the path. its a bit lame but will work. - /// - /// We also make sure that the virtual directory (SystemDirectories.Root) is stripped off first, otherwise we'd end up with something - /// like "MyVirtualDirectory-Umbraco" instead of just "Umbraco". - /// - public static string GetUmbracoMvcArea(this IGlobalSettings globalSettings, IIOHelper ioHelper) - { - if (_mvcArea != null) return _mvcArea; - - _mvcArea = GetUmbracoMvcAreaNoCache(globalSettings, ioHelper); - - return _mvcArea; - } - - internal static string GetUmbracoMvcAreaNoCache(this IGlobalSettings globalSettings, IIOHelper ioHelper) - { - if (globalSettings.Path.IsNullOrWhiteSpace()) - { - throw new InvalidOperationException("Cannot create an MVC Area path without the umbracoPath specified"); - } - - var path = globalSettings.Path; - if (path.StartsWith(ioHelper.Root)) // beware of TrimStart, see U4-2518 - path = path.Substring(ioHelper.Root.Length); - return path.TrimStart('~').TrimStart('/').Replace('/', '-').Trim().ToLower(); - } - - } -} diff --git a/src/Umbraco.Core/Configuration/Grid/GridConfig.cs b/src/Umbraco.Core/Configuration/Grid/GridConfig.cs index de4f7ccd5a..72c720e3d6 100644 --- a/src/Umbraco.Core/Configuration/Grid/GridConfig.cs +++ b/src/Umbraco.Core/Configuration/Grid/GridConfig.cs @@ -1,15 +1,18 @@ using System.IO; using Umbraco.Core.Cache; +using Umbraco.Core.Hosting; +using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Manifest; +using Umbraco.Core.Serialization; namespace Umbraco.Core.Configuration.Grid { public class GridConfig : IGridConfig { - public GridConfig(ILogger logger, AppCaches appCaches, DirectoryInfo configFolder, IManifestParser manifestParser, bool isDebug) + public GridConfig(AppCaches appCaches, IIOHelper ioHelper, IManifestParser manifestParser, IJsonSerializer jsonSerializer, IHostingEnvironment hostingEnvironment) { - EditorsConfig = new GridEditorsConfig(logger, appCaches, configFolder, manifestParser, isDebug); + EditorsConfig = new GridEditorsConfig(appCaches, ioHelper, manifestParser, jsonSerializer, hostingEnvironment.IsDebugMode); } public IGridEditorsConfig EditorsConfig { get; } diff --git a/src/Umbraco.Core/Configuration/Grid/GridEditorsConfig.cs b/src/Umbraco.Core/Configuration/Grid/GridEditorsConfig.cs index a1ebf008fc..410c83ff1a 100644 --- a/src/Umbraco.Core/Configuration/Grid/GridEditorsConfig.cs +++ b/src/Umbraco.Core/Configuration/Grid/GridEditorsConfig.cs @@ -1,27 +1,30 @@ using System; using System.Collections.Generic; using System.IO; +using Umbraco.Composing; using Umbraco.Core.Cache; +using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Manifest; using Umbraco.Core.PropertyEditors; +using Umbraco.Core.Serialization; namespace Umbraco.Core.Configuration.Grid { internal class GridEditorsConfig : IGridEditorsConfig { - private readonly ILogger _logger; private readonly AppCaches _appCaches; - private readonly DirectoryInfo _configFolder; + private readonly IIOHelper _ioHelper; private readonly IManifestParser _manifestParser; private readonly bool _isDebug; + private readonly IJsonSerializer _jsonSerializer; - public GridEditorsConfig(ILogger logger, AppCaches appCaches, DirectoryInfo configFolder, IManifestParser manifestParser, bool isDebug) + public GridEditorsConfig(AppCaches appCaches, IIOHelper ioHelper, IManifestParser manifestParser,IJsonSerializer jsonSerializer, bool isDebug) { - _logger = logger; _appCaches = appCaches; - _configFolder = configFolder; + _ioHelper = ioHelper; _manifestParser = manifestParser; + _jsonSerializer = jsonSerializer; _isDebug = isDebug; } @@ -31,19 +34,20 @@ namespace Umbraco.Core.Configuration.Grid { List GetResult() { + var configFolder = new DirectoryInfo(_ioHelper.MapPath(Constants.SystemDirectories.Config)); var editors = new List(); - var gridConfig = Path.Combine(_configFolder.FullName, "grid.editors.config.js"); + var gridConfig = Path.Combine(configFolder.FullName, "grid.editors.config.js"); if (File.Exists(gridConfig)) { var sourceString = File.ReadAllText(gridConfig); try { - editors.AddRange(_manifestParser.ParseGridEditors(sourceString)); + editors.AddRange(_jsonSerializer.Deserialize>(sourceString)); } catch (Exception ex) { - _logger.Error(ex, "Could not parse the contents of grid.editors.config.js into a JSON array '{Json}", sourceString); + Current.Logger.Error(ex, "Could not parse the contents of grid.editors.config.js into a JSON array '{Json}", sourceString); } } @@ -63,7 +67,6 @@ namespace Umbraco.Core.Configuration.Grid return result; } - } } } diff --git a/src/Umbraco.Core/Configuration/IConfigsFactory.cs b/src/Umbraco.Core/Configuration/IConfigsFactory.cs index b2ad6295a1..dd2459b88c 100644 --- a/src/Umbraco.Core/Configuration/IConfigsFactory.cs +++ b/src/Umbraco.Core/Configuration/IConfigsFactory.cs @@ -5,6 +5,6 @@ namespace Umbraco.Core.Configuration { public interface IConfigsFactory { - Configs Create(IIOHelper ioHelper, ILogger logger); + Configs Create(); } } diff --git a/src/Umbraco.Core/Configuration/IConnectionStrings.cs b/src/Umbraco.Core/Configuration/IConnectionStrings.cs index 2a14c0e614..f8d17d6794 100644 --- a/src/Umbraco.Core/Configuration/IConnectionStrings.cs +++ b/src/Umbraco.Core/Configuration/IConnectionStrings.cs @@ -1,3 +1,5 @@ +using Umbraco.Core.IO; + namespace Umbraco.Core.Configuration { public interface IConnectionStrings @@ -7,7 +9,7 @@ namespace Umbraco.Core.Configuration get; } - void RemoveConnectionString(string umbracoConnectionName); - void SaveConnectionString(string connectionString, string providerName); + void RemoveConnectionString(string umbracoConnectionName, IIOHelper ioHelper); + void SaveConnectionString(string connectionString, string providerName, IIOHelper ioHelper); } } diff --git a/src/Umbraco.Core/Configuration/IGlobalSettings.cs b/src/Umbraco.Core/Configuration/IGlobalSettings.cs index fa96f66d00..3cb211a7a7 100644 --- a/src/Umbraco.Core/Configuration/IGlobalSettings.cs +++ b/src/Umbraco.Core/Configuration/IGlobalSettings.cs @@ -21,7 +21,7 @@ string ReservedPaths { get; } /// - /// Gets the path to umbraco's root directory (/umbraco by default). + /// Gets the path to umbraco's root directory. /// string Path { get; } diff --git a/src/Umbraco.Core/Configuration/ModelsBuilderConfigExtensions.cs b/src/Umbraco.Core/Configuration/ModelsBuilderConfigExtensions.cs new file mode 100644 index 0000000000..3e3b116395 --- /dev/null +++ b/src/Umbraco.Core/Configuration/ModelsBuilderConfigExtensions.cs @@ -0,0 +1,57 @@ +using System.Configuration; +using System.IO; +using Umbraco.Core.IO; + +namespace Umbraco.Core.Configuration +{ + public static class ModelsBuilderConfigExtensions + { + private static string _modelsDirectoryAbsolute = null; + + public static string ModelsDirectoryAbsolute(this IModelsBuilderConfig modelsBuilderConfig, IIOHelper ioHelper) + { + + if (_modelsDirectoryAbsolute is null) + { + var modelsDirectory = modelsBuilderConfig.ModelsDirectory; + var root = ioHelper.MapPath("~/"); + + _modelsDirectoryAbsolute = GetModelsDirectory(root, modelsDirectory, + modelsBuilderConfig.AcceptUnsafeModelsDirectory); + } + + return _modelsDirectoryAbsolute; + } + + // internal for tests + internal static string GetModelsDirectory(string root, string config, bool acceptUnsafe) + { + // making sure it is safe, ie under the website root, + // unless AcceptUnsafeModelsDirectory and then everything is OK. + + if (!Path.IsPathRooted(root)) + throw new ConfigurationErrorsException($"Root is not rooted \"{root}\"."); + + if (config.StartsWith("~/")) + { + var dir = Path.Combine(root, config.TrimStart("~/")); + + // sanitize - GetFullPath will take care of any relative + // segments in path, eg '../../foo.tmp' - it may throw a SecurityException + // if the combined path reaches illegal parts of the filesystem + dir = Path.GetFullPath(dir); + root = Path.GetFullPath(root); + + if (!dir.StartsWith(root) && !acceptUnsafe) + throw new ConfigurationErrorsException($"Invalid models directory \"{config}\"."); + + return dir; + } + + if (acceptUnsafe) + return Path.GetFullPath(config); + + throw new ConfigurationErrorsException($"Invalid models directory \"{config}\"."); + } + } +} diff --git a/src/Umbraco.Core/IO/IIOHelper.cs b/src/Umbraco.Core/IO/IIOHelper.cs index 11f5c6c565..f478b49de6 100644 --- a/src/Umbraco.Core/IO/IIOHelper.cs +++ b/src/Umbraco.Core/IO/IIOHelper.cs @@ -4,6 +4,9 @@ namespace Umbraco.Core.IO { public interface IIOHelper { + + string BackOfficePath { get; } + bool ForceNotHosted { get; set; } char DirSepChar { get; } diff --git a/src/Umbraco.Core/IO/IOHelper.cs b/src/Umbraco.Core/IO/IOHelper.cs index d5e1335f35..3abd413fd4 100644 --- a/src/Umbraco.Core/IO/IOHelper.cs +++ b/src/Umbraco.Core/IO/IOHelper.cs @@ -4,6 +4,7 @@ using System.Globalization; using System.Reflection; using System.IO; using System.Linq; +using Umbraco.Core.Configuration; using Umbraco.Core.Hosting; using Umbraco.Core.Strings; @@ -12,10 +13,22 @@ namespace Umbraco.Core.IO public class IOHelper : IIOHelper { private readonly IHostingEnvironment _hostingEnvironment; + private readonly IGlobalSettings _globalSettings; - public IOHelper(IHostingEnvironment hostingEnvironment) + public IOHelper(IHostingEnvironment hostingEnvironment, IGlobalSettings globalSettings) { _hostingEnvironment = hostingEnvironment; + _globalSettings = globalSettings; + } + + public string BackOfficePath + { + get + { + var path = _globalSettings.Path; + + return string.IsNullOrEmpty(path) ? string.Empty : ResolveUrl(path); + } } /// diff --git a/src/Umbraco.Core/IO/IOHelperExtensions.cs b/src/Umbraco.Core/IO/IOHelperExtensions.cs index 64b57e7dc1..39bd5e6cc9 100644 --- a/src/Umbraco.Core/IO/IOHelperExtensions.cs +++ b/src/Umbraco.Core/IO/IOHelperExtensions.cs @@ -5,6 +5,8 @@ namespace Umbraco.Core.IO { public static class IOHelperExtensions { + private static string _mvcArea; + /// /// Tries to create a directory. /// @@ -35,5 +37,38 @@ namespace Umbraco.Core.IO { return "umbraco-test." + Guid.NewGuid().ToString("N").Substring(0, 8); } + + /// + /// This returns the string of the MVC Area route. + /// + /// + /// This will return the MVC area that we will route all custom routes through like surface controllers, etc... + /// We will use the 'Path' (default ~/umbraco) to create it but since it cannot contain '/' and people may specify a path of ~/asdf/asdf/admin + /// we will convert the '/' to '-' and use that as the path. its a bit lame but will work. + /// + /// We also make sure that the virtual directory (SystemDirectories.Root) is stripped off first, otherwise we'd end up with something + /// like "MyVirtualDirectory-Umbraco" instead of just "Umbraco". + /// + public static string GetUmbracoMvcArea(this IIOHelper ioHelper) + { + if (_mvcArea != null) return _mvcArea; + + _mvcArea = GetUmbracoMvcAreaNoCache(ioHelper); + + return _mvcArea; + } + + internal static string GetUmbracoMvcAreaNoCache(this IIOHelper ioHelper) + { + if (ioHelper.BackOfficePath.IsNullOrWhiteSpace()) + { + throw new InvalidOperationException("Cannot create an MVC Area path without the umbracoPath specified"); + } + + var path = ioHelper.BackOfficePath; + if (path.StartsWith(ioHelper.Root)) // beware of TrimStart, see U4-2518 + path = path.Substring(ioHelper.Root.Length); + return path.TrimStart('~').TrimStart('/').Replace('/', '-').Trim().ToLower(); + } } } diff --git a/src/Umbraco.Core/Manifest/IManifestParser.cs b/src/Umbraco.Core/Manifest/IManifestParser.cs index eeb0c756f6..3eec7007b3 100644 --- a/src/Umbraco.Core/Manifest/IManifestParser.cs +++ b/src/Umbraco.Core/Manifest/IManifestParser.cs @@ -17,7 +17,5 @@ namespace Umbraco.Core.Manifest /// Parses a manifest. /// PackageManifest ParseManifest(string text); - - IEnumerable ParseGridEditors(string text); } } diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index 7a15e7fbed..c083cccf8f 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -12,6 +12,7 @@ + diff --git a/src/Umbraco.Core/UriExtensions.cs b/src/Umbraco.Core/UriExtensions.cs index cf84d7914d..4321aefd7f 100644 --- a/src/Umbraco.Core/UriExtensions.cs +++ b/src/Umbraco.Core/UriExtensions.cs @@ -40,7 +40,7 @@ namespace Umbraco.Core /// But if we've got this far we'll just have to assume it's front-end anyways. /// /// - internal static bool IsBackOfficeRequest(this Uri url, string applicationPath, IGlobalSettings globalSettings, IIOHelper ioHelper) + internal static bool IsBackOfficeRequest(this Uri url, string applicationPath, IIOHelper ioHelper) { applicationPath = applicationPath ?? string.Empty; @@ -49,11 +49,11 @@ namespace Umbraco.Core var urlPath = fullUrlPath.TrimStart(appPath).EnsureStartsWith('/'); //check if this is in the umbraco back office - var isUmbracoPath = urlPath.InvariantStartsWith(globalSettings.Path.EnsureStartsWith('/').TrimStart(appPath.EnsureStartsWith('/')).EnsureStartsWith('/')); + var isUmbracoPath = urlPath.InvariantStartsWith(ioHelper.BackOfficePath.EnsureStartsWith('/').TrimStart(appPath.EnsureStartsWith('/')).EnsureStartsWith('/')); //if not, then def not back office if (isUmbracoPath == false) return false; - var mvcArea = globalSettings.GetUmbracoMvcArea(ioHelper); + var mvcArea = ioHelper.GetUmbracoMvcArea(); //if its the normal /umbraco path if (urlPath.InvariantEquals("/" + mvcArea) || urlPath.InvariantEquals("/" + mvcArea + "/")) @@ -127,12 +127,12 @@ namespace Umbraco.Core /// /// /// - internal static bool IsDefaultBackOfficeRequest(this Uri url, IGlobalSettings globalSettings) + internal static bool IsDefaultBackOfficeRequest(this Uri url, IIOHelper ioHelper) { - if (url.AbsolutePath.InvariantEquals(globalSettings.Path.TrimEnd("/")) - || url.AbsolutePath.InvariantEquals(globalSettings.Path.EnsureEndsWith('/')) - || url.AbsolutePath.InvariantEquals(globalSettings.Path.EnsureEndsWith('/') + "Default") - || url.AbsolutePath.InvariantEquals(globalSettings.Path.EnsureEndsWith('/') + "Default/")) + if (url.AbsolutePath.InvariantEquals(ioHelper.BackOfficePath.TrimEnd("/")) + || url.AbsolutePath.InvariantEquals(ioHelper.BackOfficePath.EnsureEndsWith('/')) + || url.AbsolutePath.InvariantEquals(ioHelper.BackOfficePath.EnsureEndsWith('/') + "Default") + || url.AbsolutePath.InvariantEquals(ioHelper.BackOfficePath.EnsureEndsWith('/') + "Default/")) { return true; } diff --git a/src/Umbraco.Infrastructure/Intall/InstallSteps/DatabaseInstallStep.cs b/src/Umbraco.Infrastructure/Intall/InstallSteps/DatabaseInstallStep.cs index a7b3dcc218..8c73e63b78 100644 --- a/src/Umbraco.Infrastructure/Intall/InstallSteps/DatabaseInstallStep.cs +++ b/src/Umbraco.Infrastructure/Intall/InstallSteps/DatabaseInstallStep.cs @@ -65,7 +65,7 @@ namespace Umbraco.Web.Install.InstallSteps // Remove legacy umbracoDbDsn configuration setting if it exists and connectionstring also exists if (databaseSettings != null) { - connectionStrings.RemoveConnectionString(Constants.System.UmbracoConnectionName); + connectionStrings.RemoveConnectionString(Constants.System.UmbracoConnectionName, ioHelper); } else { diff --git a/src/Umbraco.Infrastructure/Manifest/ManifestParser.cs b/src/Umbraco.Infrastructure/Manifest/ManifestParser.cs index 2074409ec8..987d3a98fb 100644 --- a/src/Umbraco.Infrastructure/Manifest/ManifestParser.cs +++ b/src/Umbraco.Infrastructure/Manifest/ManifestParser.cs @@ -220,11 +220,5 @@ namespace Umbraco.Core.Manifest return manifest; } - - // purely for tests - public IEnumerable ParseGridEditors(string text) - { - return _jsonSerializer.Deserialize>(text); - } } } diff --git a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseBuilder.cs b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseBuilder.cs index a5a58dc9f1..b92a8499fa 100644 --- a/src/Umbraco.Infrastructure/Migrations/Install/DatabaseBuilder.cs +++ b/src/Umbraco.Infrastructure/Migrations/Install/DatabaseBuilder.cs @@ -146,7 +146,7 @@ namespace Umbraco.Core.Migrations.Install private void ConfigureEmbeddedDatabaseConnection(IUmbracoDatabaseFactory factory, IIOHelper ioHelper) { - _connectionStrings.SaveConnectionString(EmbeddedDatabaseConnectionString, Constants.DbProviderNames.SqlCe); + _connectionStrings.SaveConnectionString(EmbeddedDatabaseConnectionString, Constants.DbProviderNames.SqlCe, ioHelper); var path = Path.Combine(ioHelper.GetRootDirectorySafe(), "App_Data", "Umbraco.sdf"); if (File.Exists(path) == false) @@ -169,7 +169,7 @@ namespace Umbraco.Core.Migrations.Install { const string providerName = Constants.DbProviderNames.SqlServer; - _connectionStrings.SaveConnectionString(connectionString, providerName); + _connectionStrings.SaveConnectionString(connectionString, providerName, _ioHelper); _databaseFactory.Configure(connectionString, providerName); } @@ -185,7 +185,7 @@ namespace Umbraco.Core.Migrations.Install { var connectionString = GetDatabaseConnectionString(server, databaseName, user, password, databaseProvider, out var providerName); - _connectionStrings.SaveConnectionString(connectionString, providerName); + _connectionStrings.SaveConnectionString(connectionString, providerName, _ioHelper); _databaseFactory.Configure(connectionString, providerName); } @@ -216,7 +216,7 @@ namespace Umbraco.Core.Migrations.Install public void ConfigureIntegratedSecurityDatabaseConnection(string server, string databaseName) { var connectionString = GetIntegratedSecurityDatabaseConnectionString(server, databaseName); - _connectionStrings.SaveConnectionString(connectionString, Constants.DbProviderNames.SqlServer); + _connectionStrings.SaveConnectionString(connectionString, Constants.DbProviderNames.SqlServer, _ioHelper); _databaseFactory.Configure(connectionString, Constants.DbProviderNames.SqlServer); } diff --git a/src/Umbraco.Infrastructure/Models/Mapping/ContentTypeMapDefinition.cs b/src/Umbraco.Infrastructure/Models/Mapping/ContentTypeMapDefinition.cs index f7a2d6376b..59f63f4f15 100644 --- a/src/Umbraco.Infrastructure/Models/Mapping/ContentTypeMapDefinition.cs +++ b/src/Umbraco.Infrastructure/Models/Mapping/ContentTypeMapDefinition.cs @@ -191,7 +191,7 @@ namespace Umbraco.Web.Models.Mapping target.Icon = source.Icon; target.IconFilePath = target.IconIsClass ? string.Empty - : $"{_globalSettings.Path.EnsureEndsWith("/")}images/umbraco/{source.Icon}"; + : $"{_ioHelper.BackOfficePath.EnsureEndsWith("/")}images/umbraco/{source.Icon}"; target.Trashed = source.Trashed; target.Id = source.Id; @@ -497,7 +497,7 @@ namespace Umbraco.Web.Models.Mapping target.Icon = source.Icon; target.IconFilePath = target.IconIsClass ? string.Empty - : $"{_globalSettings.Path.EnsureEndsWith("/")}images/umbraco/{source.Icon}"; + : $"{_ioHelper.BackOfficePath.EnsureEndsWith("/")}images/umbraco/{source.Icon}"; target.Id = source.Id; target.IsContainer = source.IsContainer; target.IsElement = source.IsElement; @@ -540,7 +540,7 @@ namespace Umbraco.Web.Models.Mapping target.Icon = source.Icon; target.IconFilePath = target.IconIsClass ? string.Empty - : $"{_globalSettings.Path.EnsureEndsWith("/")}images/umbraco/{source.Icon}"; + : $"{_ioHelper.BackOfficePath.EnsureEndsWith("/")}images/umbraco/{source.Icon}"; target.Id = source.Id; target.IsContainer = source.IsContainer; target.IsElement = source.IsElement; diff --git a/src/Umbraco.Infrastructure/Persistence/UmbracoDatabaseFactory.cs b/src/Umbraco.Infrastructure/Persistence/UmbracoDatabaseFactory.cs index 9474e02d38..a93c8db409 100644 --- a/src/Umbraco.Infrastructure/Persistence/UmbracoDatabaseFactory.cs +++ b/src/Umbraco.Infrastructure/Persistence/UmbracoDatabaseFactory.cs @@ -27,8 +27,9 @@ namespace Umbraco.Core.Persistence // TODO: this class needs not be disposable! internal class UmbracoDatabaseFactory : DisposableObjectSlim, IUmbracoDatabaseFactory { - private readonly Configs _configs; private readonly IDbProviderFactoryCreator _dbProviderFactoryCreator; + private readonly IGlobalSettings _globalSettings; + private readonly IConnectionStrings _connectionStrings; private readonly Lazy _mappers; private readonly ILogger _logger; @@ -71,27 +72,28 @@ namespace Umbraco.Core.Persistence /// Initializes a new instance of the . /// /// Used by core runtime. - public UmbracoDatabaseFactory(ILogger logger, Lazy mappers, Configs configs, IDbProviderFactoryCreator dbProviderFactoryCreator) - : this(Constants.System.UmbracoConnectionName, logger, mappers, configs, dbProviderFactoryCreator) + public UmbracoDatabaseFactory(ILogger logger, IGlobalSettings globalSettings, IConnectionStrings connectionStrings, Lazy mappers,IDbProviderFactoryCreator dbProviderFactoryCreator) + : this(Constants.System.UmbracoConnectionName, globalSettings, connectionStrings, logger, mappers, dbProviderFactoryCreator) { - _configs = configs; + } /// /// Initializes a new instance of the . /// /// Used by the other ctor and in tests. - public UmbracoDatabaseFactory(string connectionStringName, ILogger logger, Lazy mappers, Configs configs, IDbProviderFactoryCreator dbProviderFactoryCreator) + public UmbracoDatabaseFactory(string connectionStringName, IGlobalSettings globalSettings, IConnectionStrings connectionStrings, ILogger logger, Lazy mappers, IDbProviderFactoryCreator dbProviderFactoryCreator) { if (connectionStringName == null) throw new ArgumentNullException(nameof(connectionStringName)); if (string.IsNullOrWhiteSpace(connectionStringName)) throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(connectionStringName)); + _globalSettings = globalSettings; + _connectionStrings = connectionStrings; _mappers = mappers ?? throw new ArgumentNullException(nameof(mappers)); - _configs = configs; _dbProviderFactoryCreator = dbProviderFactoryCreator ?? throw new ArgumentNullException(nameof(dbProviderFactoryCreator)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - var settings = configs.ConnectionStrings()[connectionStringName]; + var settings = connectionStrings[connectionStringName]; if (settings == null) { @@ -161,7 +163,7 @@ namespace Umbraco.Core.Persistence { // replace NPoco database type by a more efficient one - var setting = _configs.Global().DatabaseFactoryServerVersion; + var setting = _globalSettings.DatabaseFactoryServerVersion; var fromSettings = false; if (setting.IsNullOrWhiteSpace() || !setting.StartsWith("SqlServer.") diff --git a/src/Umbraco.Infrastructure/Runtime/CoreInitialComposer.cs b/src/Umbraco.Infrastructure/Runtime/CoreInitialComposer.cs index 7bb5c77e80..5f4e9aec1d 100644 --- a/src/Umbraco.Infrastructure/Runtime/CoreInitialComposer.cs +++ b/src/Umbraco.Infrastructure/Runtime/CoreInitialComposer.cs @@ -1,12 +1,15 @@ using System; +using System.IO; using Umbraco.Core.Cache; using Umbraco.Core.Composing; using Umbraco.Core.Composing.CompositionExtensions; using Umbraco.Core.Configuration; +using Umbraco.Core.Configuration.Grid; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Dashboards; using Umbraco.Core.Hosting; using Umbraco.Core.Dictionary; +using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Manifest; using Umbraco.Core.Migrations; @@ -169,6 +172,9 @@ namespace Umbraco.Core.Runtime // will be injected in controllers when needed to invoke rest endpoints on Our composition.RegisterUnique(); composition.RegisterUnique(); + + // Grid config is not a real config file as we know them + composition.RegisterUnique(); } } } diff --git a/src/Umbraco.Infrastructure/Runtime/CoreRuntime.cs b/src/Umbraco.Infrastructure/Runtime/CoreRuntime.cs index 7b1aff1a4b..74a1c06eec 100644 --- a/src/Umbraco.Infrastructure/Runtime/CoreRuntime.cs +++ b/src/Umbraco.Infrastructure/Runtime/CoreRuntime.cs @@ -27,6 +27,8 @@ namespace Umbraco.Core.Runtime private IFactory _factory; private RuntimeState _state; private readonly IUmbracoBootPermissionChecker _umbracoBootPermissionChecker; + private readonly IGlobalSettings _globalSettings; + private readonly IConnectionStrings _connectionStrings; public CoreRuntime( @@ -54,6 +56,10 @@ namespace Umbraco.Core.Runtime Logger = logger; MainDom = mainDom; + _globalSettings = Configs.Global(); + _connectionStrings = configs.ConnectionStrings(); + + // runtime state // beware! must use '() => _factory.GetInstance()' and NOT '_factory.GetInstance' // as the second one captures the current value (null) and therefore fails @@ -412,7 +418,7 @@ namespace Umbraco.Core.Runtime /// /// This is strictly internal, for tests only. protected internal virtual IUmbracoDatabaseFactory GetDatabaseFactory() - => new UmbracoDatabaseFactory(Logger, new Lazy(() => _factory.GetInstance()), Configs, DbProviderFactoryCreator); + => new UmbracoDatabaseFactory(Logger, _globalSettings, _connectionStrings, new Lazy(() => _factory.GetInstance()), DbProviderFactoryCreator); #endregion diff --git a/src/Umbraco.Infrastructure/Runtime/SqlMainDomLock.cs b/src/Umbraco.Infrastructure/Runtime/SqlMainDomLock.cs index 4e1feb221a..6d73934387 100644 --- a/src/Umbraco.Infrastructure/Runtime/SqlMainDomLock.cs +++ b/src/Umbraco.Infrastructure/Runtime/SqlMainDomLock.cs @@ -28,16 +28,18 @@ namespace Umbraco.Core.Runtime private bool _hasError; private object _locker = new object(); - public SqlMainDomLock(ILogger logger, Configs configs, IDbProviderFactoryCreator dbProviderFactoryCreator) + public SqlMainDomLock(ILogger logger, IGlobalSettings globalSettings, IConnectionStrings connectionStrings, IDbProviderFactoryCreator dbProviderFactoryCreator) { // unique id for our appdomain, this is more unique than the appdomain id which is just an INT counter to its safer _lockId = Guid.NewGuid().ToString(); _logger = logger; _dbFactory = new UmbracoDatabaseFactory( Constants.System.UmbracoConnectionName, + globalSettings, + connectionStrings, _logger, new Lazy(() => new MapperCollection(Enumerable.Empty())), - configs, dbProviderFactoryCreator + dbProviderFactoryCreator ); } diff --git a/src/Umbraco.Infrastructure/Trees/TreeNode.cs b/src/Umbraco.Infrastructure/Trees/TreeNode.cs index cc130b1b97..7d3c657207 100644 --- a/src/Umbraco.Infrastructure/Trees/TreeNode.cs +++ b/src/Umbraco.Infrastructure/Trees/TreeNode.cs @@ -112,7 +112,7 @@ namespace Umbraco.Web.Models.Trees return Current.IOHelper.ResolveUrl("~" + Icon.TrimStart('~')); //legacy icon path - return string.Format("{0}images/umbraco/{1}", Current.Configs.Global().Path.EnsureEndsWith("/"), Icon); + return string.Format("{0}images/umbraco/{1}", Current.IOHelper.BackOfficePath.EnsureEndsWith("/"), Icon); } } diff --git a/src/Umbraco.ModelsBuilder.Embedded/Building/ModelsGenerator.cs b/src/Umbraco.ModelsBuilder.Embedded/Building/ModelsGenerator.cs index 192f049930..648a2e76fa 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Building/ModelsGenerator.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/Building/ModelsGenerator.cs @@ -1,6 +1,7 @@ using System.IO; using System.Text; using Umbraco.Core.Configuration; +using Umbraco.Core.IO; namespace Umbraco.ModelsBuilder.Embedded.Building { @@ -9,20 +10,23 @@ namespace Umbraco.ModelsBuilder.Embedded.Building private readonly UmbracoServices _umbracoService; private readonly IModelsBuilderConfig _config; private readonly OutOfDateModelsStatus _outOfDateModels; + private readonly IIOHelper _ioHelper; - public ModelsGenerator(UmbracoServices umbracoService, IModelsBuilderConfig config, OutOfDateModelsStatus outOfDateModels) + public ModelsGenerator(UmbracoServices umbracoService, IModelsBuilderConfig config, OutOfDateModelsStatus outOfDateModels, IIOHelper ioHelper) { _umbracoService = umbracoService; _config = config; _outOfDateModels = outOfDateModels; + _ioHelper = ioHelper; } internal void GenerateModels() { - if (!Directory.Exists(_config.ModelsDirectory)) - Directory.CreateDirectory(_config.ModelsDirectory); + var modelsDirectory = _config.ModelsDirectoryAbsolute(_ioHelper); + if (!Directory.Exists(modelsDirectory)) + Directory.CreateDirectory(modelsDirectory); - foreach (var file in Directory.GetFiles(_config.ModelsDirectory, "*.generated.cs")) + foreach (var file in Directory.GetFiles(modelsDirectory, "*.generated.cs")) File.Delete(file); var typeModels = _umbracoService.GetAllTypes(); @@ -33,7 +37,7 @@ namespace Umbraco.ModelsBuilder.Embedded.Building { var sb = new StringBuilder(); builder.Generate(sb, typeModel); - var filename = Path.Combine(_config.ModelsDirectory, typeModel.ClrName + ".generated.cs"); + var filename = Path.Combine(modelsDirectory, typeModel.ClrName + ".generated.cs"); File.WriteAllText(filename, sb.ToString()); } diff --git a/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComposer.cs b/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComposer.cs index 2914fe1b12..e582301740 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComposer.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/Compose/ModelsBuilderComposer.cs @@ -31,7 +31,7 @@ namespace Umbraco.ModelsBuilder.Embedded.Compose composition.RegisterUnique(); composition.RegisterUnique(); composition.RegisterUnique(); - + if (composition.Configs.ModelsBuilder().ModelsMode == ModelsMode.PureLive) ComposeForLiveModels(composition); else if (composition.Configs.ModelsBuilder().EnableFactory) diff --git a/src/Umbraco.ModelsBuilder.Embedded/ModelsGenerationError.cs b/src/Umbraco.ModelsBuilder.Embedded/ModelsGenerationError.cs index 5b498fd5f3..f8f6e8c7bc 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/ModelsGenerationError.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/ModelsGenerationError.cs @@ -2,16 +2,19 @@ using System.IO; using System.Text; using Umbraco.Core.Configuration; +using Umbraco.Core.IO; namespace Umbraco.ModelsBuilder.Embedded { public sealed class ModelsGenerationError { private readonly IModelsBuilderConfig _config; + private readonly IIOHelper _ioHelper; - public ModelsGenerationError(IModelsBuilderConfig config) + public ModelsGenerationError(IModelsBuilderConfig config, IIOHelper ioHelper) { _config = config; + _ioHelper = ioHelper; } public void Clear() @@ -56,7 +59,7 @@ namespace Umbraco.ModelsBuilder.Embedded private string GetErrFile() { - var modelsDirectory = _config.ModelsDirectory; + var modelsDirectory = _config.ModelsDirectoryAbsolute(_ioHelper); if (!Directory.Exists(modelsDirectory)) return null; diff --git a/src/Umbraco.ModelsBuilder.Embedded/OutOfDateModelsStatus.cs b/src/Umbraco.ModelsBuilder.Embedded/OutOfDateModelsStatus.cs index 0e93030438..b8105eeef2 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/OutOfDateModelsStatus.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/OutOfDateModelsStatus.cs @@ -1,5 +1,6 @@ using System.IO; using Umbraco.Core.Configuration; +using Umbraco.Core.IO; using Umbraco.Web.Cache; namespace Umbraco.ModelsBuilder.Embedded @@ -7,10 +8,12 @@ namespace Umbraco.ModelsBuilder.Embedded public sealed class OutOfDateModelsStatus { private readonly IModelsBuilderConfig _config; + private readonly IIOHelper _ioHelper; - public OutOfDateModelsStatus(IModelsBuilderConfig config) + public OutOfDateModelsStatus(IModelsBuilderConfig config, IIOHelper ioHelper) { _config = config; + _ioHelper = ioHelper; } internal void Install() @@ -25,7 +28,7 @@ namespace Umbraco.ModelsBuilder.Embedded private string GetFlagPath() { - var modelsDirectory = _config.ModelsDirectory; + var modelsDirectory = _config.ModelsDirectoryAbsolute(_ioHelper); if (!Directory.Exists(modelsDirectory)) Directory.CreateDirectory(modelsDirectory); return Path.Combine(modelsDirectory, "ood.flag"); diff --git a/src/Umbraco.ModelsBuilder.Embedded/PureLiveModelFactory.cs b/src/Umbraco.ModelsBuilder.Embedded/PureLiveModelFactory.cs index bef2fa8414..5db79de977 100644 --- a/src/Umbraco.ModelsBuilder.Embedded/PureLiveModelFactory.cs +++ b/src/Umbraco.ModelsBuilder.Embedded/PureLiveModelFactory.cs @@ -14,6 +14,7 @@ using System.Web.WebPages.Razor; using Umbraco.Core.Configuration; using Umbraco.Core; using Umbraco.Core.Hosting; +using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models.PublishedContent; using Umbraco.ModelsBuilder.Embedded.Building; @@ -42,15 +43,22 @@ namespace Umbraco.ModelsBuilder.Embedded private readonly IModelsBuilderConfig _config; private readonly IHostingEnvironment _hostingEnvironment; + private readonly IIOHelper _ioHelper; private readonly ModelsGenerationError _errors; - public PureLiveModelFactory(Lazy umbracoServices, IProfilingLogger logger, IModelsBuilderConfig config, IHostingEnvironment hostingEnvironment) + public PureLiveModelFactory( + Lazy umbracoServices, + IProfilingLogger logger, + IModelsBuilderConfig config, + IHostingEnvironment hostingEnvironment, + IIOHelper ioHelper) { _umbracoServices = umbracoServices; _logger = logger; _config = config; _hostingEnvironment = hostingEnvironment; - _errors = new ModelsGenerationError(config); + _ioHelper = ioHelper; + _errors = new ModelsGenerationError(config, ioHelper); _ver = 1; // zero is for when we had no version _skipver = -1; // nothing to skip @@ -58,7 +66,7 @@ namespace Umbraco.ModelsBuilder.Embedded if (!_hostingEnvironment.IsHosted) return; - var modelsDirectory = _config.ModelsDirectory; + var modelsDirectory = _config.ModelsDirectoryAbsolute(_ioHelper); if (!Directory.Exists(modelsDirectory)) Directory.CreateDirectory(modelsDirectory); @@ -208,7 +216,7 @@ namespace Umbraco.ModelsBuilder.Embedded _hasModels = false; _pendingRebuild = true; - var modelsDirectory = _config.ModelsDirectory; + var modelsDirectory = _config.ModelsDirectoryAbsolute(_ioHelper); if (!Directory.Exists(modelsDirectory)) Directory.CreateDirectory(modelsDirectory); @@ -330,7 +338,7 @@ namespace Umbraco.ModelsBuilder.Embedded private Assembly GetModelsAssembly(bool forceRebuild) { - var modelsDirectory = _config.ModelsDirectory; + var modelsDirectory = _config.ModelsDirectoryAbsolute(_ioHelper); if (!Directory.Exists(modelsDirectory)) Directory.CreateDirectory(modelsDirectory); @@ -552,7 +560,7 @@ namespace Umbraco.ModelsBuilder.Embedded private string GenerateModelsCode(IList typeModels) { - var modelsDirectory = _config.ModelsDirectory; + var modelsDirectory = _config.ModelsDirectoryAbsolute(_ioHelper); if (!Directory.Exists(modelsDirectory)) Directory.CreateDirectory(modelsDirectory); diff --git a/src/Umbraco.Tests.Common/SettingsForTests.cs b/src/Umbraco.Tests.Common/SettingsForTests.cs index 3f39881ff8..6b484bbcfc 100644 --- a/src/Umbraco.Tests.Common/SettingsForTests.cs +++ b/src/Umbraco.Tests.Common/SettingsForTests.cs @@ -1,4 +1,5 @@ using Moq; +using Semver; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.UmbracoSettings; @@ -13,14 +14,16 @@ namespace Umbraco.Tests.Common { } - public IGlobalSettings GenerateMockGlobalSettings(IUmbracoVersion umbVersion, IIOHelper ioHelper) + public IGlobalSettings GenerateMockGlobalSettings(IUmbracoVersion umbVersion = null) { + var semanticVersion = umbVersion?.SemanticVersion ?? new SemVersion(9); + var config = Mock.Of( settings => - settings.ConfigurationStatus == umbVersion.SemanticVersion.ToSemanticString() && + settings.ConfigurationStatus == semanticVersion.ToSemanticString() && settings.UseHttps == false && settings.HideTopLevelNodeFromPath == false && - settings.Path == ioHelper.ResolveUrl("~/umbraco") && + settings.Path == "~/umbraco" && settings.TimeOutInMinutes == 20 && settings.DefaultUILanguage == "en" && settings.ReservedPaths == (GlobalSettings.StaticReservedPaths + "~/umbraco") && @@ -102,12 +105,12 @@ namespace Umbraco.Tests.Common private IGlobalSettings _defaultGlobalSettings; private IHostingSettings _defaultHostingSettings; - - public IGlobalSettings GetDefaultGlobalSettings(IUmbracoVersion umbVersion, IIOHelper ioHelper) + + public IGlobalSettings GetDefaultGlobalSettings(IUmbracoVersion umbVersion) { if (_defaultGlobalSettings == null) { - _defaultGlobalSettings = GenerateMockGlobalSettings(umbVersion, ioHelper); + _defaultGlobalSettings = GenerateMockGlobalSettings(umbVersion); } return _defaultGlobalSettings; } diff --git a/src/Umbraco.Tests.Common/TestHelperBase.cs b/src/Umbraco.Tests.Common/TestHelperBase.cs index 3d6b4617b5..a5810715fb 100644 --- a/src/Umbraco.Tests.Common/TestHelperBase.cs +++ b/src/Umbraco.Tests.Common/TestHelperBase.cs @@ -30,15 +30,15 @@ namespace Umbraco.Tests.Common public TestHelperBase() { SettingsForTests = new SettingsForTests(); - IOHelper = new IOHelper(GetHostingEnvironment()); + IOHelper = new IOHelper(GetHostingEnvironment(), SettingsForTests.GenerateMockGlobalSettings()); MainDom = new MainDom(Mock.Of(), GetHostingEnvironment(), new MainDomSemaphoreLock(Mock.Of(), GetHostingEnvironment())); - UriUtility = new UriUtility(GetHostingEnvironment()); + UriUtility = new UriUtility(GetHostingEnvironment()); } public ITypeFinder GetTypeFinder() { - - var typeFinder = new TypeFinder(Mock.Of(), + + var typeFinder = new TypeFinder(Mock.Of(), new DefaultUmbracoAssemblyProvider(typeof(TestHelperBase).Assembly)); return typeFinder; } @@ -50,7 +50,7 @@ namespace Umbraco.Tests.Common public Configs GetConfigs() { - return GetConfigsFactory().Create(IOHelper, Mock.Of()); + return GetConfigsFactory().Create(); } public IRuntimeState GetRuntimeState() { diff --git a/src/Umbraco.Tests/Components/ComponentTests.cs b/src/Umbraco.Tests/Components/ComponentTests.cs index 7dc6025b0a..a41d86ee2e 100644 --- a/src/Umbraco.Tests/Components/ComponentTests.cs +++ b/src/Umbraco.Tests/Components/ComponentTests.cs @@ -33,7 +33,7 @@ namespace Umbraco.Tests.Components var logger = Mock.Of(); var typeFinder = TestHelper.GetTypeFinder(); - var f = new UmbracoDatabaseFactory(logger, new Lazy(() => new MapperCollection(Enumerable.Empty())), TestHelper.GetConfigs(), TestHelper.DbProviderFactoryCreator); + var f = new UmbracoDatabaseFactory(logger, SettingsForTests.GetDefaultGlobalSettings(), Mock.Of(), new Lazy(() => new MapperCollection(Enumerable.Empty())), TestHelper.DbProviderFactoryCreator); var fs = new FileSystems(mock.Object, logger, TestHelper.IOHelper, SettingsForTests.GenerateMockGlobalSettings()); var coreDebug = Mock.Of(); var mediaFileSystem = Mock.Of(); diff --git a/src/Umbraco.Tests/Configurations/GlobalSettingsTests.cs b/src/Umbraco.Tests/Configurations/GlobalSettingsTests.cs index 37e2636bf4..b171199e25 100644 --- a/src/Umbraco.Tests/Configurations/GlobalSettingsTests.cs +++ b/src/Umbraco.Tests/Configurations/GlobalSettingsTests.cs @@ -1,6 +1,7 @@ using Moq; using NUnit.Framework; using Umbraco.Core.Configuration; +using Umbraco.Core.IO; using Umbraco.Tests.TestHelpers; namespace Umbraco.Tests.Configurations @@ -30,13 +31,15 @@ namespace Umbraco.Tests.Configurations [TestCase("~/some-wacky/nestedPath", "/MyVirtualDir/NestedVDir/", "some-wacky-nestedpath")] public void Umbraco_Mvc_Area(string path, string rootPath, string outcome) { + var globalSettings = SettingsForTests.GenerateMockGlobalSettings(); + var ioHelper = new IOHelper(TestHelper.GetHostingEnvironment(), globalSettings); var globalSettingsMock = Mock.Get(globalSettings); - globalSettingsMock.Setup(x => x.Path).Returns(() => TestHelper.IOHelper.ResolveUrl(path)); + globalSettingsMock.Setup(x => x.Path).Returns(() => path); - TestHelper.IOHelper.Root = rootPath; - Assert.AreEqual(outcome, globalSettings.GetUmbracoMvcAreaNoCache(IOHelper)); + ioHelper.Root = rootPath; + Assert.AreEqual(outcome, ioHelper.GetUmbracoMvcAreaNoCache()); } diff --git a/src/Umbraco.Tests/CoreThings/UriExtensionsTests.cs b/src/Umbraco.Tests/CoreThings/UriExtensionsTests.cs index 5c0ca7a582..2fda471b70 100644 --- a/src/Umbraco.Tests/CoreThings/UriExtensionsTests.cs +++ b/src/Umbraco.Tests/CoreThings/UriExtensionsTests.cs @@ -47,9 +47,8 @@ namespace Umbraco.Tests.CoreThings { var ioHelper = TestHelper.IOHelper; ioHelper.Root = virtualPath; - var globalConfig = SettingsForTests.GenerateMockGlobalSettings(); var source = new Uri(input); - Assert.AreEqual(expected, source.IsBackOfficeRequest(virtualPath, globalConfig, ioHelper)); + Assert.AreEqual(expected, source.IsBackOfficeRequest(virtualPath, ioHelper)); } [TestCase("http://www.domain.com/install", true)] diff --git a/src/Umbraco.Tests/ModelsBuilder/ConfigTests.cs b/src/Umbraco.Tests/ModelsBuilder/ConfigTests.cs index 4a9e8704ec..d2acc90439 100644 --- a/src/Umbraco.Tests/ModelsBuilder/ConfigTests.cs +++ b/src/Umbraco.Tests/ModelsBuilder/ConfigTests.cs @@ -2,7 +2,7 @@ using NUnit.Framework; using Umbraco.Configuration; using Umbraco.Core; -using Umbraco.Tests.TestHelpers; +using Umbraco.Core.Configuration; namespace Umbraco.Tests.ModelsBuilder { @@ -12,21 +12,21 @@ namespace Umbraco.Tests.ModelsBuilder [Test] public void Test1() { - var config = new ModelsBuilderConfig(TestHelper.IOHelper, modelsNamespace: "test1"); + var config = new ModelsBuilderConfig(modelsNamespace: "test1"); Assert.AreEqual("test1", config.ModelsNamespace); } [Test] public void Test2() { - var config = new ModelsBuilderConfig(TestHelper.IOHelper, modelsNamespace: "test2"); + var config = new ModelsBuilderConfig(modelsNamespace: "test2"); Assert.AreEqual("test2", config.ModelsNamespace); } [Test] public void DefaultModelsNamespace() { - var config = new ModelsBuilderConfig(TestHelper.IOHelper); + var config = new ModelsBuilderConfig(); Assert.AreEqual(Constants.ModelsBuilder.DefaultModelsNamespace, config.ModelsNamespace); } @@ -35,7 +35,7 @@ namespace Umbraco.Tests.ModelsBuilder [TestCase("c:/path/to/root", "c:/another/path/to/elsewhere", true, "c:\\another\\path\\to\\elsewhere")] public void GetModelsDirectoryTests(string root, string config, bool acceptUnsafe, string expected) { - Assert.AreEqual(expected, ModelsBuilderConfig.GetModelsDirectory(root, config, acceptUnsafe)); + Assert.AreEqual(expected, ModelsBuilderConfigExtensions.GetModelsDirectory(root, config, acceptUnsafe)); } [TestCase("c:/path/to/root", "~/../../dir/models", false)] @@ -44,7 +44,7 @@ namespace Umbraco.Tests.ModelsBuilder { Assert.Throws(() => { - var modelsDirectory = ModelsBuilderConfig.GetModelsDirectory(root, config, acceptUnsafe); + var modelsDirectory = ModelsBuilderConfigExtensions.GetModelsDirectory(root, config, acceptUnsafe); }); } } diff --git a/src/Umbraco.Tests/Persistence/DatabaseContextTests.cs b/src/Umbraco.Tests/Persistence/DatabaseContextTests.cs index 531f08a72d..52f2365cbc 100644 --- a/src/Umbraco.Tests/Persistence/DatabaseContextTests.cs +++ b/src/Umbraco.Tests/Persistence/DatabaseContextTests.cs @@ -37,7 +37,9 @@ namespace Umbraco.Tests.Persistence _sqlSyntaxProviders = new[] { (ISqlSyntaxProvider) _sqlCeSyntaxProvider }; _logger = Mock.Of(); _umbracoVersion = TestHelper.GetUmbracoVersion(); - _databaseFactory = new UmbracoDatabaseFactory(_logger, new Lazy(() => Mock.Of()), TestHelper.GetConfigs(), TestHelper.DbProviderFactoryCreator); + var globalSettings = TestHelper.GetConfigs().Global(); + var connectionStrings = TestHelper.GetConfigs().ConnectionStrings(); + _databaseFactory = new UmbracoDatabaseFactory(_logger, globalSettings, connectionStrings, new Lazy(() => Mock.Of()), TestHelper.DbProviderFactoryCreator); } [TearDown] diff --git a/src/Umbraco.Tests/PublishedContent/NuCacheChildrenTests.cs b/src/Umbraco.Tests/PublishedContent/NuCacheChildrenTests.cs index abadb7dde4..de411c96ec 100644 --- a/src/Umbraco.Tests/PublishedContent/NuCacheChildrenTests.cs +++ b/src/Umbraco.Tests/PublishedContent/NuCacheChildrenTests.cs @@ -61,7 +61,7 @@ namespace Umbraco.Tests.PublishedContent var configs = TestHelper.GetConfigs(); Mock.Get(factory).Setup(x => x.GetInstance(typeof(Configs))).Returns(configs); - var globalSettings = new GlobalSettings(TestHelper.IOHelper); + var globalSettings = new GlobalSettings(); var hostingEnvironment = Mock.Of(); configs.Add(TestHelpers.SettingsForTests.GenerateMockContentSettings); configs.Add(() => globalSettings); diff --git a/src/Umbraco.Tests/PublishedContent/NuCacheTests.cs b/src/Umbraco.Tests/PublishedContent/NuCacheTests.cs index 4c6ed34ccb..096f2dcf59 100644 --- a/src/Umbraco.Tests/PublishedContent/NuCacheTests.cs +++ b/src/Umbraco.Tests/PublishedContent/NuCacheTests.cs @@ -54,7 +54,7 @@ namespace Umbraco.Tests.PublishedContent var configs = TestHelper.GetConfigs(); Mock.Get(factory).Setup(x => x.GetInstance(typeof(Configs))).Returns(configs); - var globalSettings = new GlobalSettings(TestHelper.IOHelper); + var globalSettings = new GlobalSettings(); configs.Add(TestHelpers.SettingsForTests.GenerateMockContentSettings); configs.Add(() => globalSettings); diff --git a/src/Umbraco.Tests/Routing/GetContentUrlsTests.cs b/src/Umbraco.Tests/Routing/GetContentUrlsTests.cs index 6393211791..4f11802b43 100644 --- a/src/Umbraco.Tests/Routing/GetContentUrlsTests.cs +++ b/src/Umbraco.Tests/Routing/GetContentUrlsTests.cs @@ -14,6 +14,7 @@ using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Web; using Umbraco.Web.Routing; using Umbraco.Tests.Common; +using SettingsForTests = Umbraco.Tests.TestHelpers.SettingsForTests; namespace Umbraco.Tests.Routing { @@ -77,7 +78,7 @@ namespace Umbraco.Tests.Routing content.Path = "-1,1046"; content.Published = true; - var umbracoSettings = Current.Configs.RequestHandler(); + var umbracoSettings = SettingsForTests.GenerateMockRequestHandlerSettings(); var umbContext = GetUmbracoContext("http://localhost:8000"); var umbracoContextAccessor = new TestUmbracoContextAccessor(umbContext); @@ -122,7 +123,7 @@ namespace Umbraco.Tests.Routing child.Path = "-1,1046,1173"; child.Published = true; - var umbracoSettings = Current.Configs.RequestHandler(); + var umbracoSettings = SettingsForTests.GenerateMockRequestHandlerSettings(); var umbContext = GetUmbracoContext("http://localhost:8000"); diff --git a/src/Umbraco.Tests/Routing/UmbracoModuleTests.cs b/src/Umbraco.Tests/Routing/UmbracoModuleTests.cs index e4ee8a3580..561a6d945e 100644 --- a/src/Umbraco.Tests/Routing/UmbracoModuleTests.cs +++ b/src/Umbraco.Tests/Routing/UmbracoModuleTests.cs @@ -37,14 +37,14 @@ namespace Umbraco.Tests.Routing _module = new UmbracoInjectedModule ( - globalSettings, runtime, logger, null, // FIXME: PublishedRouter complexities... Mock.Of(), new RoutableDocumentFilter(globalSettings, IOHelper), UriUtility, - AppCaches.RequestCache + AppCaches.RequestCache, + IOHelper ); runtime.Level = RuntimeLevel.Run; diff --git a/src/Umbraco.Tests/Runtimes/CoreRuntimeTests.cs b/src/Umbraco.Tests/Runtimes/CoreRuntimeTests.cs index 9fb77ef59d..3c0097f27b 100644 --- a/src/Umbraco.Tests/Runtimes/CoreRuntimeTests.cs +++ b/src/Umbraco.Tests/Runtimes/CoreRuntimeTests.cs @@ -90,16 +90,17 @@ namespace Umbraco.Tests.Runtimes private static readonly IIOHelper _ioHelper = TestHelper.IOHelper; private static readonly IProfiler _profiler = new TestProfiler(); private static readonly Configs _configs = GetConfigs(); - private static readonly IGlobalSettings _globalSettings = _configs.Global(); - private static readonly IHostingSettings _hostingSettings = _configs.Hosting(); + private static readonly IGlobalSettings _globalSettings = SettingsForTests.GetDefaultGlobalSettings(); + private static readonly IHostingSettings _hostingSettings = SettingsForTests.GetDefaultHostingSettings(); + private static readonly IContentSettings _contentSettings = SettingsForTests.GenerateMockContentSettings(); private static readonly IWebRoutingSettings _settings = _configs.WebRouting(); private static Configs GetConfigs() { - var configs = new ConfigsFactory().Create(_ioHelper, _logger); - configs.Add(SettingsForTests.GetDefaultGlobalSettings); - configs.Add(SettingsForTests.GenerateMockContentSettings); - configs.Add(SettingsForTests.GetDefaultHostingSettings); + var configs = new ConfigsFactory().Create(); + configs.Add(() => _globalSettings); + configs.Add(() => _contentSettings); + configs.Add(() => _hostingSettings); return configs; } diff --git a/src/Umbraco.Tests/Runtimes/StandaloneTests.cs b/src/Umbraco.Tests/Runtimes/StandaloneTests.cs index a0486218e4..213074caa7 100644 --- a/src/Umbraco.Tests/Runtimes/StandaloneTests.cs +++ b/src/Umbraco.Tests/Runtimes/StandaloneTests.cs @@ -62,7 +62,9 @@ namespace Umbraco.Tests.Runtimes var profiler = new LogProfiler(logger); var profilingLogger = new ProfilingLogger(logger, profiler); var appCaches = AppCaches.Disabled; - var databaseFactory = new UmbracoDatabaseFactory(logger, new Lazy(() => factory.GetInstance()), TestHelper.GetConfigs(), TestHelper.DbProviderFactoryCreator); + var globalSettings = TestHelper.GetConfigs().Global(); + var connectionStrings = TestHelper.GetConfigs().ConnectionStrings(); + var databaseFactory = new UmbracoDatabaseFactory(logger,globalSettings, connectionStrings, new Lazy(() => factory.GetInstance()), TestHelper.DbProviderFactoryCreator); var typeFinder = new TypeFinder(logger, new DefaultUmbracoAssemblyProvider(GetType().Assembly)); var ioHelper = TestHelper.IOHelper; var hostingEnvironment = Mock.Of(); diff --git a/src/Umbraco.Tests/Security/BackOfficeCookieManagerTests.cs b/src/Umbraco.Tests/Security/BackOfficeCookieManagerTests.cs index 2f4f77cee7..8b84579fec 100644 --- a/src/Umbraco.Tests/Security/BackOfficeCookieManagerTests.cs +++ b/src/Umbraco.Tests/Security/BackOfficeCookieManagerTests.cs @@ -42,7 +42,7 @@ namespace Umbraco.Tests.Security var runtime = Mock.Of(x => x.Level == RuntimeLevel.Install); var mgr = new BackOfficeCookieManager( - Mock.Of(accessor => accessor.UmbracoContext == umbracoContext), runtime, TestObjects.GetGlobalSettings(), IOHelper, AppCaches.RequestCache); + Mock.Of(accessor => accessor.UmbracoContext == umbracoContext), runtime, IOHelper, AppCaches.RequestCache); var result = mgr.ShouldAuthenticateRequest(Mock.Of(), new Uri("http://localhost/umbraco")); @@ -65,7 +65,7 @@ namespace Umbraco.Tests.Security new AspNetCookieManager(httpContextAccessor)); var runtime = Mock.Of(x => x.Level == RuntimeLevel.Run); - var mgr = new BackOfficeCookieManager(Mock.Of(accessor => accessor.UmbracoContext == umbCtx), runtime, TestObjects.GetGlobalSettings(), IOHelper, AppCaches.RequestCache); + var mgr = new BackOfficeCookieManager(Mock.Of(accessor => accessor.UmbracoContext == umbCtx), runtime, IOHelper, AppCaches.RequestCache); var request = new Mock(); request.Setup(owinRequest => owinRequest.Uri).Returns(new Uri("http://localhost/umbraco")); diff --git a/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs b/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs index ccb616989b..fc3d3f6b52 100644 --- a/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs +++ b/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs @@ -7,7 +7,7 @@ namespace Umbraco.Tests.TestHelpers { private static Common.SettingsForTests _settingsForTests = new Common.SettingsForTests(); - public static IGlobalSettings GenerateMockGlobalSettings() => _settingsForTests.GenerateMockGlobalSettings(TestHelper.GetUmbracoVersion(), TestHelper.IOHelper); + public static IGlobalSettings GenerateMockGlobalSettings() => _settingsForTests.GenerateMockGlobalSettings(TestHelper.GetUmbracoVersion()); /// /// Returns generated settings which can be stubbed to return whatever values necessary @@ -45,7 +45,7 @@ namespace Umbraco.Tests.TestHelpers public static void Reset() => _settingsForTests.Reset(); - internal static IGlobalSettings GetDefaultGlobalSettings() => _settingsForTests.GetDefaultGlobalSettings(TestHelper.GetUmbracoVersion(), TestHelper.IOHelper); + internal static IGlobalSettings GetDefaultGlobalSettings() => _settingsForTests.GetDefaultGlobalSettings(TestHelper.GetUmbracoVersion()); internal static IHostingSettings GetDefaultHostingSettings() => _settingsForTests.GetDefaultHostingSettings(); diff --git a/src/Umbraco.Tests/TestHelpers/TestHelper.cs b/src/Umbraco.Tests/TestHelpers/TestHelper.cs index a6e91cc448..693fd73231 100644 --- a/src/Umbraco.Tests/TestHelpers/TestHelper.cs +++ b/src/Umbraco.Tests/TestHelpers/TestHelper.cs @@ -51,7 +51,7 @@ namespace Umbraco.Tests.TestHelpers public override IBackOfficeInfo GetBackOfficeInfo() => new AspNetBackOfficeInfo( - SettingsForTests.GenerateMockGlobalSettings(GetUmbracoVersion(), IOHelper), + SettingsForTests.GenerateMockGlobalSettings(GetUmbracoVersion()), TestHelper.IOHelper, Mock.Of(), SettingsForTests.GenerateMockWebRoutingSettings()); public override IHostingEnvironment GetHostingEnvironment() diff --git a/src/Umbraco.Tests/TestHelpers/TestObjects.cs b/src/Umbraco.Tests/TestHelpers/TestObjects.cs index bb342c9939..be8f7db7e8 100644 --- a/src/Umbraco.Tests/TestHelpers/TestObjects.cs +++ b/src/Umbraco.Tests/TestHelpers/TestObjects.cs @@ -244,12 +244,18 @@ namespace Umbraco.Tests.TestHelpers // mappersBuilder.AddCore(); // var mappers = mappersBuilder.CreateCollection(); var mappers = Current.Factory.GetInstance(); - databaseFactory = new UmbracoDatabaseFactory(Constants.System.UmbracoConnectionName, logger, new Lazy(() => mappers), TestHelper.GetConfigs(), TestHelper.DbProviderFactoryCreator); + databaseFactory = new UmbracoDatabaseFactory( + Constants.System.UmbracoConnectionName, + SettingsForTests.GetDefaultGlobalSettings(), + new ConnectionStrings(), + logger, + new Lazy(() => mappers), + TestHelper.DbProviderFactoryCreator); } typeFinder = typeFinder ?? new TypeFinder(logger, new DefaultUmbracoAssemblyProvider(GetType().Assembly)); fileSystems = fileSystems ?? new FileSystems(Current.Factory, logger, TestHelper.IOHelper, SettingsForTests.GenerateMockGlobalSettings()); - var coreDebug = Current.Configs.CoreDebug(); + var coreDebug = TestHelper.CoreDebug; var mediaFileSystem = Mock.Of(); var scopeProvider = new ScopeProvider(databaseFactory, fileSystems, coreDebug, mediaFileSystem, logger, typeFinder, NoAppCache.Instance); return scopeProvider; diff --git a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs index 74b3ddf7b2..72c8d8b981 100644 --- a/src/Umbraco.Tests/Testing/UmbracoTestBase.cs +++ b/src/Umbraco.Tests/Testing/UmbracoTestBase.cs @@ -457,11 +457,16 @@ namespace Umbraco.Tests.Testing .AddCoreMappers(); Composition.RegisterUnique(_ => new TransientEventMessagesFactory()); + + var globalSettings = TestHelper.GetConfigs().Global(); + var connectionStrings = TestHelper.GetConfigs().ConnectionStrings(); + Composition.RegisterUnique(f => new UmbracoDatabaseFactory( Constants.System.UmbracoConnectionName, + globalSettings, + connectionStrings, Logger, new Lazy(f.GetInstance), - TestHelper.GetConfigs(), TestHelper.DbProviderFactoryCreator)); Composition.RegisterUnique(f => f.TryGetInstance().SqlContext); diff --git a/src/Umbraco.Web.BackOffice/AspNetCore/UmbracoBackOfficeServiceCollectionExtensions.cs b/src/Umbraco.Web.BackOffice/AspNetCore/UmbracoBackOfficeServiceCollectionExtensions.cs index 9441170ae4..c05f4af4f8 100644 --- a/src/Umbraco.Web.BackOffice/AspNetCore/UmbracoBackOfficeServiceCollectionExtensions.cs +++ b/src/Umbraco.Web.BackOffice/AspNetCore/UmbracoBackOfficeServiceCollectionExtensions.cs @@ -40,13 +40,14 @@ namespace Umbraco.Web.BackOffice.AspNetCore var hostingSettings = configFactory.HostingSettings; var coreDebug = configFactory.CoreDebug; + var globalSettings = configFactory.GlobalSettings; var hostingEnvironment = new AspNetCoreHostingEnvironment(hostingSettings, webHostEnvironment, httpContextAccessor, hostApplicationLifetime); - var ioHelper = new IOHelper(hostingEnvironment); + var ioHelper = new IOHelper(hostingEnvironment, globalSettings); var logger = SerilogLogger.CreateWithDefaultConfiguration(hostingEnvironment, new AspNetCoreSessionIdResolver(httpContextAccessor), () => services.BuildServiceProvider().GetService(), coreDebug, ioHelper, new AspNetCoreMarchal()); - var configs = configFactory.Create(ioHelper, logger); + var configs = configFactory.Create(); - var backOfficeInfo = new AspNetCoreBackOfficeInfo(configs.Global()); + var backOfficeInfo = new AspNetCoreBackOfficeInfo(globalSettings); var profiler = new LogProfiler(logger); Current.Initialize(logger, configs, ioHelper, hostingEnvironment, backOfficeInfo, profiler); diff --git a/src/Umbraco.Web.UI/Umbraco/Views/AuthorizeUpgrade.cshtml b/src/Umbraco.Web.UI/Umbraco/Views/AuthorizeUpgrade.cshtml index 986fa2dc76..14ef376a2c 100644 --- a/src/Umbraco.Web.UI/Umbraco/Views/AuthorizeUpgrade.cshtml +++ b/src/Umbraco.Web.UI/Umbraco/Views/AuthorizeUpgrade.cshtml @@ -17,7 +17,7 @@ - + diff --git a/src/Umbraco.Web.UI/Umbraco/Views/Default.cshtml b/src/Umbraco.Web.UI/Umbraco/Views/Default.cshtml index c48bdf4c47..ce8a0e2b9f 100644 --- a/src/Umbraco.Web.UI/Umbraco/Views/Default.cshtml +++ b/src/Umbraco.Web.UI/Umbraco/Views/Default.cshtml @@ -28,7 +28,7 @@ - + diff --git a/src/Umbraco.Web/AppBuilderExtensions.cs b/src/Umbraco.Web/AppBuilderExtensions.cs index 870cba86f3..e9833e4379 100644 --- a/src/Umbraco.Web/AppBuilderExtensions.cs +++ b/src/Umbraco.Web/AppBuilderExtensions.cs @@ -43,11 +43,10 @@ namespace Umbraco.Web /// Configures SignalR. /// /// The app builder. - /// /// - public static IAppBuilder UseSignalR(this IAppBuilder app, IGlobalSettings globalSettings, IIOHelper ioHelper) + public static IAppBuilder UseSignalR(this IAppBuilder app, IIOHelper ioHelper) { - var umbracoPath = globalSettings.GetUmbracoMvcArea(ioHelper); + var umbracoPath = ioHelper.GetUmbracoMvcArea(); var signalrPath = HttpRuntime.AppDomainAppVirtualPath + umbracoPath + "/BackOffice/signalr"; return app.MapSignalR(signalrPath, new HubConfiguration { EnableDetailedErrors = true }); } diff --git a/src/Umbraco.Web/Editors/AuthenticationController.cs b/src/Umbraco.Web/Editors/AuthenticationController.cs index 1788484981..6519cf4cf6 100644 --- a/src/Umbraco.Web/Editors/AuthenticationController.cs +++ b/src/Umbraco.Web/Editors/AuthenticationController.cs @@ -534,7 +534,7 @@ namespace Umbraco.Web.Editors var action = urlHelper.Action("ValidatePasswordResetCode", "BackOffice", new { - area = GlobalSettings.GetUmbracoMvcArea(_ioHelper), + area = _ioHelper.GetUmbracoMvcArea(), u = userId, r = code }); diff --git a/src/Umbraco.Web/Editors/BackOfficeController.cs b/src/Umbraco.Web/Editors/BackOfficeController.cs index 22da5b9fdd..e39d1658a2 100644 --- a/src/Umbraco.Web/Editors/BackOfficeController.cs +++ b/src/Umbraco.Web/Editors/BackOfficeController.cs @@ -104,8 +104,8 @@ namespace Umbraco.Web.Editors public async Task Default() { return await RenderDefaultOrProcessExternalLoginAsync( - () => View(GlobalSettings.Path.EnsureEndsWith('/') + "Views/Default.cshtml", new BackOfficeModel(_features, GlobalSettings, _umbracoVersion, _contentSettings,_ioHelper, _treeCollection, _httpContextAccessor, _hostingEnvironment, _runtimeSettings, _securitySettings)), - () => View(GlobalSettings.Path.EnsureEndsWith('/') + "Views/Default.cshtml", new BackOfficeModel(_features, GlobalSettings, _umbracoVersion, _contentSettings, _ioHelper, _treeCollection, _httpContextAccessor, _hostingEnvironment, _runtimeSettings, _securitySettings))); + () => View(_ioHelper.BackOfficePath.EnsureEndsWith('/') + "Views/Default.cshtml", new BackOfficeModel(_features, GlobalSettings, _umbracoVersion, _contentSettings,_ioHelper, _treeCollection, _httpContextAccessor, _hostingEnvironment, _runtimeSettings, _securitySettings)), + () => View(_ioHelper.BackOfficePath.EnsureEndsWith('/') + "Views/Default.cshtml", new BackOfficeModel(_features, GlobalSettings, _umbracoVersion, _contentSettings, _ioHelper, _treeCollection, _httpContextAccessor, _hostingEnvironment, _runtimeSettings, _securitySettings))); } [HttpGet] @@ -188,7 +188,7 @@ namespace Umbraco.Web.Editors { return await RenderDefaultOrProcessExternalLoginAsync( //The default view to render when there is no external login info or errors - () => View(GlobalSettings.Path.EnsureEndsWith('/') + "Views/AuthorizeUpgrade.cshtml", new BackOfficeModel(_features, GlobalSettings, _umbracoVersion, _contentSettings, _ioHelper, _treeCollection, _httpContextAccessor, _hostingEnvironment, _runtimeSettings, _securitySettings)), + () => View(_ioHelper.BackOfficePath.EnsureEndsWith('/') + "Views/AuthorizeUpgrade.cshtml", new BackOfficeModel(_features, GlobalSettings, _umbracoVersion, _contentSettings, _ioHelper, _treeCollection, _httpContextAccessor, _hostingEnvironment, _runtimeSettings, _securitySettings)), //The ActionResult to perform if external login is successful () => Redirect("/")); } @@ -389,7 +389,7 @@ namespace Umbraco.Web.Editors if (defaultResponse == null) throw new ArgumentNullException("defaultResponse"); if (externalSignInResponse == null) throw new ArgumentNullException("externalSignInResponse"); - ViewData.SetUmbracoPath(GlobalSettings.GetUmbracoMvcArea(_ioHelper)); + ViewData.SetUmbracoPath(_ioHelper.GetUmbracoMvcArea()); //check if there is the TempData with the any token name specified, if so, assign to view bag and render the view if (ViewData.FromTempData(TempData, ViewDataExtensions.TokenExternalSignInError) || diff --git a/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs b/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs index ebefb99677..14f067a0fc 100644 --- a/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs +++ b/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs @@ -344,7 +344,7 @@ namespace Umbraco.Web.Editors { "umbracoSettings", new Dictionary { - {"umbracoPath", _globalSettings.Path}, + {"umbracoPath", _ioHelper.BackOfficePath}, {"mediaPath", _ioHelper.ResolveUrl(globalSettings.UmbracoMediaPath).TrimEnd('/')}, {"appPluginsPath", _ioHelper.ResolveUrl(Constants.SystemDirectories.AppPlugins).TrimEnd('/')}, { diff --git a/src/Umbraco.Web/Editors/PreviewController.cs b/src/Umbraco.Web/Editors/PreviewController.cs index 3db5d4faab..3539047112 100644 --- a/src/Umbraco.Web/Editors/PreviewController.cs +++ b/src/Umbraco.Web/Editors/PreviewController.cs @@ -88,7 +88,7 @@ namespace Umbraco.Web.Editors } } - return View(_globalSettings.Path.EnsureEndsWith('/') + "Views/Preview/" + "Index.cshtml", model); + return View(_ioHelper.BackOfficePath.EnsureEndsWith('/') + "Views/Preview/" + "Index.cshtml", model); } /// diff --git a/src/Umbraco.Web/Editors/UsersController.cs b/src/Umbraco.Web/Editors/UsersController.cs index f75a040e0e..9554906b0d 100644 --- a/src/Umbraco.Web/Editors/UsersController.cs +++ b/src/Umbraco.Web/Editors/UsersController.cs @@ -487,7 +487,7 @@ namespace Umbraco.Web.Editors var action = urlHelper.Action("VerifyInvite", "BackOffice", new { - area = GlobalSettings.GetUmbracoMvcArea(_ioHelper), + area = _ioHelper.GetUmbracoMvcArea(), invite = inviteToken }); diff --git a/src/Umbraco.Web/Install/Controllers/InstallController.cs b/src/Umbraco.Web/Install/Controllers/InstallController.cs index 8caf5e985e..8869e02129 100644 --- a/src/Umbraco.Web/Install/Controllers/InstallController.cs +++ b/src/Umbraco.Web/Install/Controllers/InstallController.cs @@ -74,7 +74,7 @@ namespace Umbraco.Web.Install.Controllers _installHelper.InstallStatus(false, ""); // always ensure full path (see NOTE in the class remarks) - return View(_globalSettings.Path.EnsureEndsWith('/') + "install/views/index.cshtml"); + return View(_ioHelper.BackOfficePath.EnsureEndsWith('/') + "install/views/index.cshtml"); } } } diff --git a/src/Umbraco.Web/Mvc/AreaRegistrationExtensions.cs b/src/Umbraco.Web/Mvc/AreaRegistrationExtensions.cs index 7a3a3fbcf4..22e5911cf8 100644 --- a/src/Umbraco.Web/Mvc/AreaRegistrationExtensions.cs +++ b/src/Umbraco.Web/Mvc/AreaRegistrationExtensions.cs @@ -19,7 +19,7 @@ namespace Umbraco.Web.Mvc /// Creates a custom individual route for the specified controller plugin. Individual routes /// are required by controller plugins to map to a unique URL based on ID. /// - /// + /// /// /// /// An existing route collection @@ -42,7 +42,6 @@ namespace Umbraco.Web.Mvc /// /// internal static Route RouteControllerPlugin(this AreaRegistration area, - IGlobalSettings globalSettings, IIOHelper ioHelper, string controllerName, Type controllerType, RouteCollection routes, string controllerSuffixName, string defaultAction, object defaultId, @@ -59,7 +58,7 @@ namespace Umbraco.Web.Mvc if (routes == null) throw new ArgumentNullException(nameof(routes)); if (defaultId == null) throw new ArgumentNullException(nameof(defaultId)); - var umbracoArea = globalSettings.GetUmbracoMvcArea(ioHelper); + var umbracoArea = ioHelper.GetUmbracoMvcArea(); //routes are explicitly named with controller names and IDs var url = umbracoArea + "/" + diff --git a/src/Umbraco.Web/Mvc/BackOfficeArea.cs b/src/Umbraco.Web/Mvc/BackOfficeArea.cs index b4425a3239..82c0bbf909 100644 --- a/src/Umbraco.Web/Mvc/BackOfficeArea.cs +++ b/src/Umbraco.Web/Mvc/BackOfficeArea.cs @@ -11,12 +11,10 @@ namespace Umbraco.Web.Mvc /// internal class BackOfficeArea : AreaRegistration { - private readonly IGlobalSettings _globalSettings; private readonly IIOHelper _ioHelper; - public BackOfficeArea(IGlobalSettings globalSettings, IIOHelper ioHelper) + public BackOfficeArea(IIOHelper ioHelper) { - _globalSettings = globalSettings; _ioHelper = ioHelper; } @@ -51,6 +49,6 @@ namespace Umbraco.Web.Mvc new[] {typeof (BackOfficeController).Namespace}); } - public override string AreaName => _globalSettings.GetUmbracoMvcArea(_ioHelper); + public override string AreaName => _ioHelper.GetUmbracoMvcArea(); } } diff --git a/src/Umbraco.Web/Mvc/PluginControllerArea.cs b/src/Umbraco.Web/Mvc/PluginControllerArea.cs index 713b0c6551..fddf04b391 100644 --- a/src/Umbraco.Web/Mvc/PluginControllerArea.cs +++ b/src/Umbraco.Web/Mvc/PluginControllerArea.cs @@ -77,7 +77,7 @@ namespace Umbraco.Web.Mvc { foreach (var s in surfaceControllers) { - var route = this.RouteControllerPlugin(_globalSettings, _ioHelper, s.ControllerName, s.ControllerType, routes, "", "Index", UrlParameter.Optional, "surface"); + var route = this.RouteControllerPlugin(_ioHelper, s.ControllerName, s.ControllerType, routes, "", "Index", UrlParameter.Optional, "surface"); //set the route handler to our SurfaceRouteHandler route.RouteHandler = new SurfaceRouteHandler(); } @@ -92,7 +92,7 @@ namespace Umbraco.Web.Mvc { foreach (var s in apiControllers) { - this.RouteControllerPlugin(_globalSettings, _ioHelper, s.ControllerName, s.ControllerType, routes, "", "", UrlParameter.Optional, "api", + this.RouteControllerPlugin(_ioHelper, s.ControllerName, s.ControllerType, routes, "", "", UrlParameter.Optional, "api", isMvc: false, areaPathPrefix: s.IsBackOffice ? "backoffice" : null); } diff --git a/src/Umbraco.Web/Mvc/UmbracoAuthorizeAttribute.cs b/src/Umbraco.Web/Mvc/UmbracoAuthorizeAttribute.cs index 0c6898553c..593289812f 100644 --- a/src/Umbraco.Web/Mvc/UmbracoAuthorizeAttribute.cs +++ b/src/Umbraco.Web/Mvc/UmbracoAuthorizeAttribute.cs @@ -57,7 +57,7 @@ namespace Umbraco.Web.Mvc { if (redirectToUmbracoLogin) { - _redirectUrl = Current.Configs.Global().Path.EnsureStartsWith("~"); + _redirectUrl = Current.IOHelper.BackOfficePath.EnsureStartsWith("~"); } } diff --git a/src/Umbraco.Web/Runtime/WebInitialComponent.cs b/src/Umbraco.Web/Runtime/WebInitialComponent.cs index 8f07ab4837..0a668b7d65 100644 --- a/src/Umbraco.Web/Runtime/WebInitialComponent.cs +++ b/src/Umbraco.Web/Runtime/WebInitialComponent.cs @@ -172,7 +172,7 @@ namespace Umbraco.Web.Runtime UmbracoApiControllerTypeCollection apiControllerTypes, IIOHelper ioHelper) { - var umbracoPath = globalSettings.GetUmbracoMvcArea(ioHelper); + var umbracoPath = ioHelper.GetUmbracoMvcArea(); // create the front-end route var defaultRoute = RouteTable.Routes.MapRoute( @@ -189,7 +189,7 @@ namespace Umbraco.Web.Runtime RouteTable.Routes.RegisterArea(); // register all back office routes - RouteTable.Routes.RegisterArea(new BackOfficeArea(globalSettings, ioHelper)); + RouteTable.Routes.RegisterArea(new BackOfficeArea(ioHelper)); // plugin controllers must come first because the next route will catch many things RoutePluginControllers(globalSettings, surfaceControllerTypes, apiControllerTypes, ioHelper); @@ -209,7 +209,7 @@ namespace Umbraco.Web.Runtime UmbracoApiControllerTypeCollection apiControllerTypes, IIOHelper ioHelper) { - var umbracoPath = globalSettings.GetUmbracoMvcArea(ioHelper); + var umbracoPath = ioHelper.GetUmbracoMvcArea(); // need to find the plugin controllers and route them var pluginControllers = surfaceControllerTypes.Concat(apiControllerTypes).ToArray(); diff --git a/src/Umbraco.Web/Security/AppBuilderExtensions.cs b/src/Umbraco.Web/Security/AppBuilderExtensions.cs index 17a5efd1e6..8fab9f4ea8 100644 --- a/src/Umbraco.Web/Security/AppBuilderExtensions.cs +++ b/src/Umbraco.Web/Security/AppBuilderExtensions.cs @@ -235,7 +235,7 @@ namespace Umbraco.Web.Security var cookieAuthOptions = app.CreateUmbracoCookieAuthOptions( umbracoContextAccessor, globalSettings, runtimeState, securitySettings, //This defines the explicit path read cookies from for this middleware - ioHelper, requestCache, new[] {$"{globalSettings.Path}/backoffice/UmbracoApi/Authentication/GetRemainingTimeoutSeconds"}); + ioHelper, requestCache, new[] {$"{ioHelper.BackOfficePath}/backoffice/UmbracoApi/Authentication/GetRemainingTimeoutSeconds"}); cookieAuthOptions.Provider = cookieOptions.Provider; //This is a custom middleware, we need to return the user's remaining logged in seconds @@ -243,7 +243,8 @@ namespace Umbraco.Web.Security cookieAuthOptions, Current.Configs.Global(), Current.Configs.Security(), - app.CreateLogger()); + app.CreateLogger(), + Current.IOHelper); //This is required so that we can read the auth ticket format outside of this pipeline app.CreatePerOwinContext( @@ -344,7 +345,7 @@ namespace Umbraco.Web.Security CookieName = Constants.Security.BackOfficeExternalCookieName, ExpireTimeSpan = TimeSpan.FromMinutes(5), //Custom cookie manager so we can filter requests - CookieManager = new BackOfficeCookieManager(umbracoContextAccessor, runtimeState, globalSettings, ioHelper, requestCache), + CookieManager = new BackOfficeCookieManager(umbracoContextAccessor, runtimeState, ioHelper, requestCache), CookiePath = "/", CookieSecure = globalSettings.UseHttps ? CookieSecureOption.Always : CookieSecureOption.SameAsRequest, CookieHttpOnly = true, @@ -396,7 +397,7 @@ namespace Umbraco.Web.Security if (runtimeState.Level != RuntimeLevel.Run) return app; var authOptions = app.CreateUmbracoCookieAuthOptions(umbracoContextAccessor, globalSettings, runtimeState, securitySettings, ioHelper, requestCache); - app.Use(typeof(PreviewAuthenticationMiddleware), authOptions, Current.Configs.Global(), ioHelper); + app.Use(typeof(PreviewAuthenticationMiddleware), authOptions, ioHelper); // This middleware must execute at least on PostAuthentication, by default it is on Authorize // The middleware needs to execute after the RoleManagerModule executes which is during PostAuthenticate, diff --git a/src/Umbraco.Web/Security/BackOfficeCookieManager.cs b/src/Umbraco.Web/Security/BackOfficeCookieManager.cs index b7b39ea4bf..17c5f1befb 100644 --- a/src/Umbraco.Web/Security/BackOfficeCookieManager.cs +++ b/src/Umbraco.Web/Security/BackOfficeCookieManager.cs @@ -23,25 +23,23 @@ namespace Umbraco.Web.Security { private readonly IUmbracoContextAccessor _umbracoContextAccessor; private readonly IRuntimeState _runtime; - private readonly IGlobalSettings _globalSettings; private readonly IIOHelper _ioHelper; private readonly IRequestCache _requestCache; private readonly string[] _explicitPaths; private readonly string _getRemainingSecondsPath; - public BackOfficeCookieManager(IUmbracoContextAccessor umbracoContextAccessor, IRuntimeState runtime, IGlobalSettings globalSettings, IIOHelper ioHelper, IRequestCache requestCache) - : this(umbracoContextAccessor, runtime, globalSettings, ioHelper,requestCache, null) + public BackOfficeCookieManager(IUmbracoContextAccessor umbracoContextAccessor, IRuntimeState runtime, IIOHelper ioHelper, IRequestCache requestCache) + : this(umbracoContextAccessor, runtime, ioHelper,requestCache, null) { } - public BackOfficeCookieManager(IUmbracoContextAccessor umbracoContextAccessor, IRuntimeState runtime, IGlobalSettings globalSettings, IIOHelper ioHelper, IRequestCache requestCache, IEnumerable explicitPaths) + public BackOfficeCookieManager(IUmbracoContextAccessor umbracoContextAccessor, IRuntimeState runtime, IIOHelper ioHelper, IRequestCache requestCache, IEnumerable explicitPaths) { _umbracoContextAccessor = umbracoContextAccessor; _runtime = runtime; - _globalSettings = globalSettings; _ioHelper = ioHelper; _requestCache = requestCache; _explicitPaths = explicitPaths?.ToArray(); - _getRemainingSecondsPath = $"{globalSettings.Path}/backoffice/UmbracoApi/Authentication/GetRemainingTimeoutSeconds"; + _getRemainingSecondsPath = $"{ioHelper.BackOfficePath}/backoffice/UmbracoApi/Authentication/GetRemainingTimeoutSeconds"; } /// @@ -105,7 +103,7 @@ namespace Umbraco.Web.Security (checkForceAuthTokens && owinContext.Get(Constants.Security.ForceReAuthFlag) != null) || (checkForceAuthTokens && _requestCache.IsAvailable && _requestCache.Get(Constants.Security.ForceReAuthFlag) != null) //check back office - || request.Uri.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath, _globalSettings, _ioHelper) + || request.Uri.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath, _ioHelper) //check installer || request.Uri.IsInstallerRequest(_ioHelper)) { diff --git a/src/Umbraco.Web/Security/GetUserSecondsMiddleWare.cs b/src/Umbraco.Web/Security/GetUserSecondsMiddleWare.cs index 7c1c4c558c..448ec88915 100644 --- a/src/Umbraco.Web/Security/GetUserSecondsMiddleWare.cs +++ b/src/Umbraco.Web/Security/GetUserSecondsMiddleWare.cs @@ -8,6 +8,7 @@ using Microsoft.Owin.Logging; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.UmbracoSettings; +using Umbraco.Core.IO; using Umbraco.Core.Security; namespace Umbraco.Web.Security @@ -26,19 +27,22 @@ namespace Umbraco.Web.Security private readonly IGlobalSettings _globalSettings; private readonly ISecuritySettings _security; private readonly ILogger _logger; + private readonly IIOHelper _ioHelper; public GetUserSecondsMiddleWare( OwinMiddleware next, UmbracoBackOfficeCookieAuthOptions authOptions, IGlobalSettings globalSettings, ISecuritySettings security, - ILogger logger) + ILogger logger, + IIOHelper ioHelper) : base(next) { _authOptions = authOptions ?? throw new ArgumentNullException(nameof(authOptions)); _globalSettings = globalSettings; _security = security; _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _ioHelper = ioHelper; } public override async Task Invoke(IOwinContext context) @@ -48,7 +52,7 @@ namespace Umbraco.Web.Security if (request.Uri.Scheme.InvariantStartsWith("http") && request.Uri.AbsolutePath.InvariantEquals( - $"{_globalSettings.Path}/backoffice/UmbracoApi/Authentication/GetRemainingTimeoutSeconds")) + $"{_ioHelper.BackOfficePath}/backoffice/UmbracoApi/Authentication/GetRemainingTimeoutSeconds")) { var cookie = _authOptions.CookieManager.GetRequestCookie(context, _security.AuthCookieName); if (cookie.IsNullOrWhiteSpace() == false) diff --git a/src/Umbraco.Web/Security/PreviewAuthenticationMiddleware.cs b/src/Umbraco.Web/Security/PreviewAuthenticationMiddleware.cs index 18deeafcbf..c73cd061c9 100644 --- a/src/Umbraco.Web/Security/PreviewAuthenticationMiddleware.cs +++ b/src/Umbraco.Web/Security/PreviewAuthenticationMiddleware.cs @@ -12,7 +12,6 @@ namespace Umbraco.Web.Security internal class PreviewAuthenticationMiddleware : OwinMiddleware { private readonly UmbracoBackOfficeCookieAuthOptions _cookieOptions; - private readonly IGlobalSettings _globalSettings; private readonly IIOHelper _ioHelper; /// @@ -22,10 +21,9 @@ namespace Umbraco.Web.Security /// /// public PreviewAuthenticationMiddleware(OwinMiddleware next, - UmbracoBackOfficeCookieAuthOptions cookieOptions, IGlobalSettings globalSettings, IIOHelper ioHelper) : base(next) + UmbracoBackOfficeCookieAuthOptions cookieOptions, IIOHelper ioHelper) : base(next) { _cookieOptions = cookieOptions; - _globalSettings = globalSettings; _ioHelper = ioHelper; } @@ -43,7 +41,7 @@ namespace Umbraco.Web.Security var isPreview = request.HasPreviewCookie() && claimsPrincipal != null && request.Uri != null - && request.Uri.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath, _globalSettings, _ioHelper) == false; + && request.Uri.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath, _ioHelper) == false; if (isPreview) { //If we've gotten this far it means a preview cookie has been set and a front-end umbraco document request is executing. diff --git a/src/Umbraco.Web/Security/SessionIdValidator.cs b/src/Umbraco.Web/Security/SessionIdValidator.cs index 11fb28c197..2339bff7f6 100644 --- a/src/Umbraco.Web/Security/SessionIdValidator.cs +++ b/src/Umbraco.Web/Security/SessionIdValidator.cs @@ -31,7 +31,7 @@ namespace Umbraco.Web.Security public static async Task ValidateSessionAsync(TimeSpan validateInterval, CookieValidateIdentityContext context, IGlobalSettings globalSettings, IIOHelper ioHelper) { - if (context.Request.Uri.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath, globalSettings, ioHelper) == false) + if (context.Request.Uri.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath, ioHelper) == false) return; var valid = await ValidateSessionAsync(validateInterval, context.OwinContext, context.Options.CookieManager, context.Options.SystemClock, context.Properties.IssuedUtc, context.Identity, globalSettings); diff --git a/src/Umbraco.Web/Security/UmbracoBackOfficeCookieAuthOptions.cs b/src/Umbraco.Web/Security/UmbracoBackOfficeCookieAuthOptions.cs index 836c0bb53a..5e8bdffbed 100644 --- a/src/Umbraco.Web/Security/UmbracoBackOfficeCookieAuthOptions.cs +++ b/src/Umbraco.Web/Security/UmbracoBackOfficeCookieAuthOptions.cs @@ -42,7 +42,7 @@ namespace Umbraco.Web.Security TicketDataFormat = new UmbracoSecureDataFormat(LoginTimeoutMinutes, secureDataFormat1); //Custom cookie manager so we can filter requests - CookieManager = new BackOfficeCookieManager(umbracoContextAccessor, runtimeState, globalSettings, ioHelper, requestCache, explicitPaths); + CookieManager = new BackOfficeCookieManager(umbracoContextAccessor, runtimeState, ioHelper, requestCache, explicitPaths); } /// diff --git a/src/Umbraco.Web/UmbracoApplication.cs b/src/Umbraco.Web/UmbracoApplication.cs index 97f06d3c0f..891d80bb81 100644 --- a/src/Umbraco.Web/UmbracoApplication.cs +++ b/src/Umbraco.Web/UmbracoApplication.cs @@ -22,10 +22,13 @@ namespace Umbraco.Web var dbProviderFactoryCreator = new UmbracoDbProviderFactoryCreator(connectionStringConfig?.ProviderName); + var globalSettings = configs.Global(); + var connectionStrings = configs.ConnectionStrings(); + // Determine if we should use the sql main dom or the default - var appSettingMainDomLock = configs.Global().MainDomLock; + var appSettingMainDomLock = globalSettings.MainDomLock; var mainDomLock = appSettingMainDomLock == "SqlMainDomLock" - ? (IMainDomLock)new SqlMainDomLock(logger, configs, dbProviderFactoryCreator) + ? (IMainDomLock)new SqlMainDomLock(logger, globalSettings, connectionStrings, dbProviderFactoryCreator) : new MainDomSemaphoreLock(logger, hostingEnvironment); var mainDom = new MainDom(logger, hostingEnvironment, mainDomLock); diff --git a/src/Umbraco.Web/UmbracoApplicationBase.cs b/src/Umbraco.Web/UmbracoApplicationBase.cs index a4979777da..889cae5002 100644 --- a/src/Umbraco.Web/UmbracoApplicationBase.cs +++ b/src/Umbraco.Web/UmbracoApplicationBase.cs @@ -35,13 +35,14 @@ namespace Umbraco.Web var hostingSettings = configFactory.HostingSettings; var coreDebug = configFactory.CoreDebug; + var globalSettings = configFactory.GlobalSettings; var hostingEnvironment = new AspNetHostingEnvironment(hostingSettings); - var ioHelper = new IOHelper(hostingEnvironment); + var ioHelper = new IOHelper(hostingEnvironment, globalSettings); var logger = SerilogLogger.CreateWithDefaultConfiguration(hostingEnvironment, new AspNetSessionManager(), () => _factory?.GetInstance(), coreDebug, ioHelper, new FrameworkMarchal()); - var configs = configFactory.Create(ioHelper, logger); + var configs = configFactory.Create(); - var backOfficeInfo = new AspNetBackOfficeInfo(configs.Global(), ioHelper, logger, configFactory.WebRoutingSettings); + var backOfficeInfo = new AspNetBackOfficeInfo(globalSettings, ioHelper, logger, configFactory.WebRoutingSettings); var profiler = new LogProfiler(logger); Umbraco.Composing.Current.Initialize(logger, configs, ioHelper, hostingEnvironment, backOfficeInfo, profiler); } diff --git a/src/Umbraco.Web/UmbracoContext.cs b/src/Umbraco.Web/UmbracoContext.cs index a4f679ff5f..6f5fc26f90 100644 --- a/src/Umbraco.Web/UmbracoContext.cs +++ b/src/Umbraco.Web/UmbracoContext.cs @@ -184,7 +184,7 @@ namespace Umbraco.Web { var request = GetRequestFromContext(); if (request?.Url != null - && request.Url.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath, _globalSettings, _ioHelper) == false + && request.Url.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath, _ioHelper) == false && Security.CurrentUser != null) { var previewToken = _cookieManager.GetPreviewCookieValue(); // may be null or empty diff --git a/src/Umbraco.Web/UmbracoDefaultOwinStartup.cs b/src/Umbraco.Web/UmbracoDefaultOwinStartup.cs index 0a82c0644b..a69e6c6f8d 100644 --- a/src/Umbraco.Web/UmbracoDefaultOwinStartup.cs +++ b/src/Umbraco.Web/UmbracoDefaultOwinStartup.cs @@ -27,10 +27,10 @@ namespace Umbraco.Web public class UmbracoDefaultOwinStartup { protected IUmbracoContextAccessor UmbracoContextAccessor => Current.UmbracoContextAccessor; - protected IGlobalSettings GlobalSettings => Current.Configs.Global(); - protected IContentSettings ContentSettings => Current.Configs.Content(); - protected ISecuritySettings SecuritySettings => Current.Configs.Security(); - protected IUserPasswordConfiguration UserPasswordConfig => Current.Configs.UserPasswordConfiguration(); + protected IGlobalSettings GlobalSettings => Current.Factory.GetInstance(); + protected IContentSettings ContentSettings => Current.Factory.GetInstance(); + protected ISecuritySettings SecuritySettings => Current.Factory.GetInstance(); + protected IUserPasswordConfiguration UserPasswordConfig => Current.Factory.GetInstance(); protected IRuntimeState RuntimeState => Current.RuntimeState; protected ServiceContext Services => Current.Services; protected UmbracoMapper Mapper => Current.Mapper; @@ -76,7 +76,7 @@ namespace Umbraco.Web ConfigureUmbracoAuthentication(app); app - .UseSignalR(GlobalSettings, IOHelper) + .UseSignalR(IOHelper) .FinalizeMiddlewareConfiguration(); } diff --git a/src/Umbraco.Web/UmbracoInjectedModule.cs b/src/Umbraco.Web/UmbracoInjectedModule.cs index 3f92ca587e..73e82702a3 100644 --- a/src/Umbraco.Web/UmbracoInjectedModule.cs +++ b/src/Umbraco.Web/UmbracoInjectedModule.cs @@ -6,6 +6,7 @@ using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Configuration; using Umbraco.Core.Exceptions; +using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Web.Composing; using Umbraco.Web.Routing; @@ -30,26 +31,25 @@ namespace Umbraco.Web /// public class UmbracoInjectedModule : IHttpModule { - private readonly IGlobalSettings _globalSettings; private readonly IRuntimeState _runtime; private readonly ILogger _logger; private readonly IPublishedRouter _publishedRouter; private readonly IUmbracoContextFactory _umbracoContextFactory; private readonly RoutableDocumentFilter _routableDocumentLookup; private readonly IRequestCache _requestCache; + private readonly IIOHelper _ioHelper; private readonly UriUtility _uriUtility; public UmbracoInjectedModule( - IGlobalSettings globalSettings, IRuntimeState runtime, ILogger logger, IPublishedRouter publishedRouter, IUmbracoContextFactory umbracoContextFactory, RoutableDocumentFilter routableDocumentLookup, UriUtility uriUtility, - IRequestCache requestCache) + IRequestCache requestCache, + IIOHelper ioHelper) { - _globalSettings = globalSettings; _runtime = runtime; _logger = logger; _publishedRouter = publishedRouter; @@ -57,6 +57,7 @@ namespace Umbraco.Web _routableDocumentLookup = routableDocumentLookup; _uriUtility = uriUtility; _requestCache = requestCache; + _ioHelper = ioHelper; } #region HttpModule event handlers @@ -110,7 +111,7 @@ namespace Umbraco.Web var umbracoContext = Current.UmbracoContext; // re-write for the default back office path - if (httpContext.Request.Url.IsDefaultBackOfficeRequest(_globalSettings)) + if (httpContext.Request.Url.IsDefaultBackOfficeRequest(_ioHelper)) { if (EnsureRuntime(httpContext, umbracoContext.OriginalRequestUrl)) RewriteToBackOfficeHandler(httpContext); @@ -256,7 +257,7 @@ namespace Umbraco.Web private void RewriteToBackOfficeHandler(HttpContextBase context) { // GlobalSettings.Path has already been through IOHelper.ResolveUrl() so it begins with / and vdir (if any) - var rewritePath = _globalSettings.Path.TrimEnd('/') + "/Default"; + var rewritePath = _ioHelper.BackOfficePath.TrimEnd('/') + "/Default"; // rewrite the path to the path of the handler (i.e. /umbraco/RenderMvc) context.RewritePath(rewritePath, "", "", false); @@ -289,7 +290,7 @@ namespace Umbraco.Web var query = pcr.Uri.Query.TrimStart('?'); // GlobalSettings.Path has already been through IOHelper.ResolveUrl() so it begins with / and vdir (if any) - var rewritePath = _globalSettings.Path.TrimEnd('/') + "/RenderMvc"; + var rewritePath = _ioHelper.BackOfficePath.TrimEnd('/') + "/RenderMvc"; // rewrite the path to the path of the handler (i.e. /umbraco/RenderMvc) context.RewritePath(rewritePath, "", query, false);