From adced099beddaa7bedc3aec1b38d77fd3e6d8bde Mon Sep 17 00:00:00 2001 From: Stephan Date: Wed, 12 Dec 2018 17:49:24 +0100 Subject: [PATCH] Move UmbracoConfig singleton to Current --- .../Composers/ConfigurationComposer.cs | 14 +- .../Composing/CompositionExtensions.cs | 2 + src/Umbraco.Core/Composing/Current.cs | 19 +- .../Configuration/UmbracoConfig.cs | 200 +++++++----------- .../OriginalMediaPathScheme.cs | 5 +- .../Logging/Serilog/SerilogLogger.cs | 3 +- src/Umbraco.Core/MainDom.cs | 2 +- .../Models/Identity/BackOfficeIdentityUser.cs | 7 +- src/Umbraco.Core/Models/Membership/User.cs | 6 +- .../ValueConverters/GridValueConverter.cs | 20 +- src/Umbraco.Core/Runtime/CoreRuntime.cs | 16 +- src/Umbraco.Core/Scoping/Scope.cs | 3 +- .../Security/MembershipProviderExtensions.cs | 7 +- src/Umbraco.Core/StringExtensions.cs | 4 +- .../Configurations/GlobalSettingsTests.cs | 3 +- src/Umbraco.Tests/IO/ShadowFileSystemTests.cs | 40 ++-- src/Umbraco.Tests/Macros/MacroTests.cs | 3 +- .../PublishedContent/NuCacheTests.cs | 3 +- .../Routing/ContentFinderByUrlTests.cs | 11 +- .../Runtimes/CoreRuntimeTests.cs | 4 +- src/Umbraco.Tests/Runtimes/StandaloneTests.cs | 80 +++---- .../Scoping/ScopeFileSystemsTests.cs | 2 +- .../TestHelpers/SettingsForTests.cs | 7 +- .../Web/TemplateUtilitiesTests.cs | 2 +- src/Umbraco.Web.UI/Umbraco/umbraco.aspx.cs | 3 +- src/Umbraco.Web/Composing/Current.cs | 3 + .../Editors/AuthenticationController.cs | 2 +- .../Editors/BackOfficeController.cs | 8 +- .../Editors/BackOfficeServerVariables.cs | 14 +- src/Umbraco.Web/Editors/DataTypeController.cs | 2 +- src/Umbraco.Web/Editors/MediaController.cs | 17 +- .../RedirectUrlManagementController.cs | 3 +- src/Umbraco.Web/Editors/TourController.cs | 3 +- .../Editors/UpdateCheckController.cs | 5 +- src/Umbraco.Web/Editors/UsersController.cs | 16 +- .../HealthCheck/HealthCheckController.cs | 3 +- .../EmailNotificationMethod.cs | 3 +- .../NotificationMethodBase.cs | 3 +- src/Umbraco.Web/HtmlHelperRenderExtensions.cs | 2 +- .../Install/InstallSteps/NewInstallStep.cs | 5 +- src/Umbraco.Web/Macros/MacroRenderer.cs | 6 +- .../Models/ContentEditing/ContentTypeBasic.cs | 3 +- .../Models/ContentEditing/UserInvite.cs | 3 +- .../Models/Mapping/DataTypeMapperProfile.cs | 2 +- .../Models/Mapping/MediaMapperProfile.cs | 3 +- src/Umbraco.Web/Models/Trees/TreeNode.cs | 3 +- .../Mvc/UmbracoAuthorizeAttribute.cs | 4 +- .../Mvc/UmbracoRequireHttpsAttribute.cs | 5 +- .../Mvc/UmbracoViewPageOfTModel.cs | 2 +- .../UploadFileTypeValidator.cs | 2 +- .../XmlPublishedCache/XmlStore.cs | 14 +- src/Umbraco.Web/PublishedContentExtensions.cs | 4 +- src/Umbraco.Web/Routing/PublishedRequest.cs | 3 +- .../Runtime/WebRuntimeComponent.cs | 2 +- .../Scheduling/HealthCheckNotifier.cs | 3 +- .../Scheduling/SchedulerComponent.cs | 5 +- .../Security/AppBuilderExtensions.cs | 10 +- .../Security/AuthenticationExtensions.cs | 12 +- .../BackOfficeCookieAuthenticationProvider.cs | 8 +- .../Security/ExternalSignInAutoLinkOptions.cs | 3 +- .../Providers/UsersMembershipProvider.cs | 2 +- src/Umbraco.Web/Templates/TemplateRenderer.cs | 2 +- .../Templates/TemplateUtilities.cs | 2 +- .../Trees/ContentTypeTreeController.cs | 3 +- .../Trees/LegacyTreeDataConverter.cs | 2 +- .../Trees/MediaTypeTreeController.cs | 3 +- src/Umbraco.Web/UI/Pages/BasePage.cs | 2 +- .../UI/Pages/UmbracoEnsuredPage.cs | 2 +- src/Umbraco.Web/UmbracoContext.cs | 6 +- src/Umbraco.Web/UmbracoDefaultOwinStartup.cs | 6 +- src/Umbraco.Web/UmbracoInjectedModule.cs | 4 +- src/Umbraco.Web/UmbracoModule.cs | 2 +- src/Umbraco.Web/UmbracoWebService.cs | 2 +- .../CheckIfUserTicketDataIsStaleAttribute.cs | 6 +- .../SetAngularAntiForgeryTokensAttribute.cs | 5 +- .../UmbracoWebApiRequireHttpsAttribute.cs | 3 +- .../umbraco.presentation/default.aspx.cs | 2 +- 77 files changed, 341 insertions(+), 365 deletions(-) diff --git a/src/Umbraco.Core/Composing/Composers/ConfigurationComposer.cs b/src/Umbraco.Core/Composing/Composers/ConfigurationComposer.cs index 7032bbe88e..ee044e533d 100644 --- a/src/Umbraco.Core/Composing/Composers/ConfigurationComposer.cs +++ b/src/Umbraco.Core/Composing/Composers/ConfigurationComposer.cs @@ -11,12 +11,14 @@ namespace Umbraco.Core.Composing.Composers { public static Composition ComposeConfiguration(this Composition composition) { - composition.Register(factory => UmbracoConfig.For.UmbracoSettings()); - composition.Register(factory => factory.GetInstance().Content); - composition.Register(factory => factory.GetInstance().Templates); - composition.Register(factory => factory.GetInstance().RequestHandler); - composition.Register(factory => UmbracoConfig.For.GlobalSettings()); - composition.Register(factory => UmbracoConfig.For.DashboardSettings()); + composition.RegisterUnique(factory => factory.GetInstance().Umbraco()); + composition.RegisterUnique(factory => factory.GetInstance().Content); + composition.RegisterUnique(factory => factory.GetInstance().Templates); + composition.RegisterUnique(factory => factory.GetInstance().RequestHandler); + composition.RegisterUnique(factory => factory.GetInstance().Global()); + composition.RegisterUnique(factory => factory.GetInstance().Dashboards()); + composition.RegisterUnique(factory => factory.GetInstance().HealthChecks()); + composition.RegisterUnique(factory => factory.GetInstance().Grids()); // fixme - other sections we need to add? diff --git a/src/Umbraco.Core/Composing/CompositionExtensions.cs b/src/Umbraco.Core/Composing/CompositionExtensions.cs index 9c0b84cf95..cfc465b59d 100644 --- a/src/Umbraco.Core/Composing/CompositionExtensions.cs +++ b/src/Umbraco.Core/Composing/CompositionExtensions.cs @@ -17,6 +17,7 @@ namespace Umbraco.Core.Composing /// public static void RegisterEssentials(this Composition composition, ILogger logger, IProfiler profiler, IProfilingLogger profilingLogger, + IMainDom mainDom, CacheHelper appCaches, IUmbracoDatabaseFactory databaseFactory, TypeLoader typeLoader, @@ -25,6 +26,7 @@ namespace Umbraco.Core.Composing composition.RegisterUnique(logger); composition.RegisterUnique(profiler); composition.RegisterUnique(profilingLogger); + composition.RegisterUnique(mainDom); composition.RegisterUnique(appCaches); composition.RegisterUnique(factory => factory.GetInstance().RuntimeCache); composition.RegisterUnique(databaseFactory); diff --git a/src/Umbraco.Core/Composing/Current.cs b/src/Umbraco.Core/Composing/Current.cs index 312d9251a3..c383b903b2 100644 --- a/src/Umbraco.Core/Composing/Current.cs +++ b/src/Umbraco.Core/Composing/Current.cs @@ -28,11 +28,18 @@ namespace Umbraco.Core.Composing { private static IFactory _factory; + // fixme - refactor + // we don't want Umbraco tests to die because the container has not been properly initialized, + // for some too-important things such as IShortStringHelper or loggers, so if it's not + // registered we setup a default one. We should really refactor our tests so that it does + // not happen. + private static IShortStringHelper _shortStringHelper; private static ILogger _logger; private static IProfiler _profiler; private static IProfilingLogger _profilingLogger; private static IPublishedValueFallback _publishedValueFallback; + private static UmbracoConfig _config; /// /// Gets or sets the factory. @@ -73,15 +80,9 @@ namespace Umbraco.Core.Composing #region Getters - // fixme - refactor - // we don't want Umbraco to die because the container has not been properly initialized, - // for some too-important things such as IShortStringHelper or loggers, so if it's not - // registered we setup a default one. We should really refactor our tests so that it does - // not happen. Will do when we get rid of IShortStringHelper. - public static IShortStringHelper ShortStringHelper => _shortStringHelper ?? (_shortStringHelper = _factory?.TryGetInstance() - ?? new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(UmbracoConfig.For.UmbracoSettings()))); + ?? new DefaultShortStringHelper(new DefaultShortStringHelperConfig().WithDefault(Config.Umbraco()))); public static ILogger Logger => _logger ?? (_logger = _factory?.TryGetInstance() @@ -101,6 +102,10 @@ namespace Umbraco.Core.Composing public static TypeLoader TypeLoader => Factory.GetInstance(); + public static UmbracoConfig Config + => _config ?? (_config = _factory?.TryGetInstance()) + ?? (_config = new UmbracoConfig(Logger, _factory?.TryGetInstance(), _factory?.TryGetInstance())); + public static IFileSystems FileSystems => Factory.GetInstance(); diff --git a/src/Umbraco.Core/Configuration/UmbracoConfig.cs b/src/Umbraco.Core/Configuration/UmbracoConfig.cs index 6a1203313e..0ace23dba4 100644 --- a/src/Umbraco.Core/Configuration/UmbracoConfig.cs +++ b/src/Umbraco.Core/Configuration/UmbracoConfig.cs @@ -7,190 +7,132 @@ using Umbraco.Core.Configuration.Grid; using Umbraco.Core.Configuration.HealthChecks; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.Composing; +using Umbraco.Core.IO; using Umbraco.Core.Logging; namespace Umbraco.Core.Configuration { /// - /// The gateway to all umbraco configuration + /// The gateway to all umbraco configuration. /// + /// This should be registered as a unique service in the container. public class UmbracoConfig { - #region Singleton - - private static readonly Lazy Lazy = new Lazy(() => new UmbracoConfig()); - - public static UmbracoConfig For => Lazy.Value; - - #endregion + private IGlobalSettings _global; + private Lazy _umbraco; + private Lazy _healthChecks; + private Lazy _dashboards; + private Lazy _grids; /// - /// Default constructor + /// Initializes a new instance of the class. /// - private UmbracoConfig() + public UmbracoConfig(ILogger logger, IRuntimeCacheProvider runtimeCache, IRuntimeState runtimeState) + { + _global = new GlobalSettings(); + + var appPluginsDir = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.AppPlugins)); + var configDir = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.Config)); + + _umbraco = new Lazy(() => GetConfig("umbracoConfiguration/settings")); + _dashboards = new Lazy(() =>GetConfig("umbracoConfiguration/dashBoard")); + _healthChecks = new Lazy(() => GetConfig("umbracoConfiguration/HealthChecks")); + _grids = new Lazy(() => new GridConfig(logger, runtimeCache, appPluginsDir, configDir, runtimeState.Debug)); + } + + /// + /// Gets a typed and named config section. + /// + /// The type of the configuration section. + /// The name of the configuration section. + /// The configuration section. + public static 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! - if (_umbracoSettings == null) + using (new SafeCallContext()) { - IUmbracoSettingsSection umbracoSettings; - using (new SafeCallContext()) - { - umbracoSettings = ConfigurationManager.GetSection("umbracoConfiguration/settings") as IUmbracoSettingsSection; - } - SetUmbracoSettings(umbracoSettings); - } - - if (_dashboardSection == null) - { - IDashboardSection dashboardConfig; - using (new SafeCallContext()) - { - dashboardConfig = ConfigurationManager.GetSection("umbracoConfiguration/dashBoard") as IDashboardSection; - } - SetDashboardSettings(dashboardConfig); - } - - if (_healthChecks == null) - { - var healthCheckConfig = ConfigurationManager.GetSection("umbracoConfiguration/HealthChecks") as IHealthChecks; - SetHealthCheckSettings(healthCheckConfig); - } - } - - /// - /// Constructor - can be used for testing - /// - /// - /// - /// - /// - public UmbracoConfig(IUmbracoSettingsSection umbracoSettings, IDashboardSection dashboardSettings, IHealthChecks healthChecks, IGlobalSettings globalSettings) - { - SetHealthCheckSettings(healthChecks); - SetUmbracoSettings(umbracoSettings); - SetDashboardSettings(dashboardSettings); - SetGlobalConfig(globalSettings); - } - - private IHealthChecks _healthChecks; - private IDashboardSection _dashboardSection; - private IUmbracoSettingsSection _umbracoSettings; - private IGridConfig _gridConfig; - private IGlobalSettings _globalSettings; - - /// - /// Gets the IHealthCheck config - /// - public IHealthChecks HealthCheck() - { - if (_healthChecks == null) - { - var ex = new ConfigurationErrorsException("Could not load the " + typeof(IHealthChecks) + " from config file, ensure the web.config and healthchecks.config files are formatted correctly"); + if ((ConfigurationManager.GetSection(sectionName) is TConfig config)) + return config; + var ex = new ConfigurationErrorsException($"Could not get configuration section \"{sectionName}\" from config files."); Current.Logger.Error(ex, "Config error"); throw ex; } - - return _healthChecks; } /// - /// Gets the IDashboardSection + /// Gets the global configuration. /// - public IDashboardSection DashboardSettings() - { - if (_dashboardSection == null) - { - var ex = new ConfigurationErrorsException("Could not load the " + typeof(IDashboardSection) + " from config file, ensure the web.config and Dashboard.config files are formatted correctly"); - Current.Logger.Error(ex, "Config error"); - throw ex; - } - - return _dashboardSection; - } + public IGlobalSettings Global() + => _global; /// - /// Only for testing + /// Gets the Umbraco configuration. /// - /// - public void SetDashboardSettings(IDashboardSection value) - { - _dashboardSection = value; - } + public IUmbracoSettingsSection Umbraco() + => _umbraco.Value; /// - /// Only for testing + /// Gets the dashboards configuration. /// - /// - public void SetHealthCheckSettings(IHealthChecks value) - { - _healthChecks = value; - } + public IDashboardSection Dashboards() + => _dashboards.Value; /// - /// Only for testing + /// Gets the health checks configuration. /// - /// - public void SetUmbracoSettings(IUmbracoSettingsSection value) - { - _umbracoSettings = value; - } + public IHealthChecks HealthChecks() + => _healthChecks.Value; /// - /// Only for testing + /// Gets the grids configuration. + /// + public IGridConfig Grids() + => _grids.Value; + + /// + /// Sets the global configuration, for tests only. /// - /// public void SetGlobalConfig(IGlobalSettings value) { - _globalSettings = value; + _global = value; } /// - /// Gets the IGlobalSettings + /// Sets the Umbraco configuration, for tests only. /// - public IGlobalSettings GlobalSettings() + public void SetUmbracoConfig(IUmbracoSettingsSection value) { - return _globalSettings ?? (_globalSettings = new GlobalSettings()); + _umbraco = new Lazy(() => value); } /// - /// Gets the IUmbracoSettings - /// - public IUmbracoSettingsSection UmbracoSettings() - { - if (_umbracoSettings == null) - { - var ex = new ConfigurationErrorsException("Could not load the " + typeof (IUmbracoSettingsSection) + " from config file, ensure the web.config and umbracoSettings.config files are formatted correctly"); - Current.Logger.Error(ex, "Config error"); - throw ex; - } - - return _umbracoSettings; - } - - /// - /// Only for testing + /// Sets the dashboards configuration, for tests only. /// /// - public void SetGridConfig(IGridConfig value) + public void SetDashboardsConfig(IDashboardSection value) { - _gridConfig = value; + _dashboards = new Lazy(() => value); } /// - /// Gets the IGridConfig + /// Sets the health checks configuration, for tests only. /// - public IGridConfig GridConfig(ILogger logger, IRuntimeCacheProvider runtimeCache, DirectoryInfo appPlugins, DirectoryInfo configFolder, bool isDebug) + public void SetHealthChecksConfig(IHealthChecks value) { - if (_gridConfig == null) - { - _gridConfig = new GridConfig(logger, runtimeCache, appPlugins, configFolder, isDebug); - } + _healthChecks = new Lazy(() => value); + } - return _gridConfig; + /// + /// Sets the grids configuration, for tests only. + /// + public void SetGridsConfig(IGridConfig value) + { + _grids = new Lazy(() => value); } //TODO: Add other configurations here ! } -} \ No newline at end of file +} diff --git a/src/Umbraco.Core/IO/MediaPathSchemes/OriginalMediaPathScheme.cs b/src/Umbraco.Core/IO/MediaPathSchemes/OriginalMediaPathScheme.cs index 8e53e34ee8..14f0c7602b 100644 --- a/src/Umbraco.Core/IO/MediaPathSchemes/OriginalMediaPathScheme.cs +++ b/src/Umbraco.Core/IO/MediaPathSchemes/OriginalMediaPathScheme.cs @@ -2,6 +2,7 @@ using System.Globalization; using System.IO; using System.Threading; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; namespace Umbraco.Core.IO.MediaPathSchemes @@ -30,7 +31,7 @@ namespace Umbraco.Core.IO.MediaPathSchemes // prevpath should be "/" OR "-" // and we want to reuse the "" part, so try to find it - var sep = UmbracoConfig.For.UmbracoSettings().Content.UploadAllowDirectories ? "/" : "-"; + var sep = Current.Config.Umbraco().Content.UploadAllowDirectories ? "/" : "-"; var pos = previous.IndexOf(sep, StringComparison.Ordinal); var s = pos > 0 ? previous.Substring(0, pos) : null; @@ -44,7 +45,7 @@ namespace Umbraco.Core.IO.MediaPathSchemes if (directory == null) throw new InvalidOperationException("Cannot use a null directory."); - return UmbracoConfig.For.UmbracoSettings().Content.UploadAllowDirectories + return Current.Config.Umbraco().Content.UploadAllowDirectories ? Path.Combine(directory, filename).Replace('\\', '/') : directory + "-" + filename; } diff --git a/src/Umbraco.Core/Logging/Serilog/SerilogLogger.cs b/src/Umbraco.Core/Logging/Serilog/SerilogLogger.cs index 6d3b2b28b3..a7c3f1fab0 100644 --- a/src/Umbraco.Core/Logging/Serilog/SerilogLogger.cs +++ b/src/Umbraco.Core/Logging/Serilog/SerilogLogger.cs @@ -4,6 +4,7 @@ using System.Reflection; using System.Threading; using Serilog; using Serilog.Events; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Diagnostics; @@ -165,7 +166,7 @@ namespace Umbraco.Core.Logging.Serilog messageTemplate += "\r\nThe thread has been aborted, because the request has timed out."; // dump if configured, or if stacktrace contains Monitor.ReliableEnter - dump = UmbracoConfig.For.CoreDebug().DumpOnTimeoutThreadAbort || IsMonitorEnterThreadAbortException(exception); + dump = Current.Config.CoreDebug().DumpOnTimeoutThreadAbort || IsMonitorEnterThreadAbortException(exception); // dump if it is ok to dump (might have a cap on number of dump...) dump &= MiniDump.OkToDump(); diff --git a/src/Umbraco.Core/MainDom.cs b/src/Umbraco.Core/MainDom.cs index 0bbefe3546..0b4551a7cc 100644 --- a/src/Umbraco.Core/MainDom.cs +++ b/src/Umbraco.Core/MainDom.cs @@ -14,7 +14,7 @@ namespace Umbraco.Core /// When an AppDomain starts, it tries to acquire the main domain status. /// When an AppDomain stops (eg the application is restarting) it should release the main domain status. /// - internal class MainDom : IRegisteredObject + internal class MainDom : IMainDom, IRegisteredObject { #region Vars diff --git a/src/Umbraco.Core/Models/Identity/BackOfficeIdentityUser.cs b/src/Umbraco.Core/Models/Identity/BackOfficeIdentityUser.cs index 23c232324a..f163124c2d 100644 --- a/src/Umbraco.Core/Models/Identity/BackOfficeIdentityUser.cs +++ b/src/Umbraco.Core/Models/Identity/BackOfficeIdentityUser.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Reflection; using System.Security.Claims; using System.Threading.Tasks; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Models.Entities; using Umbraco.Core.Models.Membership; @@ -66,7 +67,7 @@ namespace Umbraco.Core.Models.Identity _startContentIds = new int[] { }; _groups = new IReadOnlyUserGroup[] { }; _allowedSections = new string[] { }; - _culture = UmbracoConfig.For.GlobalSettings().DefaultUILanguage; //fixme inject somehow? + _culture = Current.Config.Global().DefaultUILanguage; //fixme inject somehow? _groups = new IReadOnlyUserGroup[0]; _roles = new ObservableCollection>(); _roles.CollectionChanged += _roles_CollectionChanged; @@ -83,7 +84,7 @@ namespace Umbraco.Core.Models.Identity _startContentIds = new int[] { }; _groups = new IReadOnlyUserGroup[] { }; _allowedSections = new string[] { }; - _culture = UmbracoConfig.For.GlobalSettings().DefaultUILanguage; //fixme inject somehow? + _culture = Current.Config.Global().DefaultUILanguage; //fixme inject somehow? _groups = groups.ToArray(); _roles = new ObservableCollection>(_groups.Select(x => new IdentityUserRole { @@ -442,6 +443,6 @@ namespace Umbraco.Core.Models.Identity groups => groups.GetHashCode()); } - + } } diff --git a/src/Umbraco.Core/Models/Membership/User.cs b/src/Umbraco.Core/Models/Membership/User.cs index 0694194996..9387d3eb8f 100644 --- a/src/Umbraco.Core/Models/Membership/User.cs +++ b/src/Umbraco.Core/Models/Membership/User.cs @@ -27,7 +27,7 @@ namespace Umbraco.Core.Models.Membership { SessionTimeout = 60; _userGroups = new HashSet(); - _language = UmbracoConfig.For.GlobalSettings().DefaultUILanguage; //fixme inject somehow? + _language = Current.Config.Global().DefaultUILanguage; //fixme inject somehow? _isApproved = true; _isLockedOut = false; _startContentIds = new int[] { }; @@ -453,7 +453,7 @@ namespace Umbraco.Core.Models.Membership base.PerformDeepClone(clone); var clonedEntity = (User)clone; - + //manually clone the start node props clonedEntity._startContentIds = _startContentIds.ToArray(); clonedEntity._startMediaIds = _startMediaIds.ToArray(); @@ -483,7 +483,7 @@ namespace Umbraco.Core.Models.Membership //need to create new collections otherwise they'll get copied by ref clonedEntity._userGroups = new HashSet(_userGroups); clonedEntity._allowedSections = _allowedSections != null ? new List(_allowedSections) : null; - + } /// diff --git a/src/Umbraco.Core/PropertyEditors/ValueConverters/GridValueConverter.cs b/src/Umbraco.Core/PropertyEditors/ValueConverters/GridValueConverter.cs index d64a89dd07..29f6de0271 100644 --- a/src/Umbraco.Core/PropertyEditors/ValueConverters/GridValueConverter.cs +++ b/src/Umbraco.Core/PropertyEditors/ValueConverters/GridValueConverter.cs @@ -7,6 +7,7 @@ using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Umbraco.Core.Configuration; using Umbraco.Core.Composing; +using Umbraco.Core.Configuration.Grid; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Models.PublishedContent; @@ -19,9 +20,13 @@ namespace Umbraco.Core.PropertyEditors.ValueConverters [DefaultPropertyValueConverter(typeof(JsonValueConverter))] //this shadows the JsonValueConverter public class GridValueConverter : JsonValueConverter { - public GridValueConverter(PropertyEditorCollection propertyEditors) + private readonly IGridConfig _config; + + public GridValueConverter(PropertyEditorCollection propertyEditors, IGridConfig config) : base(propertyEditors) - { } + { + _config = config; + } public override bool IsConverter(PublishedPropertyType propertyType) => propertyType.EditorAlias.InvariantEquals(Constants.PropertyEditors.Aliases.Grid); @@ -46,15 +51,6 @@ namespace Umbraco.Core.PropertyEditors.ValueConverters //so we have the grid json... we need to merge in the grid's configuration values with the values // we've saved in the database so that when the front end gets this value, it is up-to-date. - //TODO: Change all singleton access to use ctor injection in v8!!! - //TODO: That would mean that property value converters would need to be request lifespan, hrm.... - var gridConfig = UmbracoConfig.For.GridConfig( - Current.ProfilingLogger, - Current.ApplicationCache.RuntimeCache, - new DirectoryInfo(IOHelper.MapPath(SystemDirectories.AppPlugins)), - new DirectoryInfo(IOHelper.MapPath(SystemDirectories.Config)), - Current.RuntimeState.Debug); - var sections = GetArray(obj, "sections"); foreach (var section in sections.Cast()) { @@ -74,7 +70,7 @@ namespace Umbraco.Core.PropertyEditors.ValueConverters if (alias.IsNullOrWhiteSpace() == false) { //find the alias in config - var found = gridConfig.EditorsConfig.Editors.FirstOrDefault(x => x.Alias == alias); + var found = _config.EditorsConfig.Editors.FirstOrDefault(x => x.Alias == alias); if (found != null) { //add/replace the editor value with the one from config diff --git a/src/Umbraco.Core/Runtime/CoreRuntime.cs b/src/Umbraco.Core/Runtime/CoreRuntime.cs index c677f16909..c924dc5a1e 100644 --- a/src/Umbraco.Core/Runtime/CoreRuntime.cs +++ b/src/Umbraco.Core/Runtime/CoreRuntime.cs @@ -69,7 +69,7 @@ namespace Umbraco.Core.Runtime var databaseFactory = GetDatabaseFactory(); // type loader - var globalSettings = UmbracoConfig.For.GlobalSettings(); + var globalSettings = Current.Config.Global(); var localTempStorage = globalSettings.LocalTempStorageLocation; var typeLoader = new TypeLoader(runtimeCache, localTempStorage, profilingLogger); @@ -77,16 +77,19 @@ namespace Umbraco.Core.Runtime // beware! must use '() => _factory.GetInstance()' and NOT '_factory.GetInstance' // as the second one captures the current value (null) and therefore fails _state = new RuntimeState(logger, - UmbracoConfig.For.UmbracoSettings(), UmbracoConfig.For.GlobalSettings(), + Current.Config.Umbraco(), Current.Config.Global(), new Lazy(() => _factory.GetInstance()), new Lazy(() => _factory.GetInstance())) { Level = RuntimeLevel.Boot }; + // main dom + var mainDom = new MainDom(logger); + // create the composition var composition = new Composition(register, typeLoader, profilingLogger, _state); - composition.RegisterEssentials(logger, profiler, profilingLogger, appCaches, databaseFactory, typeLoader, _state); + composition.RegisterEssentials(logger, profiler, profilingLogger, mainDom, appCaches, databaseFactory, typeLoader, _state); // register runtime-level services // there should be none, really - this is here "just in case" @@ -113,8 +116,7 @@ namespace Umbraco.Core.Runtime logger.Debug("Runtime: {Runtime}", GetType().FullName); - var mainDom = AquireMainDom(); - composition.RegisterUnique(mainDom); + AquireMainDom(mainDom); DetermineRuntimeLevel(databaseFactory); @@ -195,15 +197,13 @@ namespace Umbraco.Core.Runtime IOHelper.SetRootDirectory(path); } - private MainDom AquireMainDom() + private void AquireMainDom(MainDom mainDom) { using (var timer = ProfilingLogger.DebugDuration("Acquiring MainDom.", "Acquired.")) { try { - var mainDom = new MainDom(Logger); mainDom.Acquire(); - return mainDom; } catch { diff --git a/src/Umbraco.Core/Scoping/Scope.cs b/src/Umbraco.Core/Scoping/Scope.cs index adc5482e68..daef4c4cd7 100644 --- a/src/Umbraco.Core/Scoping/Scope.cs +++ b/src/Umbraco.Core/Scoping/Scope.cs @@ -1,6 +1,7 @@ using System; using System.Data; using Umbraco.Core.Cache; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Events; using Umbraco.Core.IO; @@ -491,7 +492,7 @@ namespace Umbraco.Core.Scoping // caching config // true if Umbraco.CoreDebug.LogUncompletedScope appSetting is set to "true" private static bool LogUncompletedScopes => (_logUncompletedScopes - ?? (_logUncompletedScopes = UmbracoConfig.For.CoreDebug().LogUncompletedScopes)).Value; + ?? (_logUncompletedScopes = Current.Config.CoreDebug().LogUncompletedScopes)).Value; /// public void ReadLock(params int[] lockIds) diff --git a/src/Umbraco.Core/Security/MembershipProviderExtensions.cs b/src/Umbraco.Core/Security/MembershipProviderExtensions.cs index ca01330212..10f44c46e7 100644 --- a/src/Umbraco.Core/Security/MembershipProviderExtensions.cs +++ b/src/Umbraco.Core/Security/MembershipProviderExtensions.cs @@ -4,6 +4,7 @@ using System.Threading; using System.Web; using System.Web.Hosting; using System.Web.Security; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Models; using Umbraco.Core.Services; @@ -87,11 +88,11 @@ namespace Umbraco.Core.Security /// public static MembershipProvider GetUsersMembershipProvider() { - if (Membership.Providers[UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider] == null) + if (Membership.Providers[Current.Config.Umbraco().Providers.DefaultBackOfficeUserProvider] == null) { - throw new InvalidOperationException("No membership provider found with name " + UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider); + throw new InvalidOperationException("No membership provider found with name " + Current.Config.Umbraco().Providers.DefaultBackOfficeUserProvider); } - return Membership.Providers[UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider]; + return Membership.Providers[Current.Config.Umbraco().Providers.DefaultBackOfficeUserProvider]; } /// diff --git a/src/Umbraco.Core/StringExtensions.cs b/src/Umbraco.Core/StringExtensions.cs index 03a371204c..9517d7f1d5 100644 --- a/src/Umbraco.Core/StringExtensions.cs +++ b/src/Umbraco.Core/StringExtensions.cs @@ -1115,7 +1115,7 @@ namespace Umbraco.Core /// Checks UmbracoSettings.ForceSafeAliases to determine whether it should filter the text. public static string ToSafeAliasWithForcingCheck(this string alias) { - return UmbracoConfig.For.UmbracoSettings().Content.ForceSafeAliases ? alias.ToSafeAlias() : alias; + return Current.Config.Umbraco().Content.ForceSafeAliases ? alias.ToSafeAlias() : alias; } /// @@ -1127,7 +1127,7 @@ namespace Umbraco.Core /// Checks UmbracoSettings.ForceSafeAliases to determine whether it should filter the text. public static string ToSafeAliasWithForcingCheck(this string alias, string culture) { - return UmbracoConfig.For.UmbracoSettings().Content.ForceSafeAliases ? alias.ToSafeAlias(culture) : alias; + return Current.Config.Umbraco().Content.ForceSafeAliases ? alias.ToSafeAlias(culture) : alias; } // the new methods to get a url segment diff --git a/src/Umbraco.Tests/Configurations/GlobalSettingsTests.cs b/src/Umbraco.Tests/Configurations/GlobalSettingsTests.cs index ebba8bc1cc..d588e19f07 100644 --- a/src/Umbraco.Tests/Configurations/GlobalSettingsTests.cs +++ b/src/Umbraco.Tests/Configurations/GlobalSettingsTests.cs @@ -2,6 +2,7 @@ using System.Web.Routing; using Moq; using NUnit.Framework; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.IO; using Umbraco.Tests.TestHelpers; @@ -50,7 +51,7 @@ namespace Umbraco.Tests.Configurations SettingsForTests.ConfigureSettings(globalSettingsMock.Object); SystemDirectories.Root = rootPath; - Assert.AreEqual(outcome, UmbracoConfig.For.GlobalSettings().GetUmbracoMvcArea()); + Assert.AreEqual(outcome, Current.Config.Global().GetUmbracoMvcArea()); } [TestCase("/umbraco/umbraco.aspx")] diff --git a/src/Umbraco.Tests/IO/ShadowFileSystemTests.cs b/src/Umbraco.Tests/IO/ShadowFileSystemTests.cs index 36f4c56173..262b026cae 100644 --- a/src/Umbraco.Tests/IO/ShadowFileSystemTests.cs +++ b/src/Umbraco.Tests/IO/ShadowFileSystemTests.cs @@ -41,7 +41,7 @@ namespace Umbraco.Tests.IO private static void ClearFiles() { TestHelper.DeleteDirectory(IOHelper.MapPath("FileSysTests")); - TestHelper.DeleteDirectory(IOHelper.MapPath("App_Data")); + TestHelper.DeleteDirectory(IOHelper.MapPath("App_Data/TEMP/ShadowFs")); } private static string NormPath(string path) @@ -388,9 +388,9 @@ namespace Umbraco.Tests.IO var logger = Mock.Of(); var path = IOHelper.MapPath("FileSysTests"); - var appdata = IOHelper.MapPath("App_Data"); + var shadowfs = IOHelper.MapPath("App_Data/TEMP/ShadowFs"); Directory.CreateDirectory(path); - Directory.CreateDirectory(appdata); + Directory.CreateDirectory(shadowfs); var scopedFileSystems = false; @@ -409,24 +409,24 @@ namespace Umbraco.Tests.IO // explicit shadow without scope does not work sw.Shadow(id = Guid.NewGuid()); - Assert.IsTrue(Directory.Exists(appdata + "/TEMP/ShadowFs/" + id)); + Assert.IsTrue(Directory.Exists(shadowfs + "/" + id)); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) sw.AddFile("sub/f2.txt", ms); Assert.IsTrue(phy.FileExists("sub/f2.txt")); sw.UnShadow(true); Assert.IsTrue(phy.FileExists("sub/f2.txt")); - Assert.IsFalse(Directory.Exists(appdata + "/TEMP/ShadowFs/" + id)); + Assert.IsFalse(Directory.Exists(shadowfs + "/" + id)); // shadow with scope but no complete does not complete scopedFileSystems = true; // pretend we have a scope var scope = new ShadowFileSystems(fileSystems, id = Guid.NewGuid()); - Assert.IsTrue(Directory.Exists(appdata + "/TEMP/ShadowFs/" + id)); + Assert.IsTrue(Directory.Exists(shadowfs + "/" + id)); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) sw.AddFile("sub/f3.txt", ms); Assert.IsFalse(phy.FileExists("sub/f3.txt")); - var dirs = Directory.GetDirectories(appdata + "/TEMP/ShadowFs"); + var dirs = Directory.GetDirectories(shadowfs); Assert.AreEqual(1, dirs.Length); - Assert.AreEqual((appdata + "/TEMP/ShadowFs/" + id).Replace('\\', '/'), dirs[0].Replace('\\', '/')); + Assert.AreEqual((shadowfs + "/" + id).Replace('\\', '/'), dirs[0].Replace('\\', '/')); dirs = Directory.GetDirectories(dirs[0]); var typedDir = dirs.FirstOrDefault(x => x.Replace('\\', '/').EndsWith("/typed")); Assert.IsNotNull(typedDir); @@ -436,28 +436,28 @@ namespace Umbraco.Tests.IO scope.Dispose(); scopedFileSystems = false; Assert.IsFalse(phy.FileExists("sub/f3.txt")); - TestHelper.TryAssert(() => Assert.IsFalse(Directory.Exists(appdata + "/TEMP/ShadowFs/" + id))); + TestHelper.TryAssert(() => Assert.IsFalse(Directory.Exists(shadowfs + "/" + id))); // shadow with scope and complete does complete scopedFileSystems = true; // pretend we have a scope scope = new ShadowFileSystems(fileSystems, id = Guid.NewGuid()); - Assert.IsTrue(Directory.Exists(appdata + "/TEMP/ShadowFs/" + id)); + Assert.IsTrue(Directory.Exists(shadowfs + "/" + id)); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) sw.AddFile("sub/f4.txt", ms); Assert.IsFalse(phy.FileExists("sub/f4.txt")); - Assert.AreEqual(1, Directory.GetDirectories(appdata + "/TEMP/ShadowFs").Length); + Assert.AreEqual(1, Directory.GetDirectories(shadowfs).Length); scope.Complete(); scope.Dispose(); scopedFileSystems = false; - TestHelper.TryAssert(() => Assert.AreEqual(0, Directory.GetDirectories(appdata + "/TEMP/ShadowFs").Length)); + TestHelper.TryAssert(() => Assert.AreEqual(0, Directory.GetDirectories(shadowfs).Length)); Assert.IsTrue(phy.FileExists("sub/f4.txt")); - Assert.IsFalse(Directory.Exists(appdata + "/TEMP/ShadowFs/" + id)); + Assert.IsFalse(Directory.Exists(shadowfs + "/" + id)); // test scope for "another thread" scopedFileSystems = true; // pretend we have a scope scope = new ShadowFileSystems(fileSystems, id = Guid.NewGuid()); - Assert.IsTrue(Directory.Exists(appdata + "/TEMP/ShadowFs/" + id)); + Assert.IsTrue(Directory.Exists(shadowfs + "/" + id)); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) sw.AddFile("sub/f5.txt", ms); Assert.IsFalse(phy.FileExists("sub/f5.txt")); @@ -473,7 +473,7 @@ namespace Umbraco.Tests.IO scope.Dispose(); scopedFileSystems = false; Assert.IsTrue(phy.FileExists("sub/f5.txt")); - Assert.IsFalse(Directory.Exists(appdata + "/TEMP/ShadowFs/" + id)); + Assert.IsFalse(Directory.Exists(shadowfs + "/" + id)); } [Test] @@ -482,7 +482,7 @@ namespace Umbraco.Tests.IO var logger = Mock.Of(); var path = IOHelper.MapPath("FileSysTests"); - var appdata = IOHelper.MapPath("App_Data"); + var shadowfs = IOHelper.MapPath("App_Data/TEMP/ShadowFs"); Directory.CreateDirectory(path); var scopedFileSystems = false; @@ -502,7 +502,7 @@ namespace Umbraco.Tests.IO scopedFileSystems = true; // pretend we have a scope var scope = new ShadowFileSystems(fileSystems, id = Guid.NewGuid()); - Assert.IsTrue(Directory.Exists(appdata + "/TEMP/ShadowFs/" + id)); + Assert.IsTrue(Directory.Exists(shadowfs + "/" + id)); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) sw.AddFile("sub/f2.txt", ms); Assert.IsFalse(phy.FileExists("sub/f2.txt")); @@ -518,7 +518,7 @@ namespace Umbraco.Tests.IO scope.Dispose(); scopedFileSystems = false; Assert.IsTrue(phy.FileExists("sub/f2.txt")); - TestHelper.TryAssert(() => Assert.IsFalse(Directory.Exists(appdata + "/TEMP/ShadowFs/" + id))); + TestHelper.TryAssert(() => Assert.IsFalse(Directory.Exists(shadowfs + "/" + id))); string text; using (var s = phy.OpenFile("sub/f2.txt")) @@ -535,7 +535,7 @@ namespace Umbraco.Tests.IO var logger = Mock.Of(); var path = IOHelper.MapPath("FileSysTests"); - var appdata = IOHelper.MapPath("App_Data"); + var shadowfs = IOHelper.MapPath("App_Data/TEMP/ShadowFs"); Directory.CreateDirectory(path); var scopedFileSystems = false; @@ -555,7 +555,7 @@ namespace Umbraco.Tests.IO scopedFileSystems = true; // pretend we have a scope var scope = new ShadowFileSystems(fileSystems, id = Guid.NewGuid()); - Assert.IsTrue(Directory.Exists(appdata + "/TEMP/ShadowFs/" + id)); + Assert.IsTrue(Directory.Exists(shadowfs + "/" + id)); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes("foo"))) sw.AddFile("sub/f2.txt", ms); Assert.IsFalse(phy.FileExists("sub/f2.txt")); diff --git a/src/Umbraco.Tests/Macros/MacroTests.cs b/src/Umbraco.Tests/Macros/MacroTests.cs index 2cb7b1aa4e..3ab56052e0 100644 --- a/src/Umbraco.Tests/Macros/MacroTests.cs +++ b/src/Umbraco.Tests/Macros/MacroTests.cs @@ -4,6 +4,7 @@ using System.Web.UI.WebControls; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Cache; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Models; using Umbraco.Tests.TestHelpers; @@ -26,7 +27,7 @@ namespace Umbraco.Tests.Macros new IsolatedRuntimeCache(type => new ObjectCacheRuntimeCacheProvider())); //Current.ApplicationContext = new ApplicationContext(cacheHelper, new ProfilingLogger(Mock.Of(), Mock.Of())); - UmbracoConfig.For.SetUmbracoSettings(SettingsForTests.GetDefaultUmbracoSettings()); + Current.Config.SetUmbracoConfig(SettingsForTests.GetDefaultUmbracoSettings()); } [TestCase("123", "IntProp", typeof(int))] diff --git a/src/Umbraco.Tests/PublishedContent/NuCacheTests.cs b/src/Umbraco.Tests/PublishedContent/NuCacheTests.cs index 492f1f7dc0..15ac7ab328 100644 --- a/src/Umbraco.Tests/PublishedContent/NuCacheTests.cs +++ b/src/Umbraco.Tests/PublishedContent/NuCacheTests.cs @@ -4,6 +4,7 @@ using System.Data; using Moq; using NUnit.Framework; using Umbraco.Core; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Events; using Umbraco.Core.Logging; @@ -35,7 +36,7 @@ namespace Umbraco.Tests.PublishedContent // use any local db files, does not rely on any database) - and tests variations SettingsForTests.ConfigureSettings(SettingsForTests.GenerateMockUmbracoSettings()); - var globalSettings = UmbracoConfig.For.GlobalSettings(); + var globalSettings = Current.Config.Global(); // create a content node kit var kit = new ContentNodeKit diff --git a/src/Umbraco.Tests/Routing/ContentFinderByUrlTests.cs b/src/Umbraco.Tests/Routing/ContentFinderByUrlTests.cs index 8b591dfb84..e4002c0da1 100644 --- a/src/Umbraco.Tests/Routing/ContentFinderByUrlTests.cs +++ b/src/Umbraco.Tests/Routing/ContentFinderByUrlTests.cs @@ -2,6 +2,7 @@ using System.Globalization; using Moq; using NUnit.Framework; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Models; using Umbraco.Tests.TestHelpers; @@ -36,7 +37,7 @@ namespace Umbraco.Tests.Routing var frequest = publishedRouter.CreateRequest(umbracoContext); var lookup = new ContentFinderByUrl(Logger); - Assert.IsTrue(UmbracoConfig.For.GlobalSettings().HideTopLevelNodeFromPath); + Assert.IsTrue(Current.Config.Global().HideTopLevelNodeFromPath); // fixme debugging - going further down, the routes cache is NOT empty?! if (urlString == "/home/sub1") @@ -66,13 +67,13 @@ namespace Umbraco.Tests.Routing var globalSettingsMock = Mock.Get(TestObjects.GetGlobalSettings()); //this will modify the IGlobalSettings instance stored in the container globalSettingsMock.Setup(x => x.HideTopLevelNodeFromPath).Returns(false); SettingsForTests.ConfigureSettings(globalSettingsMock.Object); - + var umbracoContext = GetUmbracoContext(urlString, globalSettings:globalSettingsMock.Object); var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); var lookup = new ContentFinderByUrl(Logger); - Assert.IsFalse(UmbracoConfig.For.GlobalSettings().HideTopLevelNodeFromPath); + Assert.IsFalse(Current.Config.Global().HideTopLevelNodeFromPath); var result = lookup.TryFindContent(frequest); @@ -97,7 +98,7 @@ namespace Umbraco.Tests.Routing var publishedRouter = CreatePublishedRouter(); var frequest = publishedRouter.CreateRequest(umbracoContext); var lookup = new ContentFinderByUrl(Logger); - + var result = lookup.TryFindContent(frequest); Assert.IsTrue(result); @@ -156,7 +157,7 @@ namespace Umbraco.Tests.Routing var frequest = publishedRouter.CreateRequest(umbracoContext); frequest.Domain = new DomainAndUri(new Domain(1, "mysite/æøå", -1, CultureInfo.CurrentCulture, false), new Uri("http://mysite/æøå")); var lookup = new ContentFinderByUrl(Logger); - + var result = lookup.TryFindContent(frequest); Assert.IsTrue(result); diff --git a/src/Umbraco.Tests/Runtimes/CoreRuntimeTests.cs b/src/Umbraco.Tests/Runtimes/CoreRuntimeTests.cs index 2ef6480193..addf63f55f 100644 --- a/src/Umbraco.Tests/Runtimes/CoreRuntimeTests.cs +++ b/src/Umbraco.Tests/Runtimes/CoreRuntimeTests.cs @@ -134,12 +134,12 @@ namespace Umbraco.Tests.Runtimes composition.RegisterUnique(scopeProvider); } - private MainDom _mainDom; + private IMainDom _mainDom; public override IFactory Boot(IRegister container) { var factory = base.Boot(container); - _mainDom = factory.GetInstance(); + _mainDom = factory.GetInstance(); return factory; } diff --git a/src/Umbraco.Tests/Runtimes/StandaloneTests.cs b/src/Umbraco.Tests/Runtimes/StandaloneTests.cs index 91af6ebeb6..038916f09a 100644 --- a/src/Umbraco.Tests/Runtimes/StandaloneTests.cs +++ b/src/Umbraco.Tests/Runtimes/StandaloneTests.cs @@ -1,8 +1,6 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Text; -using System.Threading.Tasks; using Moq; using NUnit.Framework; using Umbraco.Core; @@ -23,7 +21,7 @@ namespace Umbraco.Tests.Runtimes { [Test] [Explicit("This test must be run manually")] - public void Test() + public void ValidateComposition() { // this is almost what CoreRuntime does, without // - managing MainDom @@ -40,27 +38,18 @@ namespace Umbraco.Tests.Runtimes var typeLoader = new TypeLoader(appCaches.RuntimeCache, LocalTempStorage.Default, profilingLogger); var runtimeState = Mock.Of(); Mock.Get(runtimeState).Setup(x => x.Level).Returns(RuntimeLevel.Run); + var mainDom = Mock.Of(); + Mock.Get(mainDom).Setup(x => x.IsMainDom).Returns(true); // create the register and the composition var register = RegisterFactory.Create(); var composition = new Composition(register, typeLoader, profilingLogger, runtimeState); - composition.RegisterEssentials(logger, profiler, profilingLogger, appCaches, databaseFactory, typeLoader, runtimeState); + composition.RegisterEssentials(logger, profiler, profilingLogger, mainDom, appCaches, databaseFactory, typeLoader, runtimeState); // create the core runtime and have it compose itself var coreRuntime = new CoreRuntime(); coreRuntime.Compose(composition); - // fixme - // at that point, CoreRuntime also does - //composition.RegisterUnique(mainDom) - // we should make it - composition.RegisterUnique(Mock.Of()); - //composition.RegisterUnique(new SimpleMainDom()); - // because some components want to use it - // (and then, what would a standalone maindom be?) - // - // is this an essential thing then?? - // get the components // all of them? var componentTypes = typeLoader.GetTypes(); @@ -92,34 +81,45 @@ namespace Umbraco.Tests.Runtimes foreach (var result in resultGroup) { Console.WriteLine(); - Console.WriteLine($"{result.Severity}: {WordWrap(result.Message, 120)}"); - var target = result.ValidationTarget; - Console.Write("\tsvce: "); - Console.Write(target.ServiceName); - Console.Write(target.DeclaringService.ServiceType); - if (!target.DeclaringService.ServiceName.IsNullOrWhiteSpace()) - { - Console.Write(" '"); - Console.Write(target.DeclaringService.ServiceName); - Console.Write("'"); - } - - Console.Write(" ("); - if (target.DeclaringService.Lifetime == null) - Console.Write("?"); - else - Console.Write(target.DeclaringService.Lifetime.ToString().TrimStart("LightInject.")); - Console.WriteLine(")"); - Console.Write("\timpl: "); - Console.WriteLine(target.DeclaringService.ImplementingType); - Console.Write("\tparm: "); - Console.Write(target.Parameter); - Console.WriteLine(); + Console.Write(ToText(result)); } + Assert.AreEqual(0, results.Count); } - public static string WordWrap(string text, int width) + private static string ToText(ValidationResult result) + { + var text = new StringBuilder(); + + text.AppendLine($"{result.Severity}: {WordWrap(result.Message, 120)}"); + var target = result.ValidationTarget; + text.Append("\tsvce: "); + text.Append(target.ServiceName); + text.Append(target.DeclaringService.ServiceType); + if (!target.DeclaringService.ServiceName.IsNullOrWhiteSpace()) + { + text.Append(" '"); + text.Append(target.DeclaringService.ServiceName); + text.Append("'"); + } + + text.Append(" ("); + if (target.DeclaringService.Lifetime == null) + text.Append("Transient"); + else + text.Append(target.DeclaringService.Lifetime.ToString().TrimStart("LightInject.").TrimEnd("Lifetime")); + text.AppendLine(")"); + text.Append("\timpl: "); + text.Append(target.DeclaringService.ImplementingType); + text.AppendLine(); + text.Append("\tparm: "); + text.Append(target.Parameter); + text.AppendLine(); + + return text.ToString(); + } + + private static string WordWrap(string text, int width) { int pos, next; var sb = new StringBuilder(); @@ -169,7 +169,7 @@ namespace Umbraco.Tests.Runtimes return sb.ToString(); } - public static int BreakLine(string text, int pos, int max) + private static int BreakLine(string text, int pos, int max) { // Find last whitespace in line var i = max - 1; diff --git a/src/Umbraco.Tests/Scoping/ScopeFileSystemsTests.cs b/src/Umbraco.Tests/Scoping/ScopeFileSystemsTests.cs index aa41bdd613..0ef0e9362b 100644 --- a/src/Umbraco.Tests/Scoping/ScopeFileSystemsTests.cs +++ b/src/Umbraco.Tests/Scoping/ScopeFileSystemsTests.cs @@ -45,7 +45,7 @@ namespace Umbraco.Tests.Scoping { TestHelper.DeleteDirectory(IOHelper.MapPath("media")); TestHelper.DeleteDirectory(IOHelper.MapPath("FileSysTests")); - TestHelper.DeleteDirectory(IOHelper.MapPath("App_Data")); + TestHelper.DeleteDirectory(IOHelper.MapPath("App_Data/TEMP/ShadowFs")); } [TestCase(true)] diff --git a/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs b/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs index d38cd8af6f..5f08478658 100644 --- a/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs +++ b/src/Umbraco.Tests/TestHelpers/SettingsForTests.cs @@ -3,6 +3,7 @@ using System.IO; using System.Configuration; using Moq; using Umbraco.Core; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.IO; @@ -13,7 +14,7 @@ namespace Umbraco.Tests.TestHelpers { public static void ConfigureSettings(IGlobalSettings settings) { - UmbracoConfig.For.SetGlobalConfig(settings); + Current.Config.SetGlobalConfig(settings); } // umbracoSettings @@ -24,7 +25,7 @@ namespace Umbraco.Tests.TestHelpers /// public static void ConfigureSettings(IUmbracoSettingsSection settings) { - UmbracoConfig.For.SetUmbracoSettings(settings); + Current.Config.SetUmbracoConfig(settings); } public static IGlobalSettings GenerateMockGlobalSettings() @@ -103,7 +104,7 @@ namespace Umbraco.Tests.TestHelpers // SaveSetting("umbracoConfigurationStatus"); //} - + // reset & defaults diff --git a/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs b/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs index fc3224131f..d640d68333 100644 --- a/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs +++ b/src/Umbraco.Tests/Web/TemplateUtilitiesTests.cs @@ -47,7 +47,7 @@ namespace Umbraco.Tests.Web Udi.ResetUdiTypes(); - UmbracoConfig.For.SetUmbracoSettings(SettingsForTests.GetDefaultUmbracoSettings()); + Current.Config.SetUmbracoConfig(SettingsForTests.GetDefaultUmbracoSettings()); } [TearDown] diff --git a/src/Umbraco.Web.UI/Umbraco/umbraco.aspx.cs b/src/Umbraco.Web.UI/Umbraco/umbraco.aspx.cs index b70378bb01..c4d7992db4 100644 --- a/src/Umbraco.Web.UI/Umbraco/umbraco.aspx.cs +++ b/src/Umbraco.Web.UI/Umbraco/umbraco.aspx.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; namespace Umbraco.Web.UI.Umbraco @@ -13,7 +14,7 @@ namespace Umbraco.Web.UI.Umbraco protected void Page_Load(object sender, EventArgs e) { Response.Status = "301 Moved Permanently"; - Response.AddHeader("Location", UmbracoConfig.For.GlobalSettings().Path); + Response.AddHeader("Location", Current.Config.Global().Path); } } } diff --git a/src/Umbraco.Web/Composing/Current.cs b/src/Umbraco.Web/Composing/Current.cs index 6fce8c1318..fc67465e1a 100644 --- a/src/Umbraco.Web/Composing/Current.cs +++ b/src/Umbraco.Web/Composing/Current.cs @@ -10,6 +10,7 @@ using Umbraco.Core.Logging; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Persistence; using Umbraco.Core.Composing; +using Umbraco.Core.Configuration; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Scoping; using Umbraco.Core.Services; @@ -200,6 +201,8 @@ namespace Umbraco.Web.Composing public static TypeLoader TypeLoader => CoreCurrent.TypeLoader; + public static UmbracoConfig Config => CoreCurrent.Config; + public static UrlSegmentProviderCollection UrlSegmentProviders => CoreCurrent.UrlSegmentProviders; public static CacheRefresherCollection CacheRefreshers => CoreCurrent.CacheRefreshers; diff --git a/src/Umbraco.Web/Editors/AuthenticationController.cs b/src/Umbraco.Web/Editors/AuthenticationController.cs index eee6997da2..594b450e82 100644 --- a/src/Umbraco.Web/Editors/AuthenticationController.cs +++ b/src/Umbraco.Web/Editors/AuthenticationController.cs @@ -300,7 +300,7 @@ namespace Umbraco.Web.Editors { // If this feature is switched off in configuration the UI will be amended to not make the request to reset password available. // So this is just a server-side secondary check. - if (UmbracoConfig.For.UmbracoSettings().Security.AllowPasswordReset == false) + if (Current.Config.Umbraco().Security.AllowPasswordReset == false) { throw new HttpResponseException(HttpStatusCode.BadRequest); } diff --git a/src/Umbraco.Web/Editors/BackOfficeController.cs b/src/Umbraco.Web/Editors/BackOfficeController.cs index 668b35c2d9..e323f92c57 100644 --- a/src/Umbraco.Web/Editors/BackOfficeController.cs +++ b/src/Umbraco.Web/Editors/BackOfficeController.cs @@ -233,13 +233,7 @@ namespace Umbraco.Web.Editors [HttpGet] public JsonNetResult GetGridConfig() { - var gridConfig = UmbracoConfig.For.GridConfig( - Logger, - ApplicationCache.RuntimeCache, - new DirectoryInfo(Server.MapPath(SystemDirectories.AppPlugins)), - new DirectoryInfo(Server.MapPath(SystemDirectories.Config)), - HttpContext.IsDebuggingEnabled); - + var gridConfig = Current.Config.Grids(); return new JsonNetResult { Data = gridConfig.EditorsConfig.Editors, Formatting = Formatting.Indented }; } diff --git a/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs b/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs index b6448f8b74..eba7a627ad 100644 --- a/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs +++ b/src/Umbraco.Web/Editors/BackOfficeServerVariables.cs @@ -314,25 +314,25 @@ namespace Umbraco.Web.Editors {"appPluginsPath", IOHelper.ResolveUrl(SystemDirectories.AppPlugins).TrimEnd('/')}, { "imageFileTypes", - string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.ImageFileTypes) + string.Join(",", Current.Config.Umbraco().Content.ImageFileTypes) }, { "disallowedUploadFiles", - string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.DisallowedUploadFiles) + string.Join(",", Current.Config.Umbraco().Content.DisallowedUploadFiles) }, { "allowedUploadFiles", - string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.AllowedUploadFiles) + string.Join(",", Current.Config.Umbraco().Content.AllowedUploadFiles) }, { "maxFileSize", GetMaxRequestLength() }, - {"keepUserLoggedIn", UmbracoConfig.For.UmbracoSettings().Security.KeepUserLoggedIn}, - {"usernameIsEmail", UmbracoConfig.For.UmbracoSettings().Security.UsernameIsEmail}, + {"keepUserLoggedIn", Current.Config.Umbraco().Security.KeepUserLoggedIn}, + {"usernameIsEmail", Current.Config.Umbraco().Security.UsernameIsEmail}, {"cssPath", IOHelper.ResolveUrl(SystemDirectories.Css).TrimEnd('/')}, - {"allowPasswordReset", UmbracoConfig.For.UmbracoSettings().Security.AllowPasswordReset}, - {"loginBackgroundImage", UmbracoConfig.For.UmbracoSettings().Content.LoginBackgroundImage}, + {"allowPasswordReset", Current.Config.Umbraco().Security.AllowPasswordReset}, + {"loginBackgroundImage", Current.Config.Umbraco().Content.LoginBackgroundImage}, {"showUserInvite", EmailSender.CanSendRequiredEmail}, {"canSendRequiredEmail", EmailSender.CanSendRequiredEmail}, } diff --git a/src/Umbraco.Web/Editors/DataTypeController.cs b/src/Umbraco.Web/Editors/DataTypeController.cs index e11ea7cbef..79671595f4 100644 --- a/src/Umbraco.Web/Editors/DataTypeController.cs +++ b/src/Umbraco.Web/Editors/DataTypeController.cs @@ -344,7 +344,7 @@ namespace Umbraco.Web.Editors public IDictionary> GetGroupedPropertyEditors() { var datatypes = new List(); - var showDeprecatedPropertyEditors = UmbracoConfig.For.UmbracoSettings().Content.ShowDeprecatedPropertyEditors; + var showDeprecatedPropertyEditors = Current.Config.Umbraco().Content.ShowDeprecatedPropertyEditors; var propertyEditors = Current.PropertyEditors .Where(x=>x.IsDeprecated == false || showDeprecatedPropertyEditors); diff --git a/src/Umbraco.Web/Editors/MediaController.cs b/src/Umbraco.Web/Editors/MediaController.cs index dd224dc551..a15f6e9df7 100644 --- a/src/Umbraco.Web/Editors/MediaController.cs +++ b/src/Umbraco.Web/Editors/MediaController.cs @@ -23,6 +23,7 @@ using Umbraco.Web.Mvc; using Umbraco.Web.WebApi; using System.Linq; using System.Web.Http.Controllers; +using Umbraco.Core.Composing; using Umbraco.Web.WebApi.Filters; using Constants = Umbraco.Core.Constants; using Umbraco.Core.Configuration; @@ -426,7 +427,7 @@ namespace Umbraco.Web.Editors var toMove = ValidateMoveOrCopy(move); var destinationParentID = move.ParentId; var sourceParentID = toMove.ParentId; - + var moveResult = Services.MediaService.Move(toMove, move.ParentId); if (sourceParentID == destinationParentID) @@ -543,7 +544,7 @@ namespace Umbraco.Web.Editors return display; } - + /// /// Empties the recycle bin /// @@ -596,11 +597,11 @@ namespace Umbraco.Web.Editors throw; } } - + public MediaItemDisplay PostAddFolder(PostedFolder folder) { var intParentId = GetParentIdAsInt(folder.ParentId, validatePermissions:true); - + var mediaService = Services.MediaService; var f = mediaService.CreateMedia(folder.Name, intParentId, Constants.Conventions.MediaTypes.Folder); @@ -640,10 +641,10 @@ namespace Umbraco.Web.Editors //get the string json from the request string currentFolderId = result.FormData["currentFolder"]; int parentId = GetParentIdAsInt(currentFolderId, validatePermissions: true); - + var tempFiles = new PostedFiles(); var mediaService = Services.MediaService; - + //in case we pass a path with a folder in it, we will create it and upload media to it. if (result.FormData.ContainsKey("path")) { @@ -701,13 +702,13 @@ namespace Umbraco.Web.Editors var safeFileName = fileName.ToSafeFileName(); var ext = safeFileName.Substring(safeFileName.LastIndexOf('.') + 1).ToLower(); - if (UmbracoConfig.For.UmbracoSettings().Content.IsFileAllowedForUpload(ext)) + if (Current.Config.Umbraco().Content.IsFileAllowedForUpload(ext)) { var mediaType = Constants.Conventions.MediaTypes.File; if (result.FormData["contentTypeAlias"] == Constants.Conventions.MediaTypes.AutoSelect) { - if (UmbracoConfig.For.UmbracoSettings().Content.ImageFileTypes.Contains(ext)) + if (Current.Config.Umbraco().Content.ImageFileTypes.Contains(ext)) { mediaType = Constants.Conventions.MediaTypes.Image; } diff --git a/src/Umbraco.Web/Editors/RedirectUrlManagementController.cs b/src/Umbraco.Web/Editors/RedirectUrlManagementController.cs index 377b76f52a..f0a95897e8 100644 --- a/src/Umbraco.Web/Editors/RedirectUrlManagementController.cs +++ b/src/Umbraco.Web/Editors/RedirectUrlManagementController.cs @@ -13,6 +13,7 @@ using Umbraco.Web.Mvc; using Umbraco.Web.WebApi; using File = System.IO.File; using Umbraco.Core; +using Umbraco.Core.Composing; namespace Umbraco.Web.Editors { @@ -33,7 +34,7 @@ namespace Umbraco.Web.Editors [HttpGet] public IHttpActionResult GetEnableState() { - var enabled = UmbracoConfig.For.UmbracoSettings().WebRouting.DisableRedirectUrlTracking == false; + var enabled = Current.Config.Umbraco().WebRouting.DisableRedirectUrlTracking == false; var userIsAdmin = Umbraco.UmbracoContext.Security.CurrentUser.IsAdmin(); return Ok(new { enabled, userIsAdmin }); } diff --git a/src/Umbraco.Web/Editors/TourController.cs b/src/Umbraco.Web/Editors/TourController.cs index b45c233aec..81fa930c41 100644 --- a/src/Umbraco.Web/Editors/TourController.cs +++ b/src/Umbraco.Web/Editors/TourController.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; using Newtonsoft.Json; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.IO; using Umbraco.Web.Models; @@ -25,7 +26,7 @@ namespace Umbraco.Web.Editors { var result = new List(); - if (UmbracoConfig.For.UmbracoSettings().BackOffice.Tours.EnableTours == false) + if (Current.Config.Umbraco().BackOffice.Tours.EnableTours == false) return result; //get all filters that will be applied to all tour aliases diff --git a/src/Umbraco.Web/Editors/UpdateCheckController.cs b/src/Umbraco.Web/Editors/UpdateCheckController.cs index 8960d2ab89..64c6aa30aa 100644 --- a/src/Umbraco.Web/Editors/UpdateCheckController.cs +++ b/src/Umbraco.Web/Editors/UpdateCheckController.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http.Filters; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Models; using Umbraco.Web.Models; @@ -58,9 +59,9 @@ namespace Umbraco.Web.Editors var cookie = new CookieHeaderValue("UMB_UPDCHK", "1") { Path = "/", - Expires = DateTimeOffset.Now.AddDays(UmbracoConfig.For.GlobalSettings().VersionCheckPeriod), + Expires = DateTimeOffset.Now.AddDays(Current.Config.Global().VersionCheckPeriod), HttpOnly = true, - Secure = UmbracoConfig.For.GlobalSettings().UseHttps + Secure = Current.Config.Global().UseHttps }; context.Response.Headers.AddCookies(new[] { cookie }); } diff --git a/src/Umbraco.Web/Editors/UsersController.cs b/src/Umbraco.Web/Editors/UsersController.cs index dc5d45799f..9f30b01467 100644 --- a/src/Umbraco.Web/Editors/UsersController.cs +++ b/src/Umbraco.Web/Editors/UsersController.cs @@ -98,7 +98,7 @@ namespace Umbraco.Web.Editors var safeFileName = fileName.ToSafeFileName(); var ext = safeFileName.Substring(safeFileName.LastIndexOf('.') + 1).ToLower(); - if (UmbracoConfig.For.UmbracoSettings().Content.DisallowedUploadFiles.Contains(ext) == false) + if (Current.Config.Umbraco().Content.DisallowedUploadFiles.Contains(ext) == false) { //generate a path of known data, we don't want this path to be guessable user.Avatar = "UserAvatars/" + (user.Id + safeFileName).ToSHA1() + "." + ext; @@ -195,7 +195,7 @@ namespace Umbraco.Web.Editors // so to do that here, we'll need to check if this current user is an admin and if not we should exclude all user who are // also admins - var hideDisabledUsers = UmbracoConfig.For.UmbracoSettings().Security.HideDisabledUsersInBackoffice; + var hideDisabledUsers = Current.Config.Umbraco().Security.HideDisabledUsersInBackoffice; var excludeUserGroups = new string[0]; var isAdmin = Security.CurrentUser.IsAdmin(); if (isAdmin == false) @@ -253,7 +253,7 @@ namespace Umbraco.Web.Editors throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } - if (UmbracoConfig.For.UmbracoSettings().Security.UsernameIsEmail) + if (Current.Config.Umbraco().Security.UsernameIsEmail) { //ensure they are the same if we're using it userSave.Username = userSave.Email; @@ -345,7 +345,7 @@ namespace Umbraco.Web.Editors } IUser user; - if (UmbracoConfig.For.UmbracoSettings().Security.UsernameIsEmail) + if (Current.Config.Umbraco().Security.UsernameIsEmail) { //ensure it's the same userSave.Username = userSave.Email; @@ -419,7 +419,7 @@ namespace Umbraco.Web.Editors if (user != null && (extraCheck == null || extraCheck(user))) { ModelState.AddModelError( - UmbracoConfig.For.UmbracoSettings().Security.UsernameIsEmail ? "Email" : "Username", + Current.Config.Umbraco().Security.UsernameIsEmail ? "Email" : "Username", "A user with the username already exists"); throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } @@ -539,7 +539,7 @@ namespace Umbraco.Web.Editors // if the found user has his email for username, we want to keep this synced when changing the email. // we have already cross-checked above that the email isn't colliding with anything, so we can safely assign it here. - if (UmbracoConfig.For.UmbracoSettings().Security.UsernameIsEmail && found.Username == found.Email && userSave.Username != userSave.Email) + if (Current.Config.Umbraco().Security.UsernameIsEmail && found.Username == found.Email && userSave.Username != userSave.Email) { userSave.Username = userSave.Email; } @@ -552,7 +552,7 @@ namespace Umbraco.Web.Editors var passwordChangeResult = await passwordChanger.ChangePasswordWithIdentityAsync(Security.CurrentUser, found, userSave.ChangePassword, UserManager); if (passwordChangeResult.Success) { - //need to re-get the user + //need to re-get the user found = Services.UserService.GetUserById(intId.Result); } else @@ -712,7 +712,7 @@ namespace Umbraco.Web.Editors var userName = user.Name; Services.UserService.Delete(user, true); - + return Request.CreateNotificationSuccessResponse( Services.TextService.Localize("speechBubbles/deleteUserSuccess", new[] { userName })); } diff --git a/src/Umbraco.Web/HealthCheck/HealthCheckController.cs b/src/Umbraco.Web/HealthCheck/HealthCheckController.cs index fe68c5b01d..5df534232c 100644 --- a/src/Umbraco.Web/HealthCheck/HealthCheckController.cs +++ b/src/Umbraco.Web/HealthCheck/HealthCheckController.cs @@ -4,6 +4,7 @@ using System.ComponentModel; using System.Configuration; using System.Linq; using System.Web.Http; +using Umbraco.Core.Composing; using Umbraco.Core.Logging; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.HealthChecks; @@ -27,7 +28,7 @@ namespace Umbraco.Web.HealthCheck _checks = checks ?? throw new ArgumentNullException(nameof(checks)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); - var healthCheckConfig = UmbracoConfig.For.HealthCheck(); + var healthCheckConfig = Current.Config.HealthChecks(); _disabledCheckIds = healthCheckConfig.DisabledChecks .Select(x => x.Id) .ToList(); diff --git a/src/Umbraco.Web/HealthCheck/NotificationMethods/EmailNotificationMethod.cs b/src/Umbraco.Web/HealthCheck/NotificationMethods/EmailNotificationMethod.cs index b697c87335..6b1091a0c3 100644 --- a/src/Umbraco.Web/HealthCheck/NotificationMethods/EmailNotificationMethod.cs +++ b/src/Umbraco.Web/HealthCheck/NotificationMethods/EmailNotificationMethod.cs @@ -4,6 +4,7 @@ using System.Net.Mail; using System.Threading; using System.Threading.Tasks; using Umbraco.Core; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using Umbraco.Core.Services; @@ -69,7 +70,7 @@ namespace Umbraco.Web.HealthCheck.NotificationMethods private MailMessage CreateMailMessage(string subject, string message) { - var to = UmbracoConfig.For.UmbracoSettings().Content.NotificationEmailAddress; + var to = Current.Config.Umbraco().Content.NotificationEmailAddress; if (string.IsNullOrWhiteSpace(subject)) subject = "Umbraco Health Check Status"; diff --git a/src/Umbraco.Web/HealthCheck/NotificationMethods/NotificationMethodBase.cs b/src/Umbraco.Web/HealthCheck/NotificationMethods/NotificationMethodBase.cs index f35df0062e..88caff1da7 100644 --- a/src/Umbraco.Web/HealthCheck/NotificationMethods/NotificationMethodBase.cs +++ b/src/Umbraco.Web/HealthCheck/NotificationMethods/NotificationMethodBase.cs @@ -2,6 +2,7 @@ using System.Reflection; using System.Threading; using System.Threading.Tasks; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.HealthChecks; @@ -19,7 +20,7 @@ namespace Umbraco.Web.HealthCheck.NotificationMethods return; } - var healthCheckConfig = UmbracoConfig.For.HealthCheck(); + var healthCheckConfig = Current.Config.HealthChecks(); var notificationMethods = healthCheckConfig.NotificationSettings.NotificationMethods; var notificationMethod = notificationMethods[attribute.Alias]; if (notificationMethod == null) diff --git a/src/Umbraco.Web/HtmlHelperRenderExtensions.cs b/src/Umbraco.Web/HtmlHelperRenderExtensions.cs index 4504c22161..5a7c4e9b15 100644 --- a/src/Umbraco.Web/HtmlHelperRenderExtensions.cs +++ b/src/Umbraco.Web/HtmlHelperRenderExtensions.cs @@ -64,7 +64,7 @@ namespace Umbraco.Web if (UmbracoContext.Current.InPreviewMode) { var htmlBadge = - String.Format(UmbracoConfig.For.UmbracoSettings().Content.PreviewBadge, + String.Format(Current.Config.Umbraco().Content.PreviewBadge, IOHelper.ResolveUrl(SystemDirectories.Umbraco), UmbracoContext.Current.HttpContext.Server.UrlEncode(UmbracoContext.Current.HttpContext.Request.Path)); return new MvcHtmlString(htmlBadge); diff --git a/src/Umbraco.Web/Install/InstallSteps/NewInstallStep.cs b/src/Umbraco.Web/Install/InstallSteps/NewInstallStep.cs index 0b225e158b..10a84b9350 100644 --- a/src/Umbraco.Web/Install/InstallSteps/NewInstallStep.cs +++ b/src/Umbraco.Web/Install/InstallSteps/NewInstallStep.cs @@ -8,6 +8,7 @@ using System.Web; using System.Web.Security; using Newtonsoft.Json; using Umbraco.Core; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Migrations.Install; using Umbraco.Core.Services; @@ -82,7 +83,7 @@ namespace Umbraco.Web.Install.InstallSteps admin.Username = user.Email.Trim(); _userService.Save(admin); - + if (user.SubscribeToNewsLetter) { if (_httpClient == null) @@ -144,7 +145,7 @@ namespace Umbraco.Web.Install.InstallSteps // In this one case when it's a brand new install and nothing has been configured, make sure the // back office cookie is cleared so there's no old cookies lying around causing problems - _http.ExpireCookie(UmbracoConfig.For.UmbracoSettings().Security.AuthCookieName); + _http.ExpireCookie(Current.Config.Umbraco().Security.AuthCookieName); return true; } diff --git a/src/Umbraco.Web/Macros/MacroRenderer.cs b/src/Umbraco.Web/Macros/MacroRenderer.cs index 3cc890c67a..d3c646465c 100755 --- a/src/Umbraco.Web/Macros/MacroRenderer.cs +++ b/src/Umbraco.Web/Macros/MacroRenderer.cs @@ -312,7 +312,7 @@ namespace Umbraco.Web.Macros Alias = macro.Alias, MacroSource = macro.MacroSource, Exception = e, - Behaviour = UmbracoConfig.For.UmbracoSettings().Content.MacroErrorBehaviour + Behaviour = Current.Config.Umbraco().Content.MacroErrorBehaviour }; OnError(macroErrorEventArgs); @@ -604,7 +604,7 @@ namespace Umbraco.Web.Macros querystring += $"&umb_{ide.Key}={HttpContext.Current.Server.UrlEncode((ide.Value ?? String.Empty).ToString())}"; // create a new 'HttpWebRequest' object to the mentioned URL. - var useSsl = UmbracoConfig.For.GlobalSettings().UseHttps; + var useSsl = Current.Config.Global().UseHttps; var protocol = useSsl ? "https" : "http"; var currentRequest = HttpContext.Current.Request; var serverVars = currentRequest.ServerVariables; @@ -619,7 +619,7 @@ namespace Umbraco.Web.Macros // propagate the user's context // TODO: this is the worst thing ever. // also will not work if people decide to put their own custom auth system in place. - var inCookie = currentRequest.Cookies[UmbracoConfig.For.UmbracoSettings().Security.AuthCookieName]; + var inCookie = currentRequest.Cookies[Current.Config.Umbraco().Security.AuthCookieName]; if (inCookie == null) throw new NullReferenceException("No auth cookie found"); var cookie = new Cookie(inCookie.Name, inCookie.Value, inCookie.Path, serverVars["SERVER_NAME"]); myHttpWebRequest.CookieContainer = new CookieContainer(); diff --git a/src/Umbraco.Web/Models/ContentEditing/ContentTypeBasic.cs b/src/Umbraco.Web/Models/ContentEditing/ContentTypeBasic.cs index ba6fca5fd7..f19753b1d8 100644 --- a/src/Umbraco.Web/Models/ContentEditing/ContentTypeBasic.cs +++ b/src/Umbraco.Web/Models/ContentEditing/ContentTypeBasic.cs @@ -4,6 +4,7 @@ using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using Umbraco.Core; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.IO; using Umbraco.Core.Models.Validation; @@ -75,7 +76,7 @@ namespace Umbraco.Web.Models.ContentEditing { return IconIsClass ? string.Empty - : string.Format("{0}images/umbraco/{1}", UmbracoConfig.For.GlobalSettings().Path.EnsureEndsWith("/"), Icon); + : string.Format("{0}images/umbraco/{1}", Current.Config.Global().Path.EnsureEndsWith("/"), Icon); } } diff --git a/src/Umbraco.Web/Models/ContentEditing/UserInvite.cs b/src/Umbraco.Web/Models/ContentEditing/UserInvite.cs index cb85f0f3db..893a3d8020 100644 --- a/src/Umbraco.Web/Models/ContentEditing/UserInvite.cs +++ b/src/Umbraco.Web/Models/ContentEditing/UserInvite.cs @@ -3,6 +3,7 @@ using System.ComponentModel.DataAnnotations; using System.Linq; using System.Runtime.Serialization; using Umbraco.Core; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; namespace Umbraco.Web.Models.ContentEditing @@ -33,7 +34,7 @@ namespace Umbraco.Web.Models.ContentEditing if (UserGroups.Any() == false) yield return new ValidationResult("A user must be assigned to at least one group", new[] { "UserGroups" }); - if (UmbracoConfig.For.UmbracoSettings().Security.UsernameIsEmail == false && Username.IsNullOrWhiteSpace()) + if (Current.Config.Umbraco().Security.UsernameIsEmail == false && Username.IsNullOrWhiteSpace()) yield return new ValidationResult("A username cannot be empty", new[] { "Username" }); } } diff --git a/src/Umbraco.Web/Models/Mapping/DataTypeMapperProfile.cs b/src/Umbraco.Web/Models/Mapping/DataTypeMapperProfile.cs index b74d563e88..d9330ac610 100644 --- a/src/Umbraco.Web/Models/Mapping/DataTypeMapperProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/DataTypeMapperProfile.cs @@ -20,7 +20,7 @@ namespace Umbraco.Web.Models.Mapping public DataTypeMapperProfile(PropertyEditorCollection propertyEditors, ILogger logger) { // create, capture, cache - var availablePropertyEditorsResolver = new AvailablePropertyEditorsResolver(UmbracoConfig.For.UmbracoSettings().Content); + var availablePropertyEditorsResolver = new AvailablePropertyEditorsResolver(Current.Config.Umbraco().Content); var configurationDisplayResolver = new DataTypeConfigurationFieldDisplayResolver(logger); var databaseTypeResolver = new DatabaseTypeResolver(); diff --git a/src/Umbraco.Web/Models/Mapping/MediaMapperProfile.cs b/src/Umbraco.Web/Models/Mapping/MediaMapperProfile.cs index dc16ed5fe4..dc0aa16b74 100644 --- a/src/Umbraco.Web/Models/Mapping/MediaMapperProfile.cs +++ b/src/Umbraco.Web/Models/Mapping/MediaMapperProfile.cs @@ -1,5 +1,6 @@ using AutoMapper; using Umbraco.Core; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using Umbraco.Core.Models; @@ -52,7 +53,7 @@ namespace Umbraco.Web.Models.Mapping .ForMember(dest => dest.Tabs, opt => opt.ResolveUsing(tabsAndPropertiesResolver)) .ForMember(dest => dest.AdditionalData, opt => opt.Ignore()) .ForMember(dest => dest.ContentType, opt => opt.ResolveUsing(mediaTypeBasicResolver)) - .ForMember(dest => dest.MediaLink, opt => opt.ResolveUsing(content => string.Join(",", content.GetUrls(UmbracoConfig.For.UmbracoSettings().Content, logger)))) + .ForMember(dest => dest.MediaLink, opt => opt.ResolveUsing(content => string.Join(",", content.GetUrls(Current.Config.Umbraco().Content, logger)))) .ForMember(dest => dest.ContentApps, opt => opt.ResolveUsing(mediaAppResolver)) .ForMember(dest => dest.VariesByCulture, opt => opt.MapFrom(src => src.ContentType.VariesByCulture())); diff --git a/src/Umbraco.Web/Models/Trees/TreeNode.cs b/src/Umbraco.Web/Models/Trees/TreeNode.cs index 01aa78ca36..cca2bf8091 100644 --- a/src/Umbraco.Web/Models/Trees/TreeNode.cs +++ b/src/Umbraco.Web/Models/Trees/TreeNode.cs @@ -2,6 +2,7 @@ using Umbraco.Core.IO; using System.Collections.Generic; using Umbraco.Core; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Exceptions; using Umbraco.Web.Models.ContentEditing; @@ -111,7 +112,7 @@ namespace Umbraco.Web.Models.Trees return IOHelper.ResolveUrl("~" + Icon.TrimStart('~')); //legacy icon path - return string.Format("{0}images/umbraco/{1}", UmbracoConfig.For.GlobalSettings().Path.EnsureEndsWith("/"), Icon); + return string.Format("{0}images/umbraco/{1}", Current.Config.Global().Path.EnsureEndsWith("/"), Icon); } } diff --git a/src/Umbraco.Web/Mvc/UmbracoAuthorizeAttribute.cs b/src/Umbraco.Web/Mvc/UmbracoAuthorizeAttribute.cs index 2930e0a9ba..205bb0926d 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 = UmbracoConfig.For.GlobalSettings().Path.EnsureStartsWith("~"); + _redirectUrl = Current.Config.Global().Path.EnsureStartsWith("~"); } } @@ -94,7 +94,7 @@ namespace Umbraco.Web.Mvc { filterContext.Result = (ActionResult)new HttpUnauthorizedResult("You must login to view this resource."); - + } else { diff --git a/src/Umbraco.Web/Mvc/UmbracoRequireHttpsAttribute.cs b/src/Umbraco.Web/Mvc/UmbracoRequireHttpsAttribute.cs index 589090c08e..502386e9cb 100644 --- a/src/Umbraco.Web/Mvc/UmbracoRequireHttpsAttribute.cs +++ b/src/Umbraco.Web/Mvc/UmbracoRequireHttpsAttribute.cs @@ -1,4 +1,5 @@ using System.Web.Mvc; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using GlobalSettings = Umbraco.Core.Configuration.GlobalSettings; @@ -16,7 +17,7 @@ namespace Umbraco.Web.Mvc protected override void HandleNonHttpsRequest(AuthorizationContext filterContext) { // If umbracoUseSSL is set, let base method handle redirect. Otherwise, we don't care. - if (UmbracoConfig.For.GlobalSettings().UseHttps) + if (Current.Config.Global().UseHttps) { base.HandleNonHttpsRequest(filterContext); } @@ -29,7 +30,7 @@ namespace Umbraco.Web.Mvc public override void OnAuthorization(AuthorizationContext filterContext) { // If umbracoSSL is set, let base method handle checking for HTTPS. Otherwise, we don't care. - if (UmbracoConfig.For.GlobalSettings().UseHttps) + if (Current.Config.Global().UseHttps) { base.OnAuthorization(filterContext); } diff --git a/src/Umbraco.Web/Mvc/UmbracoViewPageOfTModel.cs b/src/Umbraco.Web/Mvc/UmbracoViewPageOfTModel.cs index dd18483994..86277cd18d 100644 --- a/src/Umbraco.Web/Mvc/UmbracoViewPageOfTModel.cs +++ b/src/Umbraco.Web/Mvc/UmbracoViewPageOfTModel.cs @@ -216,7 +216,7 @@ namespace Umbraco.Web.Mvc { // creating previewBadge markup markupToInject = - string.Format(UmbracoConfig.For.UmbracoSettings().Content.PreviewBadge, + string.Format(Current.Config.Umbraco().Content.PreviewBadge, IOHelper.ResolveUrl(SystemDirectories.Umbraco), Server.UrlEncode(UmbracoContext.Current.HttpContext.Request.Path)); } diff --git a/src/Umbraco.Web/PropertyEditors/UploadFileTypeValidator.cs b/src/Umbraco.Web/PropertyEditors/UploadFileTypeValidator.cs index 9fd9c1ef0e..1bf3b82312 100644 --- a/src/Umbraco.Web/PropertyEditors/UploadFileTypeValidator.cs +++ b/src/Umbraco.Web/PropertyEditors/UploadFileTypeValidator.cs @@ -35,7 +35,7 @@ namespace Umbraco.Web.PropertyEditors { if (fileName.IndexOf('.') <= 0) return false; var extension = Path.GetExtension(fileName).TrimStart("."); - return UmbracoConfig.For.UmbracoSettings().Content.IsFileAllowedForUpload(extension); + return Current.Config.Umbraco().Content.IsFileAllowedForUpload(extension); } } } diff --git a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlStore.cs b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlStore.cs index 5b816c2f26..d459821b73 100644 --- a/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlStore.cs +++ b/src/Umbraco.Web/PublishedCache/XmlPublishedCache/XmlStore.cs @@ -110,7 +110,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache _mediaRepository = mediaRepository; _memberRepository = memberRepository; _xmlFileEnabled = false; - _xmlFileName = IOHelper.MapPath(SystemFiles.GetContentCacheXml(UmbracoConfig.For.GlobalSettings())); + _xmlFileName = IOHelper.MapPath(SystemFiles.GetContentCacheXml(Current.Config.Global())); // do not plug events, we may not have what it takes to handle them } @@ -124,7 +124,7 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache _memberRepository = memberRepository; GetXmlDocument = getXmlDocument ?? throw new ArgumentNullException(nameof(getXmlDocument)); _xmlFileEnabled = false; - _xmlFileName = IOHelper.MapPath(SystemFiles.GetContentCacheXml(UmbracoConfig.For.GlobalSettings())); + _xmlFileName = IOHelper.MapPath(SystemFiles.GetContentCacheXml(Current.Config.Global())); // do not plug events, we may not have what it takes to handle them } @@ -253,16 +253,16 @@ namespace Umbraco.Web.PublishedCache.XmlPublishedCache private readonly bool _xmlFileEnabled = true; // whether the disk cache is enabled - private bool XmlFileEnabled => _xmlFileEnabled && UmbracoConfig.For.UmbracoSettings().Content.XmlCacheEnabled; + private bool XmlFileEnabled => _xmlFileEnabled && Current.Config.Umbraco().Content.XmlCacheEnabled; // whether the disk cache is enabled and to update the disk cache when xml changes - private bool SyncToXmlFile => XmlFileEnabled && UmbracoConfig.For.UmbracoSettings().Content.ContinouslyUpdateXmlDiskCache; + private bool SyncToXmlFile => XmlFileEnabled && Current.Config.Umbraco().Content.ContinouslyUpdateXmlDiskCache; // whether the disk cache is enabled and to reload from disk cache if it changes - private bool SyncFromXmlFile => XmlFileEnabled && UmbracoConfig.For.UmbracoSettings().Content.XmlContentCheckForDiskChanges; + private bool SyncFromXmlFile => XmlFileEnabled && Current.Config.Umbraco().Content.XmlContentCheckForDiskChanges; // whether _xml is immutable or not (achieved by cloning before changing anything) - private static bool XmlIsImmutable => UmbracoConfig.For.UmbracoSettings().Content.CloneXmlContent; + private static bool XmlIsImmutable => Current.Config.Umbraco().Content.CloneXmlContent; // whether to keep version of everything (incl. medias & members) in cmsPreviewXml // for audit purposes - false by default, not in umbracoSettings.config @@ -1241,7 +1241,7 @@ ORDER BY umbracoNode.level, umbracoNode.sortOrder"; // the types will be reloaded if/when needed foreach (var payload in payloads) _contentTypeCache.ClearDataType(payload.Id); - + foreach (var payload in payloads) Current.Logger.Debug("Notified {RemovedStatus} for data type {payload.Id}", payload.Removed ? "Removed" : "Refreshed", diff --git a/src/Umbraco.Web/PublishedContentExtensions.cs b/src/Umbraco.Web/PublishedContentExtensions.cs index 2bc0d7be3f..9d9dbaae6d 100644 --- a/src/Umbraco.Web/PublishedContentExtensions.cs +++ b/src/Umbraco.Web/PublishedContentExtensions.cs @@ -87,10 +87,10 @@ namespace Umbraco.Web public static bool IsAllowedTemplate(this IPublishedContent content, int templateId) { - if (UmbracoConfig.For.UmbracoSettings().WebRouting.DisableAlternativeTemplates == true) + if (Current.Config.Umbraco().WebRouting.DisableAlternativeTemplates == true) return content.TemplateId == templateId; - if (content.TemplateId != templateId && UmbracoConfig.For.UmbracoSettings().WebRouting.ValidateAlternativeTemplates == true) + if (content.TemplateId != templateId && Current.Config.Umbraco().WebRouting.ValidateAlternativeTemplates == true) { // fixme - perfs? nothing cached here var publishedContentContentType = Current.Services.ContentTypeService.Get(content.ContentType.Id); diff --git a/src/Umbraco.Web/Routing/PublishedRequest.cs b/src/Umbraco.Web/Routing/PublishedRequest.cs index 078aef8a54..6660720502 100644 --- a/src/Umbraco.Web/Routing/PublishedRequest.cs +++ b/src/Umbraco.Web/Routing/PublishedRequest.cs @@ -4,6 +4,7 @@ using System.Globalization; using System.Threading; using System.Web; using umbraco; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; @@ -180,7 +181,7 @@ namespace Umbraco.Web.Routing IsInternalRedirectPublishedContent = isInternalRedirect; // must restore the template if it's an internal redirect & the config option is set - if (isInternalRedirect && UmbracoConfig.For.UmbracoSettings().WebRouting.InternalRedirectPreservesTemplate) + if (isInternalRedirect && Current.Config.Umbraco().WebRouting.InternalRedirectPreservesTemplate) { // restore _template = template; diff --git a/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs b/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs index 35e51cca84..b07fb999b9 100644 --- a/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs +++ b/src/Umbraco.Web/Runtime/WebRuntimeComponent.cs @@ -196,7 +196,7 @@ namespace Umbraco.Web.Runtime // register published router composition.RegisterUnique(); - composition.Register(_ => UmbracoConfig.For.UmbracoSettings().WebRouting); + composition.Register(_ => Current.Config.Umbraco().WebRouting); // register preview SignalR hub composition.RegisterUnique(_ => GlobalHost.ConnectionManager.GetHubContext()); diff --git a/src/Umbraco.Web/Scheduling/HealthCheckNotifier.cs b/src/Umbraco.Web/Scheduling/HealthCheckNotifier.cs index 163549d6c7..37373d0e04 100644 --- a/src/Umbraco.Web/Scheduling/HealthCheckNotifier.cs +++ b/src/Umbraco.Web/Scheduling/HealthCheckNotifier.cs @@ -2,6 +2,7 @@ using System.Threading; using System.Threading.Tasks; using Umbraco.Core; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Logging; using Umbraco.Core.Sync; @@ -54,7 +55,7 @@ namespace Umbraco.Web.Scheduling using (_proflog.DebugDuration("Health checks executing", "Health checks complete")) { - var healthCheckConfig = UmbracoConfig.For.HealthCheck(); + var healthCheckConfig = Current.Config.HealthChecks(); // Don't notify for any checks that are disabled, nor for any disabled // just for notifications diff --git a/src/Umbraco.Web/Scheduling/SchedulerComponent.cs b/src/Umbraco.Web/Scheduling/SchedulerComponent.cs index a9e8016485..67214fdb54 100644 --- a/src/Umbraco.Web/Scheduling/SchedulerComponent.cs +++ b/src/Umbraco.Web/Scheduling/SchedulerComponent.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Threading; using Umbraco.Core; using Umbraco.Core.Components; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Configuration.HealthChecks; using Umbraco.Core.Configuration.UmbracoSettings; @@ -86,7 +87,7 @@ namespace Umbraco.Web.Scheduling LazyInitializer.EnsureInitialized(ref _tasks, ref _started, ref _locker, () => { _logger.Debug("Initializing the scheduler"); - var settings = UmbracoConfig.For.UmbracoSettings(); + var settings = Current.Config.Umbraco(); var tasks = new List(); @@ -95,7 +96,7 @@ namespace Umbraco.Web.Scheduling tasks.Add(RegisterTaskRunner(settings)); tasks.Add(RegisterLogScrubber(settings)); - var healthCheckConfig = UmbracoConfig.For.HealthCheck(); + var healthCheckConfig = Current.Config.HealthChecks(); if (healthCheckConfig.NotificationSettings.Enabled) tasks.Add(RegisterHealthCheckNotifier(healthCheckConfig, _healthChecks, _notifications, _logger, _proflog)); diff --git a/src/Umbraco.Web/Security/AppBuilderExtensions.cs b/src/Umbraco.Web/Security/AppBuilderExtensions.cs index ddcf87e9c7..84636e74cc 100644 --- a/src/Umbraco.Web/Security/AppBuilderExtensions.cs +++ b/src/Umbraco.Web/Security/AppBuilderExtensions.cs @@ -211,8 +211,8 @@ namespace Umbraco.Web.Security //This is a custom middleware, we need to return the user's remaining logged in seconds app.Use( cookieAuthOptions, - UmbracoConfig.For.GlobalSettings(), - UmbracoConfig.For.UmbracoSettings().Security, + Current.Config.Global(), + Current.Config.Umbraco().Security, app.CreateLogger()); //This is required so that we can read the auth ticket format outside of this pipeline @@ -316,7 +316,7 @@ namespace Umbraco.Web.Security CookiePath = "/", CookieSecure = globalSettings.UseHttps ? CookieSecureOption.Always : CookieSecureOption.SameAsRequest, CookieHttpOnly = true, - CookieDomain = UmbracoConfig.For.UmbracoSettings().Security.AuthCookieDomain + CookieDomain = Current.Config.Umbraco().Security.AuthCookieDomain }, stage); return app; @@ -362,7 +362,7 @@ namespace Umbraco.Web.Security if (runtimeState.Level != RuntimeLevel.Run) return app; var authOptions = app.CreateUmbracoCookieAuthOptions(umbracoContextAccessor, globalSettings, runtimeState, securitySettings); - app.Use(typeof(PreviewAuthenticationMiddleware), authOptions, UmbracoConfig.For.GlobalSettings()); + app.Use(typeof(PreviewAuthenticationMiddleware), authOptions, Current.Config.Global()); // 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, @@ -391,7 +391,7 @@ namespace Umbraco.Web.Security /// /// public static UmbracoBackOfficeCookieAuthOptions CreateUmbracoCookieAuthOptions(this IAppBuilder app, - IUmbracoContextAccessor umbracoContextAccessor, + IUmbracoContextAccessor umbracoContextAccessor, IGlobalSettings globalSettings, IRuntimeState runtimeState, ISecuritySection securitySettings, string[] explicitPaths = null) { //this is how aspnet wires up the default AuthenticationTicket protector so we'll use the same code diff --git a/src/Umbraco.Web/Security/AuthenticationExtensions.cs b/src/Umbraco.Web/Security/AuthenticationExtensions.cs index 691d577d51..b5246051f8 100644 --- a/src/Umbraco.Web/Security/AuthenticationExtensions.cs +++ b/src/Umbraco.Web/Security/AuthenticationExtensions.cs @@ -145,7 +145,7 @@ namespace Umbraco.Web.Security public static void UmbracoLogout(this HttpContextBase http) { if (http == null) throw new ArgumentNullException("http"); - Logout(http, UmbracoConfig.For.UmbracoSettings().Security.AuthCookieName); + Logout(http, Current.Config.Umbraco().Security.AuthCookieName); } /// @@ -181,7 +181,7 @@ namespace Umbraco.Web.Security http.Items[Constants.Security.ForceReAuthFlag] = true; return true; } - + /// /// returns the number of seconds the user has until their auth session times out /// @@ -193,7 +193,7 @@ namespace Umbraco.Web.Security var ticket = http.GetUmbracoAuthTicket(); return ticket.GetRemainingAuthSeconds(); } - + /// /// returns the number of seconds the user has until their auth session times out /// @@ -215,7 +215,7 @@ namespace Umbraco.Web.Security public static AuthenticationTicket GetUmbracoAuthTicket(this HttpContextBase http) { if (http == null) throw new ArgumentNullException(nameof(http)); - return GetAuthTicket(http, UmbracoConfig.For.UmbracoSettings().Security.AuthCookieName); + return GetAuthTicket(http, Current.Config.Umbraco().Security.AuthCookieName); } internal static AuthenticationTicket GetUmbracoAuthTicket(this HttpContext http) @@ -227,7 +227,7 @@ namespace Umbraco.Web.Security public static AuthenticationTicket GetUmbracoAuthTicket(this IOwinContext ctx) { if (ctx == null) throw new ArgumentNullException(nameof(ctx)); - return GetAuthTicket(ctx, UmbracoConfig.For.UmbracoSettings().Security.AuthCookieName); + return GetAuthTicket(ctx, Current.Config.Umbraco().Security.AuthCookieName); } /// @@ -342,7 +342,7 @@ namespace Umbraco.Web.Security return null; } //get the ticket - + return secureDataFormat.Unprotect(formsCookie); } } diff --git a/src/Umbraco.Web/Security/BackOfficeCookieAuthenticationProvider.cs b/src/Umbraco.Web/Security/BackOfficeCookieAuthenticationProvider.cs index e12e2ac4f8..4c3df092b8 100644 --- a/src/Umbraco.Web/Security/BackOfficeCookieAuthenticationProvider.cs +++ b/src/Umbraco.Web/Security/BackOfficeCookieAuthenticationProvider.cs @@ -21,7 +21,7 @@ namespace Umbraco.Web.Security private readonly IUserService _userService; private readonly IRuntimeState _runtimeState; private readonly IGlobalSettings _globalSettings; - + public BackOfficeCookieAuthenticationProvider(IUserService userService, IRuntimeState runtimeState, IGlobalSettings globalSettings) { _userService = userService; @@ -67,7 +67,7 @@ namespace Umbraco.Web.Security Expires = DateTime.Now.AddYears(-1), Path = "/" }); - context.Response.Cookies.Append(UmbracoConfig.For.UmbracoSettings().Security.AuthCookieName, "", new CookieOptions + context.Response.Cookies.Append(Current.Config.Umbraco().Security.AuthCookieName, "", new CookieOptions { Expires = DateTime.Now.AddYears(-1), Path = "/" @@ -111,8 +111,8 @@ namespace Umbraco.Web.Security await SessionIdValidator.ValidateSessionAsync(TimeSpan.FromMinutes(1), context, _globalSettings); } - - + + } } diff --git a/src/Umbraco.Web/Security/ExternalSignInAutoLinkOptions.cs b/src/Umbraco.Web/Security/ExternalSignInAutoLinkOptions.cs index a143233ff2..fffa2ed30e 100644 --- a/src/Umbraco.Web/Security/ExternalSignInAutoLinkOptions.cs +++ b/src/Umbraco.Web/Security/ExternalSignInAutoLinkOptions.cs @@ -1,5 +1,6 @@ using System; using Microsoft.AspNet.Identity.Owin; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Models.Identity; @@ -23,7 +24,7 @@ namespace Umbraco.Web.Security { _defaultUserGroups = defaultUserGroups ?? new[] { "editor" }; _autoLinkExternalAccount = autoLinkExternalAccount; - _defaultCulture = defaultCulture ?? UmbracoConfig.For.GlobalSettings().DefaultUILanguage; + _defaultCulture = defaultCulture ?? Current.Config.Global().DefaultUILanguage; } private readonly string[] _defaultUserGroups; diff --git a/src/Umbraco.Web/Security/Providers/UsersMembershipProvider.cs b/src/Umbraco.Web/Security/Providers/UsersMembershipProvider.cs index 5af71f1bdd..c5403f10d7 100644 --- a/src/Umbraco.Web/Security/Providers/UsersMembershipProvider.cs +++ b/src/Umbraco.Web/Security/Providers/UsersMembershipProvider.cs @@ -38,7 +38,7 @@ namespace Umbraco.Web.Security.Providers public override string ProviderName { - get { return UmbracoConfig.For.UmbracoSettings().Providers.DefaultBackOfficeUserProvider; } + get { return Current.Config.Umbraco().Providers.DefaultBackOfficeUserProvider; } } protected override MembershipUser ConvertToMembershipUser(IUser entity) diff --git a/src/Umbraco.Web/Templates/TemplateRenderer.cs b/src/Umbraco.Web/Templates/TemplateRenderer.cs index 0f5e486a50..b0f4c6efc3 100644 --- a/src/Umbraco.Web/Templates/TemplateRenderer.cs +++ b/src/Umbraco.Web/Templates/TemplateRenderer.cs @@ -86,7 +86,7 @@ namespace Umbraco.Web.Templates //set the doc that was found by id contentRequest.PublishedContent = doc; //set the template, either based on the AltTemplate found or the standard template of the doc - contentRequest.TemplateModel = UmbracoConfig.For.UmbracoSettings().WebRouting.DisableAlternativeTemplates || AltTemplate.HasValue == false + contentRequest.TemplateModel = Current.Config.Umbraco().WebRouting.DisableAlternativeTemplates || AltTemplate.HasValue == false ? FileService.GetTemplate(doc.TemplateId) : FileService.GetTemplate(AltTemplate.Value); diff --git a/src/Umbraco.Web/Templates/TemplateUtilities.cs b/src/Umbraco.Web/Templates/TemplateUtilities.cs index 91548e44f1..4b13da15af 100644 --- a/src/Umbraco.Web/Templates/TemplateUtilities.cs +++ b/src/Umbraco.Web/Templates/TemplateUtilities.cs @@ -86,7 +86,7 @@ namespace Umbraco.Web.Templates /// public static string ResolveUrlsFromTextString(string text) { - if (UmbracoConfig.For.UmbracoSettings().Content.ResolveUrlsFromTextString == false) return text; + if (Current.Config.Umbraco().Content.ResolveUrlsFromTextString == false) return text; using (var timer = Current.ProfilingLogger.DebugDuration(typeof(IOHelper), "ResolveUrlsFromTextString starting", "ResolveUrlsFromTextString complete")) { diff --git a/src/Umbraco.Web/Trees/ContentTypeTreeController.cs b/src/Umbraco.Web/Trees/ContentTypeTreeController.cs index 0ef3c073eb..5a9ee32e63 100644 --- a/src/Umbraco.Web/Trees/ContentTypeTreeController.cs +++ b/src/Umbraco.Web/Trees/ContentTypeTreeController.cs @@ -4,6 +4,7 @@ using System.Collections.Generic; using System.Linq; using System.Net.Http.Formatting; using Umbraco.Core; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Models; using Umbraco.Core.Services; @@ -73,7 +74,7 @@ namespace Umbraco.Web.Trees { var menu = new MenuItemCollection(); - var enableInheritedDocumentTypes = UmbracoConfig.For.UmbracoSettings().Content.EnableInheritedDocumentTypes; + var enableInheritedDocumentTypes = Current.Config.Umbraco().Content.EnableInheritedDocumentTypes; if (id == Constants.System.Root.ToInvariantString()) { diff --git a/src/Umbraco.Web/Trees/LegacyTreeDataConverter.cs b/src/Umbraco.Web/Trees/LegacyTreeDataConverter.cs index 85cebdf3f5..058df58c17 100644 --- a/src/Umbraco.Web/Trees/LegacyTreeDataConverter.cs +++ b/src/Umbraco.Web/Trees/LegacyTreeDataConverter.cs @@ -31,7 +31,7 @@ namespace Umbraco.Web.Trees { case ActionDelete actionDelete: return Attempt.Succeed( - UmbracoConfig.For.GlobalSettings().Path.EnsureEndsWith('/') + "views/common/dialogs/legacydelete.html"); + Current.Config.Global().Path.EnsureEndsWith('/') + "views/common/dialogs/legacydelete.html"); } return Attempt.Fail(); diff --git a/src/Umbraco.Web/Trees/MediaTypeTreeController.cs b/src/Umbraco.Web/Trees/MediaTypeTreeController.cs index 8b3ad5e8cd..1ba78d7dbf 100644 --- a/src/Umbraco.Web/Trees/MediaTypeTreeController.cs +++ b/src/Umbraco.Web/Trees/MediaTypeTreeController.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Net.Http.Formatting; using AutoMapper; using Umbraco.Core; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; using Umbraco.Core.Models; using Umbraco.Web.Models.Trees; @@ -66,7 +67,7 @@ namespace Umbraco.Web.Trees { var menu = new MenuItemCollection(); - var enableInheritedMediaTypes = UmbracoConfig.For.UmbracoSettings().Content.EnableInheritedMediaTypes; + var enableInheritedMediaTypes = Current.Config.Umbraco().Content.EnableInheritedMediaTypes; if (id == Constants.System.Root.ToInvariantString()) { diff --git a/src/Umbraco.Web/UI/Pages/BasePage.cs b/src/Umbraco.Web/UI/Pages/BasePage.cs index 5974dfcbe8..089f98d874 100644 --- a/src/Umbraco.Web/UI/Pages/BasePage.cs +++ b/src/Umbraco.Web/UI/Pages/BasePage.cs @@ -72,7 +72,7 @@ namespace Umbraco.Web.UI.Pages { base.OnLoad(e); - if (Request.IsSecureConnection || UmbracoConfig.For.GlobalSettings().UseHttps == false) return; + if (Request.IsSecureConnection || Current.Config.Global().UseHttps == false) return; var serverName = HttpUtility.UrlEncode(Request.ServerVariables["SERVER_NAME"]); Response.Redirect($"https://{serverName}{Request.FilePath}"); diff --git a/src/Umbraco.Web/UI/Pages/UmbracoEnsuredPage.cs b/src/Umbraco.Web/UI/Pages/UmbracoEnsuredPage.cs index f2edcaea35..27b92488db 100644 --- a/src/Umbraco.Web/UI/Pages/UmbracoEnsuredPage.cs +++ b/src/Umbraco.Web/UI/Pages/UmbracoEnsuredPage.cs @@ -90,7 +90,7 @@ namespace Umbraco.Web.UI.Pages //If this is not a back office request, then the module won't have authenticated it, in this case we // need to do the auth manually and since this is an UmbracoEnsuredPage, this is the anticipated behavior // TODO: When we implement Identity, this process might not work anymore, will be an interesting challenge - if (Context.Request.Url.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath, UmbracoConfig.For.GlobalSettings()) == false) + if (Context.Request.Url.IsBackOfficeRequest(HttpRuntime.AppDomainAppVirtualPath, Current.Config.Global()) == false) { var http = new HttpContextWrapper(Context); var ticket = http.GetUmbracoAuthTicket(); diff --git a/src/Umbraco.Web/UmbracoContext.cs b/src/Umbraco.Web/UmbracoContext.cs index 57f2adbaa4..8ba595a6b5 100644 --- a/src/Umbraco.Web/UmbracoContext.cs +++ b/src/Umbraco.Web/UmbracoContext.cs @@ -111,10 +111,10 @@ namespace Umbraco.Web Composing.Current.UmbracoContextAccessor, httpContext, Composing.Current.PublishedSnapshotService, - new WebSecurity(httpContext, Composing.Current.Services.UserService, UmbracoConfig.For.GlobalSettings()), - UmbracoConfig.For.UmbracoSettings(), + new WebSecurity(httpContext, Composing.Current.Services.UserService, Composing.Current.Config.Global()), + Composing.Current.Config.Umbraco(), Composing.Current.UrlProviders, - UmbracoConfig.For.GlobalSettings(), + Composing.Current.Config.Global(), Composing.Current.Factory.GetInstance(), true); diff --git a/src/Umbraco.Web/UmbracoDefaultOwinStartup.cs b/src/Umbraco.Web/UmbracoDefaultOwinStartup.cs index 6d8df48adc..de6192acb3 100644 --- a/src/Umbraco.Web/UmbracoDefaultOwinStartup.cs +++ b/src/Umbraco.Web/UmbracoDefaultOwinStartup.cs @@ -24,8 +24,8 @@ namespace Umbraco.Web public class UmbracoDefaultOwinStartup { protected IUmbracoContextAccessor UmbracoContextAccessor => Current.UmbracoContextAccessor; - protected IGlobalSettings GlobalSettings => UmbracoConfig.For.GlobalSettings(); - protected IUmbracoSettingsSection UmbracoSettings => UmbracoConfig.For.UmbracoSettings(); + protected IGlobalSettings GlobalSettings => Current.Config.Global(); + protected IUmbracoSettingsSection UmbracoSettings => Current.Config.Umbraco(); protected IRuntimeState RuntimeState => Core.Composing.Current.RuntimeState; protected ServiceContext Services => Current.Services; @@ -63,7 +63,7 @@ namespace Umbraco.Web protected virtual void ConfigureMiddleware(IAppBuilder app) { - // Configure OWIN for authentication. + // Configure OWIN for authentication. ConfigureUmbracoAuthentication(app); app diff --git a/src/Umbraco.Web/UmbracoInjectedModule.cs b/src/Umbraco.Web/UmbracoInjectedModule.cs index 23d3e2fb5a..de05671fa1 100644 --- a/src/Umbraco.Web/UmbracoInjectedModule.cs +++ b/src/Umbraco.Web/UmbracoInjectedModule.cs @@ -99,7 +99,7 @@ namespace Umbraco.Web httpContext, _publishedSnapshotService, new WebSecurity(httpContext, _userService, _globalSettings), - UmbracoConfig.For.UmbracoSettings(), + Current.Config.Umbraco(), _urlProviders, _globalSettings, _variationContextAccessor, @@ -270,7 +270,7 @@ namespace Umbraco.Web ReportRuntime(level, "Umbraco is booting."); // let requests pile up and wait for 10s then show the splash anyway - if (UmbracoConfig.For.UmbracoSettings().Content.EnableSplashWhileLoading == false + if (Current.Config.Umbraco().Content.EnableSplashWhileLoading == false && ((RuntimeState) _runtime).WaitForRunLevel(TimeSpan.FromSeconds(10))) return true; // redirect to booting page diff --git a/src/Umbraco.Web/UmbracoModule.cs b/src/Umbraco.Web/UmbracoModule.cs index 555b65cd0f..e2cbcd260e 100644 --- a/src/Umbraco.Web/UmbracoModule.cs +++ b/src/Umbraco.Web/UmbracoModule.cs @@ -77,7 +77,7 @@ namespace Umbraco.Web else if (pcr.Is404) { response.StatusCode = 404; - response.TrySkipIisCustomErrors = UmbracoConfig.For.UmbracoSettings().WebRouting.TrySkipIisCustomErrors; + response.TrySkipIisCustomErrors = Current.Config.Umbraco().WebRouting.TrySkipIisCustomErrors; if (response.TrySkipIisCustomErrors == false) logger.Warn("Status code is 404 yet TrySkipIisCustomErrors is false - IIS will take over."); diff --git a/src/Umbraco.Web/UmbracoWebService.cs b/src/Umbraco.Web/UmbracoWebService.cs index fb789c92c2..852e0df470 100644 --- a/src/Umbraco.Web/UmbracoWebService.cs +++ b/src/Umbraco.Web/UmbracoWebService.cs @@ -29,7 +29,7 @@ namespace Umbraco.Web Logger = Current.Logger; ProfilingLogger = Current.ProfilingLogger; Services = Current.Services; - GlobalSettings = UmbracoConfig.For.GlobalSettings(); + GlobalSettings = Current.Config.Global(); } /// diff --git a/src/Umbraco.Web/WebApi/Filters/CheckIfUserTicketDataIsStaleAttribute.cs b/src/Umbraco.Web/WebApi/Filters/CheckIfUserTicketDataIsStaleAttribute.cs index ae51f37ef5..a1158126ea 100644 --- a/src/Umbraco.Web/WebApi/Filters/CheckIfUserTicketDataIsStaleAttribute.cs +++ b/src/Umbraco.Web/WebApi/Filters/CheckIfUserTicketDataIsStaleAttribute.cs @@ -76,7 +76,7 @@ namespace Umbraco.Web.WebApi.Filters () => user.Username != identity.Username, () => { - var culture = UserExtensions.GetUserCulture(user, Current.Services.TextService, UmbracoConfig.For.GlobalSettings()); + var culture = UserExtensions.GetUserCulture(user, Current.Services.TextService, Current.Config.Global()); return culture != null && culture.ToString() != identity.Culture; }, () => user.AllowedSections.UnsortedSequenceEqual(identity.AllowedApplications) == false, @@ -111,10 +111,10 @@ namespace Umbraco.Web.WebApi.Filters if (owinCtx) { var signInManager = owinCtx.Result.GetBackOfficeSignInManager(); - + var backOfficeIdentityUser = Mapper.Map(user); await signInManager.SignInAsync(backOfficeIdentityUser, isPersistent: true, rememberBrowser: false); - + //ensure the remainder of the request has the correct principal set actionContext.Request.SetPrincipalForRequest(owinCtx.Result.Request.User); diff --git a/src/Umbraco.Web/WebApi/Filters/SetAngularAntiForgeryTokensAttribute.cs b/src/Umbraco.Web/WebApi/Filters/SetAngularAntiForgeryTokensAttribute.cs index b55d6aaa4f..c75e223e1b 100644 --- a/src/Umbraco.Web/WebApi/Filters/SetAngularAntiForgeryTokensAttribute.cs +++ b/src/Umbraco.Web/WebApi/Filters/SetAngularAntiForgeryTokensAttribute.cs @@ -4,6 +4,7 @@ using System.Net.Http; using System.Net.Http.Headers; using System.Web.Helpers; using System.Web.Http.Filters; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; namespace Umbraco.Web.WebApi.Filters @@ -43,14 +44,14 @@ namespace Umbraco.Web.WebApi.Filters Path = "/", //must be js readable HttpOnly = false, - Secure = UmbracoConfig.For.GlobalSettings().UseHttps + Secure = Current.Config.Global().UseHttps }; var validationCookie = new CookieHeaderValue(AngularAntiForgeryHelper.CsrfValidationCookieName, cookieToken) { Path = "/", HttpOnly = true, - Secure = UmbracoConfig.For.GlobalSettings().UseHttps + Secure = Current.Config.Global().UseHttps }; context.Response.Headers.AddCookies(new[] { angularCookie, validationCookie }); diff --git a/src/Umbraco.Web/WebApi/Filters/UmbracoWebApiRequireHttpsAttribute.cs b/src/Umbraco.Web/WebApi/Filters/UmbracoWebApiRequireHttpsAttribute.cs index 560e5c0512..e1278b0b9f 100644 --- a/src/Umbraco.Web/WebApi/Filters/UmbracoWebApiRequireHttpsAttribute.cs +++ b/src/Umbraco.Web/WebApi/Filters/UmbracoWebApiRequireHttpsAttribute.cs @@ -4,6 +4,7 @@ using System.Net.Http; using System.Text; using System.Web.Http.Controllers; using System.Web.Http.Filters; +using Umbraco.Core.Composing; using Umbraco.Core.Configuration; namespace Umbraco.Web.WebApi.Filters @@ -23,7 +24,7 @@ namespace Umbraco.Web.WebApi.Filters public override void OnAuthorization(HttpActionContext actionContext) { var request = actionContext.Request; - if (UmbracoConfig.For.GlobalSettings().UseHttps && request.RequestUri.Scheme != Uri.UriSchemeHttps) + if (Current.Config.Global().UseHttps && request.RequestUri.Scheme != Uri.UriSchemeHttps) { HttpResponseMessage response; var uri = new UriBuilder(request.RequestUri) diff --git a/src/Umbraco.Web/umbraco.presentation/default.aspx.cs b/src/Umbraco.Web/umbraco.presentation/default.aspx.cs index 25dcae7a4e..c571c99ced 100644 --- a/src/Umbraco.Web/umbraco.presentation/default.aspx.cs +++ b/src/Umbraco.Web/umbraco.presentation/default.aspx.cs @@ -141,7 +141,7 @@ namespace umbraco if (pos > -1) { string htmlBadge = - string.Format(UmbracoConfig.For.UmbracoSettings().Content.PreviewBadge, + string.Format(Current.Config.Umbraco().Content.PreviewBadge, IOHelper.ResolveUrl(SystemDirectories.Umbraco), Server.UrlEncode(UmbracoContext.Current.HttpContext.Request.Path));